blob: 3243903863d9dbf5bcca4d5f9f4b53b9c8ab547a [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCalla020a012010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000030using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000032
John McCall9b72f892010-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 Gregorb7bfe792009-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 McCalle9cccd82010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000047
Douglas Gregorb7bfe792009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000049 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000050
Douglas Gregorb7bfe792009-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 Gregor568a0712009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000072
Douglas Gregorb7bfe792009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 return 0;
77}
78
John McCalle66edc12009-11-24 19:00:30 +000079static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000085 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor41f90302010-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 McCallbd8062d2010-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 Gregor41f90302010-04-12 20:54:26 +0000112 }
John McCalle66edc12009-11-24 19:00:30 +0000113 }
114 filter.done();
115}
116
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000118 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000119 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000120 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000121 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000122 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000125 assert(getLangOptions().CPlusPlus && "No template names in C!");
126
Douglas Gregor3cf81312009-11-03 23:16:33 +0000127 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000128 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-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
Alexis Hunted0530f2009-11-28 08:58:14 +0000140 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000143
Douglas Gregor3cf81312009-11-03 23:16:33 +0000144 default:
145 return TNK_Non_template;
146 }
Mike Stump11289f42009-09-09 15:08:12 +0000147
John McCallba7bf592010-08-24 05:47:05 +0000148 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000149
Douglas Gregorff18cc12009-12-31 08:11:17 +0000150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-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 McCalldcc71402010-08-13 02:23:42 +0000157 R.suppressDiagnostics();
John McCallfb3f9ba2010-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 Gregorb7bfe792009-09-02 22:59:36 +0000161 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000162 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000163
John McCalld28ae272009-12-02 08:04:21 +0000164 TemplateName Template;
165 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000166
John McCalld28ae272009-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 McCalldcc71402010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000176 } else {
John McCalld28ae272009-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 Bagnara7c5dee42010-08-06 12:11:11 +0000182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000184 } else {
185 Template = TemplateName(TD);
186 }
187
John McCalldcc71402010-08-13 02:23:42 +0000188 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000189 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
John McCalld28ae272009-12-02 08:04:21 +0000194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
196 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000197 }
Mike Stump11289f42009-09-09 15:08:12 +0000198
John McCalld28ae272009-12-02 08:04:21 +0000199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000201}
202
Douglas Gregor18473f32010-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 Gregor20c38a72010-05-21 23:43:39 +0000211 // FIXME: Typo correction?
Douglas Gregor18473f32010-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 Gregora771f462010-03-31 17:46:05 +0000221 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-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 McCalle66edc12009-11-24 19:00:30 +0000228void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000229 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000230 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000233 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000234 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-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 McCall0b66eb32010-05-01 00:40:08 +0000252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-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 McCalle66edc12009-11-24 19:00:30 +0000274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
276 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000277 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000278 // We cannot look into a dependent object type or nested nme
279 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000280 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-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 Gregorc119dd52010-01-12 17:06:20 +0000287 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000291 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000292 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000293 if (!Found.empty()) {
Douglas Gregorff18cc12009-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 Gregora771f462010-03-31 17:46:05 +0000297 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-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 Gregora771f462010-03-31 17:46:05 +0000302 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000303 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000307 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000308 } else {
309 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000310 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000311 }
312 }
313
John McCalle66edc12009-11-24 19:00:30 +0000314 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000318 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000319 }
John McCalle66edc12009-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 Gregor41f90302010-04-12 20:54:26 +0000331
John McCalle66edc12009-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 McCalle9cccd82010-06-16 08:42:20 +0000339 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-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 Yasskin2f96e9f2010-06-05 01:39:57 +0000347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
John McCalle66edc12009-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 McCallcd4b4772009-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 McCalldadc5752010-08-24 06:29:42 +0000366ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000368 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000369 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000373
374 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000375
John McCallcd4b4772009-12-02 03:53:29 +0000376 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000380
John McCalle66edc12009-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 McCall2d74de92009-12-01 22:10:20 +0000385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000391 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000392 TemplateArgs));
393 }
394
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000396}
397
John McCalldadc5752010-08-24 06:29:42 +0000398ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000399Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000400 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-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 Bagnarad6d2f182010-08-11 22:01:17 +0000405 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000406 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000407}
408
Douglas Gregor5101c242008-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 Gregor5daeee22008-12-08 18:40:42 +0000414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-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 Stump11289f42009-09-09 15:08:12 +0000423 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-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 Gregor463421d2009-03-03 04:44:36 +0000429/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-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 McCall48871652010-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 Gregorded2d7b2009-02-04 19:02:06 +0000435 return Temp;
436 }
437 return 0;
438}
439
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000440static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
441 const ParsedTemplateArgument &Arg) {
442
443 switch (Arg.getKind()) {
444 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000445 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000446 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
447 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000448 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-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 McCall3e56fd42010-08-23 07:28:44 +0000458 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000459 return TemplateArgumentLoc(TemplateArgument(Template),
460 Arg.getScopeSpec().getRange(),
461 Arg.getLocation());
462 }
463 }
464
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000465 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-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 McCall6b51f282009-11-23 01:53:49 +0000471void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
472 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000473 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000474 TemplateArgs.addArgument(translateTemplateArgument(*this,
475 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000476}
477
Douglas Gregor5101c242008-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 Gregor2ebcae12010-06-16 15:23:05 +0000484/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000485/// If the type parameter has a default argument, it will be added
486/// later via ActOnTypeParameterDefault.
John McCall48871652010-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 McCallba7bf592010-08-24 05:47:05 +0000494 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000495 assert(S->isTemplateParamScope() &&
496 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000497 bool Invalid = false;
498
499 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000500 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000501 LookupOrdinaryName,
502 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000503 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000504 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000505 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000506 }
507
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000508 SourceLocation Loc = ParamNameLoc;
509 if (!ParamName)
510 Loc = KeyLoc;
511
Douglas Gregor5101c242008-12-05 18:15:24 +0000512 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000513 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
514 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000515 Ellipsis);
Douglas Gregor5101c242008-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 McCall48871652010-08-21 09:40:31 +0000521 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000522 IdResolver.AddDecl(Param);
523 }
524
Douglas Gregordc13ded2010-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 McCall48871652010-08-21 09:40:31 +0000537 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000538 }
539
540 // Check the template argument itself.
541 if (CheckTemplateArgument(Param, DefaultTInfo)) {
542 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000543 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000544 }
545
546 Param->setDefaultArgument(DefaultTInfo, false);
547 }
548
John McCall48871652010-08-21 09:40:31 +0000549 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000550}
551
Douglas Gregor463421d2009-03-03 04:44:36 +0000552/// \brief Check that the type of a non-type template parameter is
553/// well-formed.
554///
555/// \returns the (possibly-promoted) parameter type if valid;
556/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000557QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000558Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000559 // We don't allow variably-modified types as the type of non-type template
560 // parameters.
561 if (T->isVariablyModifiedType()) {
562 Diag(Loc, diag::err_variably_modified_nontype_template_param)
563 << T;
564 return QualType();
565 }
566
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 // C++ [temp.param]p4:
568 //
569 // A non-type template-parameter shall have one of the following
570 // (optionally cv-qualified) types:
571 //
572 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000573 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000574 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000575 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000576 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000577 T->isReferenceType() ||
578 // -- pointer to member.
579 T->isMemberPointerType() ||
580 // If T is a dependent type, we can't do the check now, so we
581 // assume that it is well-formed.
582 T->isDependentType())
583 return T;
584 // C++ [temp.param]p8:
585 //
586 // A non-type template-parameter of type "array of T" or
587 // "function returning T" is adjusted to be of type "pointer to
588 // T" or "pointer to function returning T", respectively.
589 else if (T->isArrayType())
590 // FIXME: Keep the type prior to promotion?
591 return Context.getArrayDecayedType(T);
592 else if (T->isFunctionType())
593 // FIXME: Keep the type prior to promotion?
594 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000595
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 Diag(Loc, diag::err_template_nontype_parm_bad_type)
597 << T;
598
599 return QualType();
600}
601
John McCall48871652010-08-21 09:40:31 +0000602Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
603 unsigned Depth,
604 unsigned Position,
605 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000606 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000607 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
608 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000609
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000610 assert(S->isTemplateParamScope() &&
611 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000612 bool Invalid = false;
613
614 IdentifierInfo *ParamName = D.getIdentifier();
615 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000616 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000617 LookupOrdinaryName,
618 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000619 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000620 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000621 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000622 }
623
Douglas Gregor463421d2009-03-03 04:44:36 +0000624 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000625 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000627 Invalid = true;
628 }
Douglas Gregor81338792009-02-10 17:43:50 +0000629
Douglas Gregor5101c242008-12-05 18:15:24 +0000630 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000631 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
632 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000633 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000634 if (Invalid)
635 Param->setInvalidDecl();
636
637 if (D.getIdentifier()) {
638 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000639 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000640 IdResolver.AddDecl(Param);
641 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000642
643 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000644 if (Default) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000645 TemplateArgument Converted;
646 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
647 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000648 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000649 }
650
John McCallb268a282010-08-23 23:25:46 +0000651 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000652 }
653
John McCall48871652010-08-21 09:40:31 +0000654 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000655}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000656
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000657/// ActOnTemplateTemplateParameter - Called when a C++ template template
658/// parameter (e.g. T in template <template <typename> class T> class array)
659/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000660Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
661 SourceLocation TmpLoc,
662 TemplateParamsTy *Params,
663 IdentifierInfo *Name,
664 SourceLocation NameLoc,
665 unsigned Depth,
666 unsigned Position,
667 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000668 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000669 assert(S->isTemplateParamScope() &&
670 "Template template parameter not in template parameter scope!");
671
672 // Construct the parameter object.
673 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000674 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregor713602b2010-08-31 17:01:39 +0000675 NameLoc.isInvalid()? TmpLoc : NameLoc,
676 Depth, Position, Name,
Douglas Gregora02bb372010-10-21 17:26:49 +0000677 Params);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000678
Douglas Gregordc13ded2010-07-01 00:00:45 +0000679 // If the template template parameter has a name, then link the identifier
680 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000681 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000682 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000683 IdResolver.AddDecl(Param);
684 }
685
Douglas Gregordc13ded2010-07-01 00:00:45 +0000686 if (!Default.isInvalid()) {
687 // Check only that we have a template template argument. We don't want to
688 // try to check well-formedness now, because our template template parameter
689 // might have dependent types in its template parameters, which we wouldn't
690 // be able to match now.
691 //
692 // If none of the template template parameter's template arguments mention
693 // other template parameters, we could actually perform more checking here.
694 // However, it isn't worth doing.
695 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
696 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
697 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
698 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000699 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000700 }
701
702 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000703 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000704
Douglas Gregora02bb372010-10-21 17:26:49 +0000705 if (Params->size() == 0) {
706 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
707 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
708 Param->setInvalidDecl();
709 }
John McCall48871652010-08-21 09:40:31 +0000710 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000711}
712
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000713/// ActOnTemplateParameterList - Builds a TemplateParameterList that
714/// contains the template parameters in Params/NumParams.
715Sema::TemplateParamsTy *
716Sema::ActOnTemplateParameterList(unsigned Depth,
717 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000718 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000719 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000720 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000721 SourceLocation RAngleLoc) {
722 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000723 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000724
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000725 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000726 (NamedDecl**)Params, NumParams,
727 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000728}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000729
John McCall3e11ebe2010-03-15 10:12:16 +0000730static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
731 if (SS.isSet())
732 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
733 SS.getRange());
734}
735
John McCallfaf5fb42010-08-26 23:41:50 +0000736DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000737Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000738 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000739 IdentifierInfo *Name, SourceLocation NameLoc,
740 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000741 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000742 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000743 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000744 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000745 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000746 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000747
748 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000750 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000751
Abramo Bagnara6150c882010-05-11 21:36:43 +0000752 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
753 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000754
755 // There is no such thing as an unnamed class template.
756 if (!Name) {
757 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000758 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759 }
760
761 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000762 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000763 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000764 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000765 if (SS.isNotEmpty() && !SS.isInvalid()) {
766 SemanticContext = computeDeclContext(SS, true);
767 if (!SemanticContext) {
768 // FIXME: Produce a reasonable diagnostic here
769 return true;
770 }
Mike Stump11289f42009-09-09 15:08:12 +0000771
John McCall0b66eb32010-05-01 00:40:08 +0000772 if (RequireCompleteDeclContext(SS, SemanticContext))
773 return true;
774
John McCall27b18f82009-11-17 02:14:36 +0000775 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000776 } else {
777 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000778 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000781 if (Previous.isAmbiguous())
782 return true;
783
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000784 NamedDecl *PrevDecl = 0;
785 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000786 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000787
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000788 // If there is a previous declaration with the same name, check
789 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000790 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000791 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000792
793 // We may have found the injected-class-name of a class template,
794 // class template partial specialization, or class template specialization.
795 // In these cases, grab the template that is being defined or specialized.
796 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
797 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
798 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
799 PrevClassTemplate
800 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
801 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
802 PrevClassTemplate
803 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
804 ->getSpecializedTemplate();
805 }
806 }
807
John McCalld43784f2009-12-18 11:25:59 +0000808 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000809 // C++ [namespace.memdef]p3:
810 // [...] When looking for a prior declaration of a class or a function
811 // declared as a friend, and when the name of the friend class or
812 // function is neither a qualified name nor a template-id, scopes outside
813 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000814 if (!SS.isSet()) {
815 DeclContext *OutermostContext = CurContext;
816 while (!OutermostContext->isFileContext())
817 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000818
Douglas Gregorb74b1032010-04-18 17:37:40 +0000819 if (PrevDecl &&
820 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
821 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
822 SemanticContext = PrevDecl->getDeclContext();
823 } else {
824 // Declarations in outer scopes don't matter. However, the outermost
825 // context we computed is the semantic context for our new
826 // declaration.
827 PrevDecl = PrevClassTemplate = 0;
828 SemanticContext = OutermostContext;
829 }
John McCall90d3bb92009-12-17 23:21:11 +0000830 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000831
John McCall90d3bb92009-12-17 23:21:11 +0000832 if (CurContext->isDependentContext()) {
833 // If this is a dependent context, we don't want to link the friend
834 // class template to the template in scope, because that would perform
835 // checking of the template parameter lists that can't be performed
836 // until the outer context is instantiated.
837 PrevDecl = PrevClassTemplate = 0;
838 }
839 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
840 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000841
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000842 if (PrevClassTemplate) {
843 // Ensure that the template parameter lists are compatible.
844 if (!TemplateParameterListsAreEqual(TemplateParams,
845 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000846 /*Complain=*/true,
847 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000848 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849
850 // C++ [temp.class]p4:
851 // In a redeclaration, partial specialization, explicit
852 // specialization or explicit instantiation of a class template,
853 // the class-key shall agree in kind with the original class
854 // template declaration (7.1.5.3).
855 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000856 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000857 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000858 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000859 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000860 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000861 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000862 }
863
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000864 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000865 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000866 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000867 Diag(NameLoc, diag::err_redefinition) << Name;
868 Diag(Def->getLocation(), diag::note_previous_definition);
869 // FIXME: Would it make sense to try to "forget" the previous
870 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000871 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000872 }
873 }
874 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
875 // Maybe we will complain about the shadowed template parameter.
876 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
877 // Just pretend that we didn't see the previous declaration.
878 PrevDecl = 0;
879 } else if (PrevDecl) {
880 // C++ [temp]p5:
881 // A class template shall not have the same name as any other
882 // template, class, function, object, enumeration, enumerator,
883 // namespace, or type in the same scope (3.3), except as specified
884 // in (14.5.4).
885 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
886 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000887 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000888 }
889
Douglas Gregordba32632009-02-10 19:49:53 +0000890 // Check the template parameter list of this declaration, possibly
891 // merging in the template parameter list from the previous class
892 // template declaration.
893 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000894 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
895 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000896 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000898 if (SS.isSet()) {
899 // If the name of the template was qualified, we must be defining the
900 // template out-of-line.
901 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
902 !(TUK == TUK_Friend && CurContext->isDependentContext()))
903 Diag(NameLoc, diag::err_member_def_does_not_match)
904 << Name << SemanticContext << SS.getRange();
905 }
906
Mike Stump11289f42009-09-09 15:08:12 +0000907 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000908 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000909 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000910 PrevClassTemplate->getTemplatedDecl() : 0,
911 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000912 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000913
914 ClassTemplateDecl *NewTemplate
915 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
916 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000917 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000918 NewClass->setDescribedClassTemplate(NewTemplate);
919
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000920 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000921 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000922 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000923 assert(T->isDependentType() && "Class template type is not dependent?");
924 (void)T;
925
Douglas Gregorcf915552009-10-13 16:30:37 +0000926 // If we are providing an explicit specialization of a member that is a
927 // class template, make a note of that.
928 if (PrevClassTemplate &&
929 PrevClassTemplate->getInstantiatedFromMemberTemplate())
930 PrevClassTemplate->setMemberSpecialization();
931
Anders Carlsson137108d2009-03-26 01:24:28 +0000932 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000933 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000934 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000935
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000936 // Set the lexical context of these templates
937 NewClass->setLexicalDeclContext(CurContext);
938 NewTemplate->setLexicalDeclContext(CurContext);
939
John McCall9bb74a52009-07-31 02:45:11 +0000940 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000941 NewClass->startDefinition();
942
943 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000944 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000945
John McCall27b5c252009-09-14 21:59:20 +0000946 if (TUK != TUK_Friend)
947 PushOnScopeChains(NewTemplate, S);
948 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000949 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000950 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000951 NewClass->setAccess(PrevClassTemplate->getAccess());
952 }
John McCall27b5c252009-09-14 21:59:20 +0000953
Douglas Gregor3dad8422009-09-26 06:47:28 +0000954 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
955 PrevClassTemplate != NULL);
956
John McCall27b5c252009-09-14 21:59:20 +0000957 // Friend templates are visible in fairly strange ways.
958 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000959 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall27b5c252009-09-14 21:59:20 +0000960 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
961 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
962 PushOnScopeChains(NewTemplate, EnclosingScope,
963 /* AddToContext = */ false);
964 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000965
966 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
967 NewClass->getLocation(),
968 NewTemplate,
969 /*FIXME:*/NewClass->getLocation());
970 Friend->setAccess(AS_public);
971 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000972 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000973
Douglas Gregordba32632009-02-10 19:49:53 +0000974 if (Invalid) {
975 NewTemplate->setInvalidDecl();
976 NewClass->setInvalidDecl();
977 }
John McCall48871652010-08-21 09:40:31 +0000978 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000979}
980
Douglas Gregored5731f2009-11-25 17:50:39 +0000981/// \brief Diagnose the presence of a default template argument on a
982/// template parameter, which is ill-formed in certain contexts.
983///
984/// \returns true if the default template argument should be dropped.
985static bool DiagnoseDefaultTemplateArgument(Sema &S,
986 Sema::TemplateParamListContext TPC,
987 SourceLocation ParamLoc,
988 SourceRange DefArgRange) {
989 switch (TPC) {
990 case Sema::TPC_ClassTemplate:
991 return false;
992
993 case Sema::TPC_FunctionTemplate:
994 // C++ [temp.param]p9:
995 // A default template-argument shall not be specified in a
996 // function template declaration or a function template
997 // definition [...]
998 // (This sentence is not in C++0x, per DR226).
999 if (!S.getLangOptions().CPlusPlus0x)
1000 S.Diag(ParamLoc,
1001 diag::err_template_parameter_default_in_function_template)
1002 << DefArgRange;
1003 return false;
1004
1005 case Sema::TPC_ClassTemplateMember:
1006 // C++0x [temp.param]p9:
1007 // A default template-argument shall not be specified in the
1008 // template-parameter-lists of the definition of a member of a
1009 // class template that appears outside of the member's class.
1010 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1011 << DefArgRange;
1012 return true;
1013
1014 case Sema::TPC_FriendFunctionTemplate:
1015 // C++ [temp.param]p9:
1016 // A default template-argument shall not be specified in a
1017 // friend template declaration.
1018 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1019 << DefArgRange;
1020 return true;
1021
1022 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1023 // for friend function templates if there is only a single
1024 // declaration (and it is a definition). Strange!
1025 }
1026
1027 return false;
1028}
1029
Douglas Gregordba32632009-02-10 19:49:53 +00001030/// \brief Checks the validity of a template parameter list, possibly
1031/// considering the template parameter list from a previous
1032/// declaration.
1033///
1034/// If an "old" template parameter list is provided, it must be
1035/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1036/// template parameter list.
1037///
1038/// \param NewParams Template parameter list for a new template
1039/// declaration. This template parameter list will be updated with any
1040/// default arguments that are carried through from the previous
1041/// template parameter list.
1042///
1043/// \param OldParams If provided, template parameter list from a
1044/// previous declaration of the same template. Default template
1045/// arguments will be merged from the old template parameter list to
1046/// the new template parameter list.
1047///
Douglas Gregored5731f2009-11-25 17:50:39 +00001048/// \param TPC Describes the context in which we are checking the given
1049/// template parameter list.
1050///
Douglas Gregordba32632009-02-10 19:49:53 +00001051/// \returns true if an error occurred, false otherwise.
1052bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001053 TemplateParameterList *OldParams,
1054 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001055 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001056
Douglas Gregordba32632009-02-10 19:49:53 +00001057 // C++ [temp.param]p10:
1058 // The set of default template-arguments available for use with a
1059 // template declaration or definition is obtained by merging the
1060 // default arguments from the definition (if in scope) and all
1061 // declarations in scope in the same way default function
1062 // arguments are (8.3.6).
1063 bool SawDefaultArgument = false;
1064 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001065
Anders Carlsson327865d2009-06-12 23:20:15 +00001066 bool SawParameterPack = false;
1067 SourceLocation ParameterPackLoc;
1068
Mike Stumpc89c8e32009-02-11 23:03:27 +00001069 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001070 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001071 if (OldParams)
1072 OldParam = OldParams->begin();
1073
1074 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1075 NewParamEnd = NewParams->end();
1076 NewParam != NewParamEnd; ++NewParam) {
1077 // Variables used to diagnose redundant default arguments
1078 bool RedundantDefaultArg = false;
1079 SourceLocation OldDefaultLoc;
1080 SourceLocation NewDefaultLoc;
1081
1082 // Variables used to diagnose missing default arguments
1083 bool MissingDefaultArg = false;
1084
Anders Carlsson327865d2009-06-12 23:20:15 +00001085 // C++0x [temp.param]p11:
1086 // If a template parameter of a class template is a template parameter pack,
1087 // it must be the last template parameter.
1088 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001089 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001090 diag::err_template_param_pack_must_be_last_template_parameter);
1091 Invalid = true;
1092 }
1093
Douglas Gregordba32632009-02-10 19:49:53 +00001094 if (TemplateTypeParmDecl *NewTypeParm
1095 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001096 // Check the presence of a default argument here.
1097 if (NewTypeParm->hasDefaultArgument() &&
1098 DiagnoseDefaultTemplateArgument(*this, TPC,
1099 NewTypeParm->getLocation(),
1100 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001101 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001102 NewTypeParm->removeDefaultArgument();
1103
1104 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001105 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001106 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Anders Carlsson327865d2009-06-12 23:20:15 +00001108 if (NewTypeParm->isParameterPack()) {
1109 assert(!NewTypeParm->hasDefaultArgument() &&
1110 "Parameter packs can't have a default argument!");
1111 SawParameterPack = true;
1112 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001113 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001114 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001115 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1116 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1117 SawDefaultArgument = true;
1118 RedundantDefaultArg = true;
1119 PreviousDefaultArgLoc = NewDefaultLoc;
1120 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1121 // Merge the default argument from the old declaration to the
1122 // new declaration.
1123 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001124 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001125 true);
1126 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1127 } else if (NewTypeParm->hasDefaultArgument()) {
1128 SawDefaultArgument = true;
1129 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1130 } else if (SawDefaultArgument)
1131 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001132 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001133 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001134 // Check the presence of a default argument here.
1135 if (NewNonTypeParm->hasDefaultArgument() &&
1136 DiagnoseDefaultTemplateArgument(*this, TPC,
1137 NewNonTypeParm->getLocation(),
1138 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001139 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001140 }
1141
Mike Stump12b8ce12009-08-04 21:02:39 +00001142 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001143 NonTypeTemplateParmDecl *OldNonTypeParm
1144 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001145 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001146 NewNonTypeParm->hasDefaultArgument()) {
1147 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1148 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1149 SawDefaultArgument = true;
1150 RedundantDefaultArg = true;
1151 PreviousDefaultArgLoc = NewDefaultLoc;
1152 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1153 // Merge the default argument from the old declaration to the
1154 // new declaration.
1155 SawDefaultArgument = true;
1156 // FIXME: We need to create a new kind of "default argument"
1157 // expression that points to a previous template template
1158 // parameter.
1159 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001160 OldNonTypeParm->getDefaultArgument(),
1161 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001162 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1163 } else if (NewNonTypeParm->hasDefaultArgument()) {
1164 SawDefaultArgument = true;
1165 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1166 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001167 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001168 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001169 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001170 TemplateTemplateParmDecl *NewTemplateParm
1171 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001172 if (NewTemplateParm->hasDefaultArgument() &&
1173 DiagnoseDefaultTemplateArgument(*this, TPC,
1174 NewTemplateParm->getLocation(),
1175 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001176 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001177
1178 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001179 TemplateTemplateParmDecl *OldTemplateParm
1180 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001181 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001182 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001183 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1184 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001185 SawDefaultArgument = true;
1186 RedundantDefaultArg = true;
1187 PreviousDefaultArgLoc = NewDefaultLoc;
1188 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1189 // Merge the default argument from the old declaration to the
1190 // new declaration.
1191 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001192 // FIXME: We need to create a new kind of "default argument" expression
1193 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001194 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001195 OldTemplateParm->getDefaultArgument(),
1196 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001197 PreviousDefaultArgLoc
1198 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001199 } else if (NewTemplateParm->hasDefaultArgument()) {
1200 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001201 PreviousDefaultArgLoc
1202 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001203 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001204 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001205 }
1206
1207 if (RedundantDefaultArg) {
1208 // C++ [temp.param]p12:
1209 // A template-parameter shall not be given default arguments
1210 // by two different declarations in the same scope.
1211 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1212 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1213 Invalid = true;
1214 } else if (MissingDefaultArg) {
1215 // C++ [temp.param]p11:
1216 // If a template-parameter has a default template-argument,
1217 // all subsequent template-parameters shall have a default
1218 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001219 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001220 diag::err_template_param_default_arg_missing);
1221 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1222 Invalid = true;
1223 }
1224
1225 // If we have an old template parameter list that we're merging
1226 // in, move on to the next parameter.
1227 if (OldParams)
1228 ++OldParam;
1229 }
1230
1231 return Invalid;
1232}
Douglas Gregord32e0282009-02-09 23:23:08 +00001233
John McCalla020a012010-10-20 05:44:58 +00001234namespace {
1235
1236/// A class which looks for a use of a certain level of template
1237/// parameter.
1238struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1239 typedef RecursiveASTVisitor<DependencyChecker> super;
1240
1241 unsigned Depth;
1242 bool Match;
1243
1244 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1245 NamedDecl *ND = Params->getParam(0);
1246 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1247 Depth = PD->getDepth();
1248 } else if (NonTypeTemplateParmDecl *PD =
1249 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1250 Depth = PD->getDepth();
1251 } else {
1252 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1253 }
1254 }
1255
1256 bool Matches(unsigned ParmDepth) {
1257 if (ParmDepth >= Depth) {
1258 Match = true;
1259 return true;
1260 }
1261 return false;
1262 }
1263
1264 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1265 return !Matches(T->getDepth());
1266 }
1267
1268 bool TraverseTemplateName(TemplateName N) {
1269 if (TemplateTemplateParmDecl *PD =
1270 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1271 if (Matches(PD->getDepth())) return false;
1272 return super::TraverseTemplateName(N);
1273 }
1274
1275 bool VisitDeclRefExpr(DeclRefExpr *E) {
1276 if (NonTypeTemplateParmDecl *PD =
1277 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1278 if (PD->getDepth() == Depth) {
1279 Match = true;
1280 return false;
1281 }
1282 }
1283 return super::VisitDeclRefExpr(E);
1284 }
1285};
1286}
1287
1288/// Determines whether a template-id depends on the given parameter
1289/// list.
1290static bool
1291DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1292 TemplateParameterList *Params) {
1293 DependencyChecker Checker(Params);
1294 Checker.TraverseType(QualType(TemplateId, 0));
1295 return Checker.Match;
1296}
1297
Mike Stump11289f42009-09-09 15:08:12 +00001298/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001299/// specifier, returning the template parameter list that applies to the
1300/// name.
1301///
1302/// \param DeclStartLoc the start of the declaration that has a scope
1303/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001304///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001305/// \param SS the scope specifier that will be matched to the given template
1306/// parameter lists. This scope specifier precedes a qualified name that is
1307/// being declared.
1308///
1309/// \param ParamLists the template parameter lists, from the outermost to the
1310/// innermost template parameter lists.
1311///
1312/// \param NumParamLists the number of template parameter lists in ParamLists.
1313///
John McCalle820e5e2010-04-13 20:37:33 +00001314/// \param IsFriend Whether to apply the slightly different rules for
1315/// matching template parameters to scope specifiers in friend
1316/// declarations.
1317///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001318/// \param IsExplicitSpecialization will be set true if the entity being
1319/// declared is an explicit specialization, false otherwise.
1320///
Mike Stump11289f42009-09-09 15:08:12 +00001321/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001322/// name that is preceded by the scope specifier @p SS. This template
1323/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001324/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001325/// template specialization), or may be NULL (if we were's declaring isn't
1326/// itself a template).
1327TemplateParameterList *
1328Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1329 const CXXScopeSpec &SS,
1330 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001331 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001332 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001333 bool &IsExplicitSpecialization,
1334 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001335 IsExplicitSpecialization = false;
1336
Douglas Gregord8d297c2009-07-21 23:53:31 +00001337 // Find the template-ids that occur within the nested-name-specifier. These
1338 // template-ids will match up with the template parameter lists.
1339 llvm::SmallVector<const TemplateSpecializationType *, 4>
1340 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001341 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1342 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001343 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1344 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001345 const Type *T = NNS->getAsType();
1346 if (!T) break;
1347
1348 // C++0x [temp.expl.spec]p17:
1349 // A member or a member template may be nested within many
1350 // enclosing class templates. In an explicit specialization for
1351 // such a member, the member declaration shall be preceded by a
1352 // template<> for each enclosing class template that is
1353 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001354 //
1355 // Following the existing practice of GNU and EDG, we allow a typedef of a
1356 // template specialization type.
1357 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1358 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001359
Mike Stump11289f42009-09-09 15:08:12 +00001360 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001361 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001362 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1363 if (!Template)
1364 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001365
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001367 ClassTemplateSpecializationDecl *SpecDecl
1368 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1369 // If the nested name specifier refers to an explicit specialization,
1370 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001371 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1372 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001373 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001374 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001375 }
Mike Stump11289f42009-09-09 15:08:12 +00001376
Douglas Gregord8d297c2009-07-21 23:53:31 +00001377 TemplateIdsInSpecifier.push_back(SpecType);
1378 }
1379 }
Mike Stump11289f42009-09-09 15:08:12 +00001380
Douglas Gregord8d297c2009-07-21 23:53:31 +00001381 // Reverse the list of template-ids in the scope specifier, so that we can
1382 // more easily match up the template-ids and the template parameter lists.
1383 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001384
Douglas Gregord8d297c2009-07-21 23:53:31 +00001385 SourceLocation FirstTemplateLoc = DeclStartLoc;
1386 if (NumParamLists)
1387 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001388
Douglas Gregord8d297c2009-07-21 23:53:31 +00001389 // Match the template-ids found in the specifier to the template parameter
1390 // lists.
John McCalla020a012010-10-20 05:44:58 +00001391 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001392 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCalla020a012010-10-20 05:44:58 +00001393 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1394 const TemplateSpecializationType *TemplateId
1395 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregor15301382009-07-30 17:40:51 +00001396 bool DependentTemplateId = TemplateId->isDependentType();
John McCalla020a012010-10-20 05:44:58 +00001397
1398 // In friend declarations we can have template-ids which don't
1399 // depend on the corresponding template parameter lists. But
1400 // assume that empty parameter lists are supposed to match this
1401 // template-id.
1402 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1403 if (!DependentTemplateId ||
1404 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1405 continue;
1406 }
1407
1408 if (ParamIdx >= NumParamLists) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001409 // We have a template-id without a corresponding template parameter
1410 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001411
1412 // ...which is fine if this is a friend declaration.
1413 if (IsFriend) {
1414 IsExplicitSpecialization = true;
1415 break;
1416 }
1417
Douglas Gregord8d297c2009-07-21 23:53:31 +00001418 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001419 // FIXME: the location information here isn't great.
1420 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001421 diag::err_template_spec_needs_template_parameters)
John McCalla020a012010-10-20 05:44:58 +00001422 << QualType(TemplateId, 0)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001423 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001424 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001425 } else {
1426 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1427 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001428 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001429 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001430 }
1431 return 0;
1432 }
Mike Stump11289f42009-09-09 15:08:12 +00001433
Douglas Gregord8d297c2009-07-21 23:53:31 +00001434 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001435 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001436 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001437
John McCall2408e322010-04-27 00:57:59 +00001438 // Are there cases in (e.g.) friends where this won't match?
1439 if (const InjectedClassNameType *Injected
1440 = TemplateId->getAs<InjectedClassNameType>()) {
1441 CXXRecordDecl *Record = Injected->getDecl();
1442 if (ClassTemplatePartialSpecializationDecl *Partial =
1443 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1444 ExpectedTemplateParams = Partial->getTemplateParameters();
1445 else
1446 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1447 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001448 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001449
John McCall2408e322010-04-27 00:57:59 +00001450 if (ExpectedTemplateParams)
John McCalla020a012010-10-20 05:44:58 +00001451 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall2408e322010-04-27 00:57:59 +00001452 ExpectedTemplateParams,
1453 true, TPL_TemplateMatch);
1454
John McCalla020a012010-10-20 05:44:58 +00001455 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1456 TPC_ClassTemplateMember);
1457 } else if (ParamLists[ParamIdx]->size() > 0)
1458 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001459 diag::err_template_param_list_matches_nontemplate)
1460 << TemplateId
John McCalla020a012010-10-20 05:44:58 +00001461 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001462 else
1463 IsExplicitSpecialization = true;
John McCalla020a012010-10-20 05:44:58 +00001464
1465 ++ParamIdx;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001466 }
Mike Stump11289f42009-09-09 15:08:12 +00001467
Douglas Gregord8d297c2009-07-21 23:53:31 +00001468 // If there were at least as many template-ids as there were template
1469 // parameter lists, then there are no template parameter lists remaining for
1470 // the declaration itself.
John McCalla020a012010-10-20 05:44:58 +00001471 if (ParamIdx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001472 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001473
Douglas Gregord8d297c2009-07-21 23:53:31 +00001474 // If there were too many template parameter lists, complain about that now.
John McCalla020a012010-10-20 05:44:58 +00001475 if (ParamIdx != NumParamLists - 1) {
1476 while (ParamIdx < NumParamLists - 1) {
1477 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1478 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001479 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1480 : diag::err_template_spec_extra_headers)
John McCalla020a012010-10-20 05:44:58 +00001481 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1482 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001483
1484 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1485 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1486 diag::note_explicit_template_spec_does_not_need_header)
1487 << ExplicitSpecializationsInSpecifier.back();
1488 ExplicitSpecializationsInSpecifier.pop_back();
1489 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001490
1491 // We have a template parameter list with no corresponding scope, which
1492 // means that the resulting template declaration can't be instantiated
1493 // properly (we'll end up with dependent nodes when we shouldn't).
1494 if (!isExplicitSpecHeader)
1495 Invalid = true;
1496
John McCalla020a012010-10-20 05:44:58 +00001497 ++ParamIdx;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001498 }
1499 }
Mike Stump11289f42009-09-09 15:08:12 +00001500
Douglas Gregord8d297c2009-07-21 23:53:31 +00001501 // Return the last template parameter list, which corresponds to the
1502 // entity being declared.
1503 return ParamLists[NumParamLists - 1];
1504}
1505
Douglas Gregordc572a32009-03-30 22:58:21 +00001506QualType Sema::CheckTemplateIdType(TemplateName Name,
1507 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001508 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001509 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001510 if (!Template) {
1511 // The template name does not resolve to a template, so we just
1512 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001513 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001514 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001515
Douglas Gregorc40290e2009-03-09 23:48:35 +00001516 // Check that the template argument list is well-formed for this
1517 // template.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001518 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00001519 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001520 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001521 return QualType();
1522
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001523 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001524 "Converted template argument list is too short!");
1525
1526 QualType CanonType;
1527
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001528 if (Name.isDependent() ||
1529 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001530 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001531 // This class template specialization is a dependent
1532 // type. Therefore, its canonical type is another class template
1533 // specialization type that contains all of the converted
1534 // arguments in canonical form. This ensures that, e.g., A<T> and
1535 // A<T, T> have identical types when A is declared as:
1536 //
1537 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001538 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001539 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001540 Converted.data(),
1541 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00001542
Douglas Gregora8e02e72009-07-28 23:00:59 +00001543 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001544 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001545 // In the future, we need to teach getTemplateSpecializationType to only
1546 // build the canonical type and return that to us.
1547 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001548
1549 // This might work out to be a current instantiation, in which
1550 // case the canonical type needs to be the InjectedClassNameType.
1551 //
1552 // TODO: in theory this could be a simple hashtable lookup; most
1553 // changes to CurContext don't change the set of current
1554 // instantiations.
1555 if (isa<ClassTemplateDecl>(Template)) {
1556 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1557 // If we get out to a namespace, we're done.
1558 if (Ctx->isFileContext()) break;
1559
1560 // If this isn't a record, keep looking.
1561 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1562 if (!Record) continue;
1563
1564 // Look for one of the two cases with InjectedClassNameTypes
1565 // and check whether it's the same template.
1566 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1567 !Record->getDescribedClassTemplate())
1568 continue;
1569
1570 // Fetch the injected class name type and check whether its
1571 // injected type is equal to the type we just built.
1572 QualType ICNT = Context.getTypeDeclType(Record);
1573 QualType Injected = cast<InjectedClassNameType>(ICNT)
1574 ->getInjectedSpecializationType();
1575
1576 if (CanonType != Injected->getCanonicalTypeInternal())
1577 continue;
1578
1579 // If so, the canonical type of this TST is the injected
1580 // class name type of the record we just found.
1581 assert(ICNT.isCanonical());
1582 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001583 break;
1584 }
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001587 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001588 // Find the class template specialization declaration that
1589 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001590 void *InsertPos = 0;
1591 ClassTemplateSpecializationDecl *Decl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001592 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1593 InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001594 if (!Decl) {
1595 // This is the first time we have referenced this class template
1596 // specialization. Create the canonical declaration and add it to
1597 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001598 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001599 ClassTemplate->getTemplatedDecl()->getTagKind(),
1600 ClassTemplate->getDeclContext(),
1601 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001602 ClassTemplate,
1603 Converted.data(),
1604 Converted.size(), 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001605 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001606 Decl->setLexicalDeclContext(CurContext);
1607 }
1608
1609 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001610 assert(isa<RecordType>(CanonType) &&
1611 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
Douglas Gregorc40290e2009-03-09 23:48:35 +00001614 // Build the fully-sugared type for this class template
1615 // specialization, which refers back to the class template
1616 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001617 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001618}
1619
John McCallfaf5fb42010-08-26 23:41:50 +00001620TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001621Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001622 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001623 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001624 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001625 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001626
Douglas Gregorc40290e2009-03-09 23:48:35 +00001627 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001628 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001629 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001630
John McCall6b51f282009-11-23 01:53:49 +00001631 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001632 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001633
1634 if (Result.isNull())
1635 return true;
1636
John McCallbcd03502009-12-07 02:54:59 +00001637 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001638 TemplateSpecializationTypeLoc TL
1639 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1640 TL.setTemplateNameLoc(TemplateLoc);
1641 TL.setLAngleLoc(LAngleLoc);
1642 TL.setRAngleLoc(RAngleLoc);
1643 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1644 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1645
John McCallba7bf592010-08-24 05:47:05 +00001646 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001647}
John McCall06f6fe8d2009-09-04 01:14:41 +00001648
John McCallfaf5fb42010-08-26 23:41:50 +00001649TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1650 TagUseKind TUK,
1651 TypeSpecifierType TagSpec,
1652 SourceLocation TagLoc) {
John McCalld8fe9af2009-09-08 17:47:29 +00001653 if (TypeResult.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001654 return ::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001655
John McCall0ad16662009-10-29 08:12:44 +00001656 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001657 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001658 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001659
John McCalld8fe9af2009-09-08 17:47:29 +00001660 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001661 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001662
John McCalld8fe9af2009-09-08 17:47:29 +00001663 if (const RecordType *RT = Type->getAs<RecordType>()) {
1664 RecordDecl *D = RT->getDecl();
1665
1666 IdentifierInfo *Id = D->getIdentifier();
1667 assert(Id && "templated class must have an identifier");
1668
1669 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1670 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001671 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001672 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001673 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001674 }
1675 }
1676
Abramo Bagnara6150c882010-05-11 21:36:43 +00001677 ElaboratedTypeKeyword Keyword
1678 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1679 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001680
John McCallba7bf592010-08-24 05:47:05 +00001681 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001682}
1683
John McCalldadc5752010-08-24 06:29:42 +00001684ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001685 LookupResult &R,
1686 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001687 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001688 // FIXME: Can we do any checking at this point? I guess we could check the
1689 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001690 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001691 // though.
John McCalle66edc12009-11-24 19:00:30 +00001692
1693 // These should be filtered out by our callers.
1694 assert(!R.empty() && "empty lookup results when building templateid");
1695 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1696
1697 NestedNameSpecifier *Qualifier = 0;
1698 SourceRange QualifierRange;
1699 if (SS.isSet()) {
1700 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1701 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001702 }
John McCall58cc69d2010-01-27 01:50:18 +00001703
1704 // We don't want lookup warnings at this point.
1705 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001706
John McCalle66edc12009-11-24 19:00:30 +00001707 bool Dependent
1708 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1709 &TemplateArgs);
1710 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001711 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001712 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001713 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001714 RequiresADL, TemplateArgs,
1715 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001716
1717 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001718}
1719
John McCalle66edc12009-11-24 19:00:30 +00001720// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001721ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001722Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001723 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001724 const TemplateArgumentListInfo &TemplateArgs) {
1725 DeclContext *DC;
1726 if (!(DC = computeDeclContext(SS, false)) ||
1727 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001728 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001729 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001730
Douglas Gregor786123d2010-05-21 23:18:07 +00001731 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001732 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001733 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1734 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001735
John McCalle66edc12009-11-24 19:00:30 +00001736 if (R.isAmbiguous())
1737 return ExprError();
1738
1739 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001740 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1741 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001742 return ExprError();
1743 }
1744
1745 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001746 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1747 << (NestedNameSpecifier*) SS.getScopeRep()
1748 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001749 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1750 return ExprError();
1751 }
1752
1753 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001754}
1755
Douglas Gregorb67535d2009-03-31 00:43:58 +00001756/// \brief Form a dependent template name.
1757///
1758/// This action forms a dependent template name given the template
1759/// name and its (presumably dependent) scope specifier. For
1760/// example, given "MetaFun::template apply", the scope specifier \p
1761/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1762/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001763TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1764 SourceLocation TemplateKWLoc,
1765 CXXScopeSpec &SS,
1766 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001767 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001768 bool EnteringContext,
1769 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001770 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1771 !getLangOptions().CPlusPlus0x)
1772 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1773 << FixItHint::CreateRemoval(TemplateKWLoc);
1774
Douglas Gregor9abe2372010-01-19 16:01:07 +00001775 DeclContext *LookupCtx = 0;
1776 if (SS.isSet())
1777 LookupCtx = computeDeclContext(SS, EnteringContext);
1778 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001779 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001780 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001781 // C++0x [temp.names]p5:
1782 // If a name prefixed by the keyword template is not the name of
1783 // a template, the program is ill-formed. [Note: the keyword
1784 // template may not be applied to non-template members of class
1785 // templates. -end note ] [ Note: as is the case with the
1786 // typename prefix, the template prefix is allowed in cases
1787 // where it is not strictly necessary; i.e., when the
1788 // nested-name-specifier or the expression on the left of the ->
1789 // or . is not dependent on a template-parameter, or the use
1790 // does not appear in the scope of a template. -end note]
1791 //
1792 // Note: C++03 was more strict here, because it banned the use of
1793 // the "template" keyword prior to a template-name that was not a
1794 // dependent name. C++ DR468 relaxed this requirement (the
1795 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001796 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001797 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001798 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1799 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001800 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001801 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1802 isa<CXXRecordDecl>(LookupCtx) &&
1803 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001804 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001805 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001806 Diag(Name.getSourceRange().getBegin(),
1807 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001808 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001809 << Name.getSourceRange()
1810 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001811 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001812 } else {
1813 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001814 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001815 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001816 }
1817
Mike Stump11289f42009-09-09 15:08:12 +00001818 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001819 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001820
1821 switch (Name.getKind()) {
1822 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001823 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1824 Name.Identifier));
1825 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001826
Douglas Gregor71395fa2009-11-04 00:56:37 +00001827 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001828 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001829 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001830 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001831
1832 case UnqualifiedId::IK_LiteralOperatorId:
1833 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1834
Douglas Gregor3cf81312009-11-03 23:16:33 +00001835 default:
1836 break;
1837 }
1838
1839 Diag(Name.getSourceRange().getBegin(),
1840 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001841 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001842 << Name.getSourceRange()
1843 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001844 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001845}
1846
Mike Stump11289f42009-09-09 15:08:12 +00001847bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001848 const TemplateArgumentLoc &AL,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001849 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001850 const TemplateArgument &Arg = AL.getArgument();
1851
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001852 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001853 switch(Arg.getKind()) {
1854 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001855 // C++ [temp.arg.type]p1:
1856 // A template-argument for a template-parameter which is a
1857 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001858 break;
1859 case TemplateArgument::Template: {
1860 // We have a template type parameter but the template argument
1861 // is a template without any arguments.
1862 SourceRange SR = AL.getSourceRange();
1863 TemplateName Name = Arg.getAsTemplate();
1864 Diag(SR.getBegin(), diag::err_template_missing_args)
1865 << Name << SR;
1866 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1867 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001868
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001869 return true;
1870 }
1871 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001872 // We have a template type parameter but the template argument
1873 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001874 SourceRange SR = AL.getSourceRange();
1875 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001876 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001877
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001878 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001879 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001880 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001881
John McCallbcd03502009-12-07 02:54:59 +00001882 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001883 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001884
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001885 // Add the converted template type argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001886 Converted.push_back(
John McCall0ad16662009-10-29 08:12:44 +00001887 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001888 return false;
1889}
1890
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001891/// \brief Substitute template arguments into the default template argument for
1892/// the given template type parameter.
1893///
1894/// \param SemaRef the semantic analysis object for which we are performing
1895/// the substitution.
1896///
1897/// \param Template the template that we are synthesizing template arguments
1898/// for.
1899///
1900/// \param TemplateLoc the location of the template name that started the
1901/// template-id we are checking.
1902///
1903/// \param RAngleLoc the location of the right angle bracket ('>') that
1904/// terminates the template-id.
1905///
1906/// \param Param the template template parameter whose default we are
1907/// substituting into.
1908///
1909/// \param Converted the list of template arguments provided for template
1910/// parameters that precede \p Param in the template parameter list.
1911///
1912/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001913static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001914SubstDefaultTemplateArgument(Sema &SemaRef,
1915 TemplateDecl *Template,
1916 SourceLocation TemplateLoc,
1917 SourceLocation RAngleLoc,
1918 TemplateTypeParmDecl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001919 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001920 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001921
1922 // If the argument type is dependent, instantiate it now based
1923 // on the previously-computed template arguments.
1924 if (ArgType->getType()->isDependentType()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001925 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1926 Converted.data(), Converted.size());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001927
1928 MultiLevelTemplateArgumentList AllTemplateArgs
1929 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1930
1931 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001932 Template, Converted.data(),
1933 Converted.size(),
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001934 SourceRange(TemplateLoc, RAngleLoc));
1935
1936 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1937 Param->getDefaultArgumentLoc(),
1938 Param->getDeclName());
1939 }
1940
1941 return ArgType;
1942}
1943
1944/// \brief Substitute template arguments into the default template argument for
1945/// the given non-type template parameter.
1946///
1947/// \param SemaRef the semantic analysis object for which we are performing
1948/// the substitution.
1949///
1950/// \param Template the template that we are synthesizing template arguments
1951/// for.
1952///
1953/// \param TemplateLoc the location of the template name that started the
1954/// template-id we are checking.
1955///
1956/// \param RAngleLoc the location of the right angle bracket ('>') that
1957/// terminates the template-id.
1958///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001959/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001960/// substituting into.
1961///
1962/// \param Converted the list of template arguments provided for template
1963/// parameters that precede \p Param in the template parameter list.
1964///
1965/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001966static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001967SubstDefaultTemplateArgument(Sema &SemaRef,
1968 TemplateDecl *Template,
1969 SourceLocation TemplateLoc,
1970 SourceLocation RAngleLoc,
1971 NonTypeTemplateParmDecl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001972 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
1973 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1974 Converted.data(), Converted.size());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001975
1976 MultiLevelTemplateArgumentList AllTemplateArgs
1977 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1978
1979 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001980 Template, Converted.data(),
1981 Converted.size(),
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001982 SourceRange(TemplateLoc, RAngleLoc));
1983
1984 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1985}
1986
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001987/// \brief Substitute template arguments into the default template argument for
1988/// the given template template parameter.
1989///
1990/// \param SemaRef the semantic analysis object for which we are performing
1991/// the substitution.
1992///
1993/// \param Template the template that we are synthesizing template arguments
1994/// for.
1995///
1996/// \param TemplateLoc the location of the template name that started the
1997/// template-id we are checking.
1998///
1999/// \param RAngleLoc the location of the right angle bracket ('>') that
2000/// terminates the template-id.
2001///
2002/// \param Param the template template parameter whose default we are
2003/// substituting into.
2004///
2005/// \param Converted the list of template arguments provided for template
2006/// parameters that precede \p Param in the template parameter list.
2007///
2008/// \returns the substituted template argument, or NULL if an error occurred.
2009static TemplateName
2010SubstDefaultTemplateArgument(Sema &SemaRef,
2011 TemplateDecl *Template,
2012 SourceLocation TemplateLoc,
2013 SourceLocation RAngleLoc,
2014 TemplateTemplateParmDecl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002015 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2016 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2017 Converted.data(), Converted.size());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002018
2019 MultiLevelTemplateArgumentList AllTemplateArgs
2020 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2021
2022 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002023 Template, Converted.data(),
2024 Converted.size(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002025 SourceRange(TemplateLoc, RAngleLoc));
2026
2027 return SemaRef.SubstTemplateName(
2028 Param->getDefaultArgument().getArgument().getAsTemplate(),
2029 Param->getDefaultArgument().getTemplateNameLoc(),
2030 AllTemplateArgs);
2031}
2032
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002033/// \brief If the given template parameter has a default template
2034/// argument, substitute into that default template argument and
2035/// return the corresponding template argument.
2036TemplateArgumentLoc
2037Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2038 SourceLocation TemplateLoc,
2039 SourceLocation RAngleLoc,
2040 Decl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002041 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2042 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002043 if (!TypeParm->hasDefaultArgument())
2044 return TemplateArgumentLoc();
2045
John McCallbcd03502009-12-07 02:54:59 +00002046 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002047 TemplateLoc,
2048 RAngleLoc,
2049 TypeParm,
2050 Converted);
2051 if (DI)
2052 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2053
2054 return TemplateArgumentLoc();
2055 }
2056
2057 if (NonTypeTemplateParmDecl *NonTypeParm
2058 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2059 if (!NonTypeParm->hasDefaultArgument())
2060 return TemplateArgumentLoc();
2061
John McCalldadc5752010-08-24 06:29:42 +00002062 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002063 TemplateLoc,
2064 RAngleLoc,
2065 NonTypeParm,
2066 Converted);
2067 if (Arg.isInvalid())
2068 return TemplateArgumentLoc();
2069
2070 Expr *ArgE = Arg.takeAs<Expr>();
2071 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2072 }
2073
2074 TemplateTemplateParmDecl *TempTempParm
2075 = cast<TemplateTemplateParmDecl>(Param);
2076 if (!TempTempParm->hasDefaultArgument())
2077 return TemplateArgumentLoc();
2078
2079 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2080 TemplateLoc,
2081 RAngleLoc,
2082 TempTempParm,
2083 Converted);
2084 if (TName.isNull())
2085 return TemplateArgumentLoc();
2086
2087 return TemplateArgumentLoc(TemplateArgument(TName),
2088 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2089 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2090}
2091
Douglas Gregorda0fb532009-11-11 19:31:23 +00002092/// \brief Check that the given template argument corresponds to the given
2093/// template parameter.
2094bool Sema::CheckTemplateArgument(NamedDecl *Param,
2095 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002096 TemplateDecl *Template,
2097 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002098 SourceLocation RAngleLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002099 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002100 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002101 // Check template type parameters.
2102 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002103 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002104
Douglas Gregoreebed722009-11-11 19:41:09 +00002105 // Check non-type template parameters.
2106 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002107 // Do substitution on the type of the non-type template parameter
2108 // with the template arguments we've seen thus far.
2109 QualType NTTPType = NTTP->getType();
2110 if (NTTPType->isDependentType()) {
2111 // Do substitution on the type of the non-type template parameter.
2112 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002113 NTTP, Converted.data(), Converted.size(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002114 SourceRange(TemplateLoc, RAngleLoc));
2115
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002116 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2117 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002118 NTTPType = SubstType(NTTPType,
2119 MultiLevelTemplateArgumentList(TemplateArgs),
2120 NTTP->getLocation(),
2121 NTTP->getDeclName());
2122 // If that worked, check the non-type template parameter type
2123 // for validity.
2124 if (!NTTPType.isNull())
2125 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2126 NTTP->getLocation());
2127 if (NTTPType.isNull())
2128 return true;
2129 }
2130
2131 switch (Arg.getArgument().getKind()) {
2132 case TemplateArgument::Null:
2133 assert(false && "Should never see a NULL template argument here");
2134 return true;
2135
2136 case TemplateArgument::Expression: {
2137 Expr *E = Arg.getArgument().getAsExpr();
2138 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002139 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002140 return true;
2141
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002142 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002143 break;
2144 }
2145
2146 case TemplateArgument::Declaration:
2147 case TemplateArgument::Integral:
2148 // We've already checked this template argument, so just copy
2149 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002150 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002151 break;
2152
2153 case TemplateArgument::Template:
2154 // We were given a template template argument. It may not be ill-formed;
2155 // see below.
2156 if (DependentTemplateName *DTN
2157 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2158 // We have a template argument such as \c T::template X, which we
2159 // parsed as a template template argument. However, since we now
2160 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002161 // template name into an expression.
2162
2163 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2164 Arg.getTemplateNameLoc());
2165
John McCalle66edc12009-11-24 19:00:30 +00002166 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2167 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002168 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002169 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002170
2171 TemplateArgument Result;
2172 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2173 return true;
2174
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002175 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002176 break;
2177 }
2178
2179 // We have a template argument that actually does refer to a class
2180 // template, template alias, or template template parameter, and
2181 // therefore cannot be a non-type template argument.
2182 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2183 << Arg.getSourceRange();
2184
2185 Diag(Param->getLocation(), diag::note_template_param_here);
2186 return true;
2187
2188 case TemplateArgument::Type: {
2189 // We have a non-type template parameter but the template
2190 // argument is a type.
2191
2192 // C++ [temp.arg]p2:
2193 // In a template-argument, an ambiguity between a type-id and
2194 // an expression is resolved to a type-id, regardless of the
2195 // form of the corresponding template-parameter.
2196 //
2197 // We warn specifically about this case, since it can be rather
2198 // confusing for users.
2199 QualType T = Arg.getArgument().getAsType();
2200 SourceRange SR = Arg.getSourceRange();
2201 if (T->isFunctionType())
2202 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2203 else
2204 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2205 Diag(Param->getLocation(), diag::note_template_param_here);
2206 return true;
2207 }
2208
2209 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002210 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002211 break;
2212 }
2213
2214 return false;
2215 }
2216
2217
2218 // Check template template parameters.
2219 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2220
2221 // Substitute into the template parameter list of the template
2222 // template parameter, since previously-supplied template arguments
2223 // may appear within the template template parameter.
2224 {
2225 // Set up a template instantiation context.
2226 LocalInstantiationScope Scope(*this);
2227 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002228 TempParm, Converted.data(), Converted.size(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002229 SourceRange(TemplateLoc, RAngleLoc));
2230
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002231 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2232 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002233 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2234 SubstDecl(TempParm, CurContext,
2235 MultiLevelTemplateArgumentList(TemplateArgs)));
2236 if (!TempParm)
2237 return true;
2238
2239 // FIXME: TempParam is leaked.
2240 }
2241
2242 switch (Arg.getArgument().getKind()) {
2243 case TemplateArgument::Null:
2244 assert(false && "Should never see a NULL template argument here");
2245 return true;
2246
2247 case TemplateArgument::Template:
2248 if (CheckTemplateArgument(TempParm, Arg))
2249 return true;
2250
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002251 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002252 break;
2253
2254 case TemplateArgument::Expression:
2255 case TemplateArgument::Type:
2256 // We have a template template parameter but the template
2257 // argument does not refer to a template.
2258 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2259 return true;
2260
2261 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002262 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002263 "Declaration argument with template template parameter");
2264 break;
2265 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002266 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002267 "Integral argument with template template parameter");
2268 break;
2269
2270 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002271 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002272 break;
2273 }
2274
2275 return false;
2276}
2277
Douglas Gregord32e0282009-02-09 23:23:08 +00002278/// \brief Check that the given template argument list is well-formed
2279/// for specializing the given template.
2280bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2281 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002282 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002283 bool PartialTemplateArgs,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002284 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002285 TemplateParameterList *Params = Template->getTemplateParameters();
2286 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002287 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002288 bool Invalid = false;
2289
John McCall6b51f282009-11-23 01:53:49 +00002290 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2291
Mike Stump11289f42009-09-09 15:08:12 +00002292 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002293 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002294
Anders Carlsson15201f12009-06-13 02:08:00 +00002295 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002296 (NumArgs < Params->getMinRequiredArguments() &&
2297 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002298 // FIXME: point at either the first arg beyond what we can handle,
2299 // or the '>', depending on whether we have too many or too few
2300 // arguments.
2301 SourceRange Range;
2302 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002303 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002304 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2305 << (NumArgs > NumParams)
2306 << (isa<ClassTemplateDecl>(Template)? 0 :
2307 isa<FunctionTemplateDecl>(Template)? 1 :
2308 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2309 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002310 Diag(Template->getLocation(), diag::note_template_decl_here)
2311 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002312 Invalid = true;
2313 }
Mike Stump11289f42009-09-09 15:08:12 +00002314
2315 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002316 // [...] The type and form of each template-argument specified in
2317 // a template-id shall match the type and form specified for the
2318 // corresponding parameter declared by the template in its
2319 // template-parameter-list.
2320 unsigned ArgIdx = 0;
2321 for (TemplateParameterList::iterator Param = Params->begin(),
2322 ParamEnd = Params->end();
2323 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002324 if (ArgIdx > NumArgs && PartialTemplateArgs)
2325 break;
Mike Stump11289f42009-09-09 15:08:12 +00002326
Douglas Gregoreebed722009-11-11 19:41:09 +00002327 // If we have a template parameter pack, check every remaining template
2328 // argument against that template parameter pack.
2329 if ((*Param)->isTemplateParameterPack()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002330 Diag(TemplateLoc, diag::err_variadic_templates_unsupported);
2331 return true;
Douglas Gregoreebed722009-11-11 19:41:09 +00002332 }
2333
Douglas Gregor84d49a22009-11-11 21:54:23 +00002334 if (ArgIdx < NumArgs) {
2335 // Check the template argument we were given.
2336 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2337 TemplateLoc, RAngleLoc, Converted))
2338 return true;
2339
2340 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002341 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002342
Douglas Gregor84d49a22009-11-11 21:54:23 +00002343 // We have a default template argument that we will use.
2344 TemplateArgumentLoc Arg;
2345
2346 // Retrieve the default template argument from the template
2347 // parameter. For each kind of template parameter, we substitute the
2348 // template arguments provided thus far and any "outer" template arguments
2349 // (when the template parameter was part of a nested template) into
2350 // the default argument.
2351 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2352 if (!TTP->hasDefaultArgument()) {
2353 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2354 break;
2355 }
2356
John McCallbcd03502009-12-07 02:54:59 +00002357 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002358 Template,
2359 TemplateLoc,
2360 RAngleLoc,
2361 TTP,
2362 Converted);
2363 if (!ArgType)
2364 return true;
2365
2366 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2367 ArgType);
2368 } else if (NonTypeTemplateParmDecl *NTTP
2369 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2370 if (!NTTP->hasDefaultArgument()) {
2371 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2372 break;
2373 }
2374
John McCalldadc5752010-08-24 06:29:42 +00002375 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002376 TemplateLoc,
2377 RAngleLoc,
2378 NTTP,
2379 Converted);
2380 if (E.isInvalid())
2381 return true;
2382
2383 Expr *Ex = E.takeAs<Expr>();
2384 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2385 } else {
2386 TemplateTemplateParmDecl *TempParm
2387 = cast<TemplateTemplateParmDecl>(*Param);
2388
2389 if (!TempParm->hasDefaultArgument()) {
2390 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2391 break;
2392 }
2393
2394 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2395 TemplateLoc,
2396 RAngleLoc,
2397 TempParm,
2398 Converted);
2399 if (Name.isNull())
2400 return true;
2401
2402 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2403 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2404 TempParm->getDefaultArgument().getTemplateNameLoc());
2405 }
2406
2407 // Introduce an instantiation record that describes where we are using
2408 // the default template argument.
2409 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002410 Converted.data(), Converted.size(),
Douglas Gregor84d49a22009-11-11 21:54:23 +00002411 SourceRange(TemplateLoc, RAngleLoc));
2412
2413 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002414 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002415 RAngleLoc, Converted))
2416 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002417 }
2418
2419 return Invalid;
2420}
2421
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002422namespace {
2423 class UnnamedLocalNoLinkageFinder
2424 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2425 {
2426 Sema &S;
2427 SourceRange SR;
2428
2429 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2430
2431 public:
2432 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2433
2434 bool Visit(QualType T) {
2435 return inherited::Visit(T.getTypePtr());
2436 }
2437
2438#define TYPE(Class, Parent) \
2439 bool Visit##Class##Type(const Class##Type *);
2440#define ABSTRACT_TYPE(Class, Parent) \
2441 bool Visit##Class##Type(const Class##Type *) { return false; }
2442#define NON_CANONICAL_TYPE(Class, Parent) \
2443 bool Visit##Class##Type(const Class##Type *) { return false; }
2444#include "clang/AST/TypeNodes.def"
2445
2446 bool VisitTagDecl(const TagDecl *Tag);
2447 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2448 };
2449}
2450
2451bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2452 return false;
2453}
2454
2455bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2456 return Visit(T->getElementType());
2457}
2458
2459bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2460 return Visit(T->getPointeeType());
2461}
2462
2463bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2464 const BlockPointerType* T) {
2465 return Visit(T->getPointeeType());
2466}
2467
2468bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2469 const LValueReferenceType* T) {
2470 return Visit(T->getPointeeType());
2471}
2472
2473bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2474 const RValueReferenceType* T) {
2475 return Visit(T->getPointeeType());
2476}
2477
2478bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2479 const MemberPointerType* T) {
2480 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2481}
2482
2483bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2484 const ConstantArrayType* T) {
2485 return Visit(T->getElementType());
2486}
2487
2488bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2489 const IncompleteArrayType* T) {
2490 return Visit(T->getElementType());
2491}
2492
2493bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2494 const VariableArrayType* T) {
2495 return Visit(T->getElementType());
2496}
2497
2498bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2499 const DependentSizedArrayType* T) {
2500 return Visit(T->getElementType());
2501}
2502
2503bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2504 const DependentSizedExtVectorType* T) {
2505 return Visit(T->getElementType());
2506}
2507
2508bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2509 return Visit(T->getElementType());
2510}
2511
2512bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2513 return Visit(T->getElementType());
2514}
2515
2516bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2517 const FunctionProtoType* T) {
2518 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2519 AEnd = T->arg_type_end();
2520 A != AEnd; ++A) {
2521 if (Visit(*A))
2522 return true;
2523 }
2524
2525 return Visit(T->getResultType());
2526}
2527
2528bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2529 const FunctionNoProtoType* T) {
2530 return Visit(T->getResultType());
2531}
2532
2533bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2534 const UnresolvedUsingType*) {
2535 return false;
2536}
2537
2538bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2539 return false;
2540}
2541
2542bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2543 return Visit(T->getUnderlyingType());
2544}
2545
2546bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2547 return false;
2548}
2549
2550bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2551 return VisitTagDecl(T->getDecl());
2552}
2553
2554bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2555 return VisitTagDecl(T->getDecl());
2556}
2557
2558bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2559 const TemplateTypeParmType*) {
2560 return false;
2561}
2562
2563bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2564 const TemplateSpecializationType*) {
2565 return false;
2566}
2567
2568bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2569 const InjectedClassNameType* T) {
2570 return VisitTagDecl(T->getDecl());
2571}
2572
2573bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2574 const DependentNameType* T) {
2575 return VisitNestedNameSpecifier(T->getQualifier());
2576}
2577
2578bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2579 const DependentTemplateSpecializationType* T) {
2580 return VisitNestedNameSpecifier(T->getQualifier());
2581}
2582
2583bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2584 return false;
2585}
2586
2587bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2588 const ObjCInterfaceType *) {
2589 return false;
2590}
2591
2592bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2593 const ObjCObjectPointerType *) {
2594 return false;
2595}
2596
2597bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2598 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2599 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2600 << S.Context.getTypeDeclType(Tag) << SR;
2601 return true;
2602 }
2603
2604 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2605 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2606 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2607 return true;
2608 }
2609
2610 return false;
2611}
2612
2613bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2614 NestedNameSpecifier *NNS) {
2615 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2616 return true;
2617
2618 switch (NNS->getKind()) {
2619 case NestedNameSpecifier::Identifier:
2620 case NestedNameSpecifier::Namespace:
2621 case NestedNameSpecifier::Global:
2622 return false;
2623
2624 case NestedNameSpecifier::TypeSpec:
2625 case NestedNameSpecifier::TypeSpecWithTemplate:
2626 return Visit(QualType(NNS->getAsType(), 0));
2627 }
Fariborz Jahanian26d1e2b2010-10-13 16:19:16 +00002628 return false;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002629}
2630
2631
Douglas Gregord32e0282009-02-09 23:23:08 +00002632/// \brief Check a template argument against its corresponding
2633/// template type parameter.
2634///
2635/// This routine implements the semantics of C++ [temp.arg.type]. It
2636/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002637bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002638 TypeSourceInfo *ArgInfo) {
2639 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002640 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00002641 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002642
2643 if (Arg->isVariablyModifiedType()) {
2644 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002645 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002646 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002647 }
2648
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002649 // C++03 [temp.arg.type]p2:
2650 // A local type, a type with no linkage, an unnamed type or a type
2651 // compounded from any of these types shall not be used as a
2652 // template-argument for a template type-parameter.
2653 //
2654 // C++0x allows these, and even in C++03 we allow them as an extension with
2655 // a warning.
Douglas Gregor52051cb2010-10-13 18:05:20 +00002656 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002657 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2658 (void)Finder.Visit(Context.getCanonicalType(Arg));
2659 }
2660
Douglas Gregord32e0282009-02-09 23:23:08 +00002661 return false;
2662}
2663
Douglas Gregorccb07762009-02-11 19:52:55 +00002664/// \brief Checks whether the given template argument is the address
2665/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002666static bool
2667CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2668 NonTypeTemplateParmDecl *Param,
2669 QualType ParamType,
2670 Expr *ArgIn,
2671 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002672 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002673 Expr *Arg = ArgIn;
2674 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002675
2676 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002677 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002678 Arg = Cast->getSubExpr();
2679
2680 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002681 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002682 // A template-argument for a non-type, non-template
2683 // template-parameter shall be one of: [...]
2684 //
2685 // -- the address of an object or function with external
2686 // linkage, including function templates and function
2687 // template-ids but excluding non-static class members,
2688 // expressed as & id-expression where the & is optional if
2689 // the name refers to a function or array, or if the
2690 // corresponding template-parameter is a reference; or
2691 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002692
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002693 // In C++98/03 mode, give an extension warning on any extra parentheses.
2694 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2695 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002696 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002697 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002698 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002699 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002700 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002701 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002702 }
2703
2704 Arg = Parens->getSubExpr();
2705 }
2706
Douglas Gregorb242683d2010-04-01 18:32:35 +00002707 bool AddressTaken = false;
2708 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002709 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002710 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002711 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002712 AddressTaken = true;
2713 AddrOpLoc = UnOp->getOperatorLoc();
2714 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002715 } else
2716 DRE = dyn_cast<DeclRefExpr>(Arg);
2717
Douglas Gregorb242683d2010-04-01 18:32:35 +00002718 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002719 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2720 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002721 S.Diag(Param->getLocation(), diag::note_template_param_here);
2722 return true;
2723 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002724
2725 // Stop checking the precise nature of the argument if it is value dependent,
2726 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002727 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00002728 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00002729 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002730 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002731
Douglas Gregorb242683d2010-04-01 18:32:35 +00002732 if (!isa<ValueDecl>(DRE->getDecl())) {
2733 S.Diag(Arg->getSourceRange().getBegin(),
2734 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002735 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002736 S.Diag(Param->getLocation(), diag::note_template_param_here);
2737 return true;
2738 }
2739
2740 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002741
2742 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002743 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2744 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002745 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002746 S.Diag(Param->getLocation(), diag::note_template_param_here);
2747 return true;
2748 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002749
2750 // Cannot refer to non-static member functions
2751 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002752 if (!Method->isStatic()) {
2753 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002754 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002755 S.Diag(Param->getLocation(), diag::note_template_param_here);
2756 return true;
2757 }
Mike Stump11289f42009-09-09 15:08:12 +00002758
Douglas Gregorccb07762009-02-11 19:52:55 +00002759 // Functions must have external linkage.
2760 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002761 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002762 S.Diag(Arg->getSourceRange().getBegin(),
2763 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002764 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002765 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002766 << true;
2767 return true;
2768 }
2769
2770 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002771 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002772
Douglas Gregorb242683d2010-04-01 18:32:35 +00002773 // If the template parameter has pointer type, the function decays.
2774 if (ParamType->isPointerType() && !AddressTaken)
2775 ArgType = S.Context.getPointerType(Func->getType());
2776 else if (AddressTaken && ParamType->isReferenceType()) {
2777 // If we originally had an address-of operator, but the
2778 // parameter has reference type, complain and (if things look
2779 // like they will work) drop the address-of operator.
2780 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2781 ParamType.getNonReferenceType())) {
2782 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2783 << ParamType;
2784 S.Diag(Param->getLocation(), diag::note_template_param_here);
2785 return true;
2786 }
2787
2788 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2789 << ParamType
2790 << FixItHint::CreateRemoval(AddrOpLoc);
2791 S.Diag(Param->getLocation(), diag::note_template_param_here);
2792
2793 ArgType = Func->getType();
2794 }
2795 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002796 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002797 S.Diag(Arg->getSourceRange().getBegin(),
2798 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002799 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002800 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002801 << true;
2802 return true;
2803 }
2804
Douglas Gregorb242683d2010-04-01 18:32:35 +00002805 // A value of reference type is not an object.
2806 if (Var->getType()->isReferenceType()) {
2807 S.Diag(Arg->getSourceRange().getBegin(),
2808 diag::err_template_arg_reference_var)
2809 << Var->getType() << Arg->getSourceRange();
2810 S.Diag(Param->getLocation(), diag::note_template_param_here);
2811 return true;
2812 }
2813
Douglas Gregorccb07762009-02-11 19:52:55 +00002814 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002815 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002816
2817 // If the template parameter has pointer type, we must have taken
2818 // the address of this object.
2819 if (ParamType->isReferenceType()) {
2820 if (AddressTaken) {
2821 // If we originally had an address-of operator, but the
2822 // parameter has reference type, complain and (if things look
2823 // like they will work) drop the address-of operator.
2824 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2825 ParamType.getNonReferenceType())) {
2826 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2827 << ParamType;
2828 S.Diag(Param->getLocation(), diag::note_template_param_here);
2829 return true;
2830 }
2831
2832 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2833 << ParamType
2834 << FixItHint::CreateRemoval(AddrOpLoc);
2835 S.Diag(Param->getLocation(), diag::note_template_param_here);
2836
2837 ArgType = Var->getType();
2838 }
2839 } else if (!AddressTaken && ParamType->isPointerType()) {
2840 if (Var->getType()->isArrayType()) {
2841 // Array-to-pointer decay.
2842 ArgType = S.Context.getArrayDecayedType(Var->getType());
2843 } else {
2844 // If the template parameter has pointer type but the address of
2845 // this object was not taken, complain and (possibly) recover by
2846 // taking the address of the entity.
2847 ArgType = S.Context.getPointerType(Var->getType());
2848 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2849 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2850 << ParamType;
2851 S.Diag(Param->getLocation(), diag::note_template_param_here);
2852 return true;
2853 }
2854
2855 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2856 << ParamType
2857 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2858
2859 S.Diag(Param->getLocation(), diag::note_template_param_here);
2860 }
2861 }
2862 } else {
2863 // We found something else, but we don't know specifically what it is.
2864 S.Diag(Arg->getSourceRange().getBegin(),
2865 diag::err_template_arg_not_object_or_func)
2866 << Arg->getSourceRange();
2867 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2868 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002869 }
Mike Stump11289f42009-09-09 15:08:12 +00002870
Douglas Gregorb242683d2010-04-01 18:32:35 +00002871 if (ParamType->isPointerType() &&
2872 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2873 S.IsQualificationConversion(ArgType, ParamType)) {
2874 // For pointer-to-object types, qualification conversions are
2875 // permitted.
2876 } else {
2877 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2878 if (!ParamRef->getPointeeType()->isFunctionType()) {
2879 // C++ [temp.arg.nontype]p5b3:
2880 // For a non-type template-parameter of type reference to
2881 // object, no conversions apply. The type referred to by the
2882 // reference may be more cv-qualified than the (otherwise
2883 // identical) type of the template- argument. The
2884 // template-parameter is bound directly to the
2885 // template-argument, which shall be an lvalue.
2886
2887 // FIXME: Other qualifiers?
2888 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2889 unsigned ArgQuals = ArgType.getCVRQualifiers();
2890
2891 if ((ParamQuals | ArgQuals) != ParamQuals) {
2892 S.Diag(Arg->getSourceRange().getBegin(),
2893 diag::err_template_arg_ref_bind_ignores_quals)
2894 << ParamType << Arg->getType()
2895 << Arg->getSourceRange();
2896 S.Diag(Param->getLocation(), diag::note_template_param_here);
2897 return true;
2898 }
2899 }
2900 }
2901
2902 // At this point, the template argument refers to an object or
2903 // function with external linkage. We now need to check whether the
2904 // argument and parameter types are compatible.
2905 if (!S.Context.hasSameUnqualifiedType(ArgType,
2906 ParamType.getNonReferenceType())) {
2907 // We can't perform this conversion or binding.
2908 if (ParamType->isReferenceType())
2909 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2910 << ParamType << Arg->getType() << Arg->getSourceRange();
2911 else
2912 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2913 << Arg->getType() << ParamType << Arg->getSourceRange();
2914 S.Diag(Param->getLocation(), diag::note_template_param_here);
2915 return true;
2916 }
2917 }
2918
2919 // Create the template argument.
2920 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002921 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002922 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002923}
2924
2925/// \brief Checks whether the given template argument is a pointer to
2926/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002927bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2928 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002929 bool Invalid = false;
2930
2931 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002932 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002933 Arg = Cast->getSubExpr();
2934
2935 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002936 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002937 // A template-argument for a non-type, non-template
2938 // template-parameter shall be one of: [...]
2939 //
2940 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002941 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002942
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002943 // In C++98/03 mode, give an extension warning on any extra parentheses.
2944 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2945 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002946 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002947 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00002948 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002949 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002950 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002951 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002952 }
2953
2954 Arg = Parens->getSubExpr();
2955 }
2956
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002957 // A pointer-to-member constant written &Class::member.
2958 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002959 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002960 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2961 if (DRE && !DRE->getQualifier())
2962 DRE = 0;
2963 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002964 }
2965 // A constant of pointer-to-member type.
2966 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2967 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2968 if (VD->getType()->isMemberPointerType()) {
2969 if (isa<NonTypeTemplateParmDecl>(VD) ||
2970 (isa<VarDecl>(VD) &&
2971 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2972 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCallc3007a22010-10-26 07:05:15 +00002973 Converted = TemplateArgument(Arg);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002974 else
2975 Converted = TemplateArgument(VD->getCanonicalDecl());
2976 return Invalid;
2977 }
2978 }
2979 }
2980
2981 DRE = 0;
2982 }
2983
Douglas Gregorccb07762009-02-11 19:52:55 +00002984 if (!DRE)
2985 return Diag(Arg->getSourceRange().getBegin(),
2986 diag::err_template_arg_not_pointer_to_member_form)
2987 << Arg->getSourceRange();
2988
2989 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2990 assert((isa<FieldDecl>(DRE->getDecl()) ||
2991 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2992 "Only non-static member pointers can make it here");
2993
2994 // Okay: this is the address of a non-static member, and therefore
2995 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002996 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCallc3007a22010-10-26 07:05:15 +00002997 Converted = TemplateArgument(Arg);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002998 else
2999 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00003000 return Invalid;
3001 }
3002
3003 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00003004 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00003005 diag::err_template_arg_not_pointer_to_member_form)
3006 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003007 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00003008 diag::note_template_arg_refers_here);
3009 return true;
3010}
3011
Douglas Gregord32e0282009-02-09 23:23:08 +00003012/// \brief Check a template argument against its corresponding
3013/// non-type template parameter.
3014///
Douglas Gregor463421d2009-03-03 04:44:36 +00003015/// This routine implements the semantics of C++ [temp.arg.nontype].
3016/// It returns true if an error occurred, and false otherwise. \p
3017/// InstantiatedParamType is the type of the non-type template
3018/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003019///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003020/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00003021bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00003022 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003023 TemplateArgument &Converted,
3024 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003025 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3026
Douglas Gregor86560402009-02-10 23:36:10 +00003027 // If either the parameter has a dependent type or the argument is
3028 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00003029 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3030 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003031 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00003032 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003033 }
Douglas Gregor86560402009-02-10 23:36:10 +00003034
3035 // C++ [temp.arg.nontype]p5:
3036 // The following conversions are performed on each expression used
3037 // as a non-type template-argument. If a non-type
3038 // template-argument cannot be converted to the type of the
3039 // corresponding template-parameter then the program is
3040 // ill-formed.
3041 //
3042 // -- for a non-type template-parameter of integral or
3043 // enumeration type, integral promotions (4.5) and integral
3044 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00003045 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003046 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00003047 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00003048 // C++ [temp.arg.nontype]p1:
3049 // A template-argument for a non-type, non-template
3050 // template-parameter shall be one of:
3051 //
3052 // -- an integral constant-expression of integral or enumeration
3053 // type; or
3054 // -- the name of a non-type template-parameter; or
3055 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003056 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00003057 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003058 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003059 diag::err_template_arg_not_integral_or_enumeral)
3060 << ArgType << Arg->getSourceRange();
3061 Diag(Param->getLocation(), diag::note_template_param_here);
3062 return true;
3063 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003064 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003065 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3066 << ArgType << Arg->getSourceRange();
3067 return true;
3068 }
3069
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003070 // From here on out, all we care about are the unqualified forms
3071 // of the parameter and argument types.
3072 ParamType = ParamType.getUnqualifiedType();
3073 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00003074
3075 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00003076 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003077 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003078 } else if (CTAK == CTAK_Deduced) {
3079 // C++ [temp.deduct.type]p17:
3080 // If, in the declaration of a function template with a non-type
3081 // template-parameter, the non-type template- parameter is used
3082 // in an expression in the function parameter-list and, if the
3083 // corresponding template-argument is deduced, the
3084 // template-argument type shall match the type of the
3085 // template-parameter exactly, except that a template-argument
3086 // deduced from an array bound may be of any integral type.
3087 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3088 << ArgType << ParamType;
3089 Diag(Param->getLocation(), diag::note_template_param_here);
3090 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00003091 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3092 !ParamType->isEnumeralType()) {
3093 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00003094 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00003095 } else {
3096 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003097 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003098 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003099 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00003100 Diag(Param->getLocation(), diag::note_template_param_here);
3101 return true;
3102 }
3103
Douglas Gregor52aba872009-03-14 00:20:21 +00003104 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00003105 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003106 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00003107
3108 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003109 llvm::APSInt OldValue = Value;
3110
3111 // Coerce the template argument's value to the value it will have
3112 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003113 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003114 if (Value.getBitWidth() != AllowedBits)
3115 Value.extOrTrunc(AllowedBits);
3116 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003117
3118 // Complain if an unsigned parameter received a negative value.
3119 if (IntegerType->isUnsignedIntegerType()
3120 && (OldValue.isSigned() && OldValue.isNegative())) {
3121 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3122 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3123 << Arg->getSourceRange();
3124 Diag(Param->getLocation(), diag::note_template_param_here);
3125 }
3126
3127 // Complain if we overflowed the template parameter's type.
3128 unsigned RequiredBits;
3129 if (IntegerType->isUnsignedIntegerType())
3130 RequiredBits = OldValue.getActiveBits();
3131 else if (OldValue.isUnsigned())
3132 RequiredBits = OldValue.getActiveBits() + 1;
3133 else
3134 RequiredBits = OldValue.getMinSignedBits();
3135 if (RequiredBits > AllowedBits) {
3136 Diag(Arg->getSourceRange().getBegin(),
3137 diag::warn_template_arg_too_large)
3138 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3139 << Arg->getSourceRange();
3140 Diag(Param->getLocation(), diag::note_template_param_here);
3141 }
Douglas Gregor52aba872009-03-14 00:20:21 +00003142 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003143
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003144 // Add the value of this argument to the list of converted
3145 // arguments. We use the bitwidth and signedness of the template
3146 // parameter.
3147 if (Arg->isValueDependent()) {
3148 // The argument is value-dependent. Create a new
3149 // TemplateArgument with the converted expression.
3150 Converted = TemplateArgument(Arg);
3151 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003152 }
3153
John McCall0ad16662009-10-29 08:12:44 +00003154 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00003155 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003156 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00003157 return false;
3158 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003159
John McCall16df1e52010-03-30 21:47:33 +00003160 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3161
Douglas Gregorb242683d2010-04-01 18:32:35 +00003162 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3163 // from a template argument of type std::nullptr_t to a non-type
3164 // template parameter of type pointer to object, pointer to
3165 // function, or pointer-to-member, respectively.
3166 if (ArgType->isNullPtrType() &&
3167 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3168 Converted = TemplateArgument((NamedDecl *)0);
3169 return false;
3170 }
3171
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003172 // Handle pointer-to-function, reference-to-function, and
3173 // pointer-to-member-function all in (roughly) the same way.
3174 if (// -- For a non-type template-parameter of type pointer to
3175 // function, only the function-to-pointer conversion (4.3) is
3176 // applied. If the template-argument represents a set of
3177 // overloaded functions (or a pointer to such), the matching
3178 // function is selected from the set (13.4).
3179 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003180 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003181 // -- For a non-type template-parameter of type reference to
3182 // function, no conversions apply. If the template-argument
3183 // represents a set of overloaded functions, the matching
3184 // function is selected from the set (13.4).
3185 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003186 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003187 // -- For a non-type template-parameter of type pointer to
3188 // member function, no conversions apply. If the
3189 // template-argument represents a set of overloaded member
3190 // functions, the matching member function is selected from
3191 // the set (13.4).
3192 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003193 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003194 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003195
Douglas Gregor064fdb22010-04-14 23:11:21 +00003196 if (Arg->getType() == Context.OverloadTy) {
3197 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3198 true,
3199 FoundResult)) {
3200 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3201 return true;
3202
3203 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3204 ArgType = Arg->getType();
3205 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00003206 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003207 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003208
Douglas Gregorb242683d2010-04-01 18:32:35 +00003209 if (!ParamType->isMemberPointerType())
3210 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3211 ParamType,
3212 Arg, Converted);
3213
3214 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00003215 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00003216 } else if (!Context.hasSameUnqualifiedType(ArgType,
3217 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003218 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003219 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003220 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003221 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003222 Diag(Param->getLocation(), diag::note_template_param_here);
3223 return true;
3224 }
Mike Stump11289f42009-09-09 15:08:12 +00003225
Douglas Gregorb242683d2010-04-01 18:32:35 +00003226 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003227 }
3228
Chris Lattner696197c2009-02-20 21:37:53 +00003229 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003230 // -- for a non-type template-parameter of type pointer to
3231 // object, qualification conversions (4.4) and the
3232 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00003233 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00003234 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003235 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003236
Douglas Gregorb242683d2010-04-01 18:32:35 +00003237 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3238 ParamType,
3239 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00003240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003242 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003243 // -- For a non-type template-parameter of type reference to
3244 // object, no conversions apply. The type referred to by the
3245 // reference may be more cv-qualified than the (otherwise
3246 // identical) type of the template-argument. The
3247 // template-parameter is bound directly to the
3248 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00003249 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003250 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003251
Douglas Gregor064fdb22010-04-14 23:11:21 +00003252 if (Arg->getType() == Context.OverloadTy) {
3253 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3254 ParamRefType->getPointeeType(),
3255 true,
3256 FoundResult)) {
3257 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3258 return true;
3259
3260 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3261 ArgType = Arg->getType();
3262 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00003263 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003264 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003265
Douglas Gregorb242683d2010-04-01 18:32:35 +00003266 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3267 ParamType,
3268 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003269 }
Douglas Gregor0e558532009-02-11 16:16:59 +00003270
3271 // -- For a non-type template-parameter of type pointer to data
3272 // member, qualification conversions (4.4) are applied.
3273 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3274
Douglas Gregor1515f762009-02-11 18:22:40 +00003275 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003276 // Types match exactly: nothing more to do here.
3277 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00003278 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00003279 } else {
3280 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003281 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003282 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003283 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003284 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003285 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003286 }
3287
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003288 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003289}
3290
3291/// \brief Check a template argument against its corresponding
3292/// template template parameter.
3293///
3294/// This routine implements the semantics of C++ [temp.arg.template].
3295/// It returns true if an error occurred, and false otherwise.
3296bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003297 const TemplateArgumentLoc &Arg) {
3298 TemplateName Name = Arg.getArgument().getAsTemplate();
3299 TemplateDecl *Template = Name.getAsTemplateDecl();
3300 if (!Template) {
3301 // Any dependent template name is fine.
3302 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3303 return false;
3304 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003305
3306 // C++ [temp.arg.template]p1:
3307 // A template-argument for a template template-parameter shall be
3308 // the name of a class template, expressed as id-expression. Only
3309 // primary class templates are considered when matching the
3310 // template template argument with the corresponding parameter;
3311 // partial specializations are not considered even if their
3312 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003313 //
3314 // Note that we also allow template template parameters here, which
3315 // will happen when we are dealing with, e.g., class template
3316 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003317 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003318 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003319 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003320 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003321 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003322 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003323 << Template;
3324 }
3325
3326 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3327 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003328 true,
3329 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003330 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003331}
3332
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003333/// \brief Given a non-type template argument that refers to a
3334/// declaration and the type of its corresponding non-type template
3335/// parameter, produce an expression that properly refers to that
3336/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003337ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003338Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3339 QualType ParamType,
3340 SourceLocation Loc) {
3341 assert(Arg.getKind() == TemplateArgument::Declaration &&
3342 "Only declaration template arguments permitted here");
3343 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3344
3345 if (VD->getDeclContext()->isRecord() &&
3346 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3347 // If the value is a class member, we might have a pointer-to-member.
3348 // Determine whether the non-type template template parameter is of
3349 // pointer-to-member type. If so, we need to build an appropriate
3350 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3351 // would refer to the member itself.
3352 if (ParamType->isMemberPointerType()) {
3353 QualType ClassType
3354 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3355 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003356 = NestedNameSpecifier::Create(Context, 0, false,
3357 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003358 CXXScopeSpec SS;
3359 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003360 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003361 VD->getType().getNonReferenceType(),
3362 Loc,
3363 &SS);
3364 if (RefExpr.isInvalid())
3365 return ExprError();
3366
John McCalle3027922010-08-25 11:45:40 +00003367 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003368
3369 // We might need to perform a trailing qualification conversion, since
3370 // the element type on the parameter could be more qualified than the
3371 // element type in the expression we constructed.
3372 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3373 ParamType.getUnqualifiedType())) {
3374 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003375 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003376 RefExpr = Owned(RefE);
3377 }
3378
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003379 assert(!RefExpr.isInvalid() &&
3380 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003381 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003382 return move(RefExpr);
3383 }
3384 }
3385
3386 QualType T = VD->getType().getNonReferenceType();
3387 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003388 // When the non-type template parameter is a pointer, take the
3389 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003390 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003391 if (RefExpr.isInvalid())
3392 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003393
3394 if (T->isFunctionType() || T->isArrayType()) {
3395 // Decay functions and arrays.
3396 Expr *RefE = (Expr *)RefExpr.get();
3397 DefaultFunctionArrayConversion(RefE);
3398 if (RefE != RefExpr.get()) {
3399 RefExpr.release();
3400 RefExpr = Owned(RefE);
3401 }
3402
3403 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003404 }
3405
Douglas Gregorb242683d2010-04-01 18:32:35 +00003406 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003407 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003408 }
3409
3410 // If the non-type template parameter has reference type, qualify the
3411 // resulting declaration reference with the extra qualifiers on the
3412 // type that the reference refers to.
3413 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3414 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3415
3416 return BuildDeclRefExpr(VD, T, Loc);
3417}
3418
3419/// \brief Construct a new expression that refers to the given
3420/// integral template argument with the given source-location
3421/// information.
3422///
3423/// This routine takes care of the mapping from an integral template
3424/// argument (which may have any integral type) to the appropriate
3425/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003426ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003427Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3428 SourceLocation Loc) {
3429 assert(Arg.getKind() == TemplateArgument::Integral &&
3430 "Operation is only value for integral template arguments");
3431 QualType T = Arg.getIntegralType();
3432 if (T->isCharType() || T->isWideCharType())
3433 return Owned(new (Context) CharacterLiteral(
3434 Arg.getAsIntegral()->getZExtValue(),
3435 T->isWideCharType(),
3436 T,
3437 Loc));
3438 if (T->isBooleanType())
3439 return Owned(new (Context) CXXBoolLiteralExpr(
3440 Arg.getAsIntegral()->getBoolValue(),
3441 T,
3442 Loc));
3443
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003444 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003445}
3446
3447
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003448/// \brief Determine whether the given template parameter lists are
3449/// equivalent.
3450///
Mike Stump11289f42009-09-09 15:08:12 +00003451/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003452/// source code as part of a new template declaration.
3453///
3454/// \param Old The old template parameter list, typically found via
3455/// name lookup of the template declared with this template parameter
3456/// list.
3457///
3458/// \param Complain If true, this routine will produce a diagnostic if
3459/// the template parameter lists are not equivalent.
3460///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003461/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003462///
3463/// \param TemplateArgLoc If this source location is valid, then we
3464/// are actually checking the template parameter list of a template
3465/// argument (New) against the template parameter list of its
3466/// corresponding template template parameter (Old). We produce
3467/// slightly different diagnostics in this scenario.
3468///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003469/// \returns True if the template parameter lists are equal, false
3470/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003471bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003472Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3473 TemplateParameterList *Old,
3474 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003475 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003476 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003477 if (Old->size() != New->size()) {
3478 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003479 unsigned NextDiag = diag::err_template_param_list_different_arity;
3480 if (TemplateArgLoc.isValid()) {
3481 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3482 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003483 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003484 Diag(New->getTemplateLoc(), NextDiag)
3485 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003486 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003487 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003488 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003489 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003490 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3491 }
3492
3493 return false;
3494 }
3495
3496 for (TemplateParameterList::iterator OldParm = Old->begin(),
3497 OldParmEnd = Old->end(), NewParm = New->begin();
3498 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3499 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003500 if (Complain) {
3501 unsigned NextDiag = diag::err_template_param_different_kind;
3502 if (TemplateArgLoc.isValid()) {
3503 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3504 NextDiag = diag::note_template_param_different_kind;
3505 }
3506 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003507 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003508 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003509 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003510 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003511 return false;
3512 }
3513
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003514 if (TemplateTypeParmDecl *OldTTP
3515 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3516 // Template type parameters are equivalent if either both are template
3517 // type parameter packs or neither are (since we know we're at the same
3518 // index).
3519 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3520 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3521 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3522 // allow one to match a template parameter pack in the template
3523 // parameter list of a template template parameter to one or more
3524 // template parameters in the template parameter list of the
3525 // corresponding template template argument.
3526 if (Complain) {
3527 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3528 if (TemplateArgLoc.isValid()) {
3529 Diag(TemplateArgLoc,
3530 diag::err_template_arg_template_params_mismatch);
3531 NextDiag = diag::note_template_parameter_pack_non_pack;
3532 }
3533 Diag(NewTTP->getLocation(), NextDiag)
3534 << 0 << NewTTP->isParameterPack();
3535 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3536 << 0 << OldTTP->isParameterPack();
3537 }
3538 return false;
3539 }
Mike Stump11289f42009-09-09 15:08:12 +00003540 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003541 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3542 // The types of non-type template parameters must agree.
3543 NonTypeTemplateParmDecl *NewNTTP
3544 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003545
3546 // If we are matching a template template argument to a template
3547 // template parameter and one of the non-type template parameter types
3548 // is dependent, then we must wait until template instantiation time
3549 // to actually compare the arguments.
3550 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3551 (OldNTTP->getType()->isDependentType() ||
3552 NewNTTP->getType()->isDependentType()))
3553 continue;
3554
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003555 if (Context.getCanonicalType(OldNTTP->getType()) !=
3556 Context.getCanonicalType(NewNTTP->getType())) {
3557 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003558 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3559 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003560 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003561 diag::err_template_arg_template_params_mismatch);
3562 NextDiag = diag::note_template_nontype_parm_different_type;
3563 }
3564 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003565 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003566 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003567 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003568 diag::note_template_nontype_parm_prev_declaration)
3569 << OldNTTP->getType();
3570 }
3571 return false;
3572 }
3573 } else {
3574 // The template parameter lists of template template
3575 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003576 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003577 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003578 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003579 = cast<TemplateTemplateParmDecl>(*OldParm);
3580 TemplateTemplateParmDecl *NewTTP
3581 = cast<TemplateTemplateParmDecl>(*NewParm);
3582 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3583 OldTTP->getTemplateParameters(),
3584 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003585 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003586 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003587 return false;
3588 }
3589 }
3590
3591 return true;
3592}
3593
3594/// \brief Check whether a template can be declared within this scope.
3595///
3596/// If the template declaration is valid in this scope, returns
3597/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003598bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003599Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003600 // Find the nearest enclosing declaration scope.
3601 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3602 (S->getFlags() & Scope::TemplateParamScope) != 0)
3603 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003604
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003605 // C++ [temp]p2:
3606 // A template-declaration can appear only as a namespace scope or
3607 // class scope declaration.
3608 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003609 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3610 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003611 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003612 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003613
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003614 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003615 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003616
3617 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3618 return false;
3619
Mike Stump11289f42009-09-09 15:08:12 +00003620 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003621 diag::err_template_outside_namespace_or_class_scope)
3622 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003623}
Douglas Gregor67a65642009-02-17 23:15:12 +00003624
Douglas Gregor54888652009-10-07 00:13:32 +00003625/// \brief Determine what kind of template specialization the given declaration
3626/// is.
3627static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3628 if (!D)
3629 return TSK_Undeclared;
3630
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003631 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3632 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003633 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3634 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003635 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3636 return Var->getTemplateSpecializationKind();
3637
Douglas Gregor54888652009-10-07 00:13:32 +00003638 return TSK_Undeclared;
3639}
3640
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003641/// \brief Check whether a specialization is well-formed in the current
3642/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003643///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003644/// This routine determines whether a template specialization can be declared
3645/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003646///
3647/// \param S the semantic analysis object for which this check is being
3648/// performed.
3649///
3650/// \param Specialized the entity being specialized or instantiated, which
3651/// may be a kind of template (class template, function template, etc.) or
3652/// a member of a class template (member function, static data member,
3653/// member class).
3654///
3655/// \param PrevDecl the previous declaration of this entity, if any.
3656///
3657/// \param Loc the location of the explicit specialization or instantiation of
3658/// this entity.
3659///
3660/// \param IsPartialSpecialization whether this is a partial specialization of
3661/// a class template.
3662///
Douglas Gregor54888652009-10-07 00:13:32 +00003663/// \returns true if there was an error that we cannot recover from, false
3664/// otherwise.
3665static bool CheckTemplateSpecializationScope(Sema &S,
3666 NamedDecl *Specialized,
3667 NamedDecl *PrevDecl,
3668 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003669 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003670 // Keep these "kind" numbers in sync with the %select statements in the
3671 // various diagnostics emitted by this routine.
3672 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003673 bool isTemplateSpecialization = false;
3674 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003675 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003676 isTemplateSpecialization = true;
3677 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003678 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003679 isTemplateSpecialization = true;
3680 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003681 EntityKind = 3;
3682 else if (isa<VarDecl>(Specialized))
3683 EntityKind = 4;
3684 else if (isa<RecordDecl>(Specialized))
3685 EntityKind = 5;
3686 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003687 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3688 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003689 return true;
3690 }
3691
Douglas Gregorf47b9112009-02-25 22:02:03 +00003692 // C++ [temp.expl.spec]p2:
3693 // An explicit specialization shall be declared in the namespace
3694 // of which the template is a member, or, for member templates, in
3695 // the namespace of which the enclosing class or enclosing class
3696 // template is a member. An explicit specialization of a member
3697 // function, member class or static data member of a class
3698 // template shall be declared in the namespace of which the class
3699 // template is a member. Such a declaration may also be a
3700 // definition. If the declaration is not a definition, the
3701 // specialization may be defined later in the name- space in which
3702 // the explicit specialization was declared, or in a namespace
3703 // that encloses the one in which the explicit specialization was
3704 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00003705 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00003706 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003707 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003708 return true;
3709 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003710
Douglas Gregor40fb7442009-10-07 17:30:37 +00003711 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3712 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003713 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003714 return true;
3715 }
3716
Douglas Gregore4b05162009-10-07 17:21:34 +00003717 // C++ [temp.class.spec]p6:
3718 // A class template partial specialization may be declared or redeclared
3719 // in any namespace scope in which its definition may be defined (14.5.1
3720 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003721 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003722 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003723 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003724 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003725 if ((!PrevDecl ||
3726 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3727 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregorb1aab432010-09-12 05:08:28 +00003728 // C++ [temp.exp.spec]p2:
3729 // An explicit specialization shall be declared in the namespace of which
3730 // the template is a member, or, for member templates, in the namespace
3731 // of which the enclosing class or enclosing class template is a member.
3732 // An explicit specialization of a member function, member class or
3733 // static data member of a class template shall be declared in the
3734 // namespace of which the class template is a member.
3735 //
3736 // C++0x [temp.expl.spec]p2:
3737 // An explicit specialization shall be declared in a namespace enclosing
3738 // the specialized template.
3739 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3740 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregor8ce63152010-09-12 05:24:55 +00003741 bool IsCPlusPlus0xExtension
3742 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003743 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003744 S.Diag(Loc, IsCPlusPlus0xExtension
3745 ? diag::ext_template_spec_decl_out_of_scope_global
3746 : diag::err_template_spec_decl_out_of_scope_global)
3747 << EntityKind << Specialized;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003748 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003749 S.Diag(Loc, IsCPlusPlus0xExtension
3750 ? diag::ext_template_spec_decl_out_of_scope
3751 : diag::err_template_spec_decl_out_of_scope)
3752 << EntityKind << Specialized
3753 << cast<NamedDecl>(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003754
3755 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3756 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003757 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003758 }
Douglas Gregor54888652009-10-07 00:13:32 +00003759
3760 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003761 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003762 // Note that HandleDeclarator() performs this check for explicit
3763 // specializations of function templates, static data members, and member
3764 // functions, so we skip the check here for those kinds of entities.
3765 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003766 // Should we refactor that check, so that it occurs later?
3767 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003768 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3769 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003770 if (isa<TranslationUnitDecl>(SpecializedContext))
3771 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3772 << EntityKind << Specialized;
3773 else if (isa<NamespaceDecl>(SpecializedContext))
3774 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3775 << EntityKind << Specialized
3776 << cast<NamedDecl>(SpecializedContext);
3777
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003778 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003779 }
Douglas Gregor54888652009-10-07 00:13:32 +00003780
3781 // FIXME: check for specialization-after-instantiation errors and such.
3782
Douglas Gregorf47b9112009-02-25 22:02:03 +00003783 return false;
3784}
Douglas Gregor54888652009-10-07 00:13:32 +00003785
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003786/// \brief Check the non-type template arguments of a class template
3787/// partial specialization according to C++ [temp.class.spec]p9.
3788///
Douglas Gregor09a30232009-06-12 22:08:06 +00003789/// \param TemplateParams the template parameters of the primary class
3790/// template.
3791///
3792/// \param TemplateArg the template arguments of the class template
3793/// partial specialization.
3794///
3795/// \param MirrorsPrimaryTemplate will be set true if the class
3796/// template partial specialization arguments are identical to the
3797/// implicit template arguments of the primary template. This is not
3798/// necessarily an error (C++0x), and it is left to the caller to diagnose
3799/// this condition when it is an error.
3800///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003801/// \returns true if there was an error, false otherwise.
3802bool Sema::CheckClassTemplatePartialSpecializationArgs(
3803 TemplateParameterList *TemplateParams,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003804 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003805 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003806 // FIXME: the interface to this function will have to change to
3807 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003808 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003809
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003810 const TemplateArgument *ArgList = TemplateArgs.data();
Mike Stump11289f42009-09-09 15:08:12 +00003811
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003812 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003813 // Determine whether the template argument list of the partial
3814 // specialization is identical to the implicit argument list of
3815 // the primary template. The caller may need to diagnostic this as
3816 // an error per C++ [temp.class.spec]p9b3.
3817 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003818 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003819 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3820 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003821 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003822 MirrorsPrimaryTemplate = false;
3823 } else if (TemplateTemplateParmDecl *TTP
3824 = dyn_cast<TemplateTemplateParmDecl>(
3825 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003826 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003827 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003828 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003829 if (!ArgDecl ||
3830 ArgDecl->getIndex() != TTP->getIndex() ||
3831 ArgDecl->getDepth() != TTP->getDepth())
3832 MirrorsPrimaryTemplate = false;
3833 }
3834 }
3835
Mike Stump11289f42009-09-09 15:08:12 +00003836 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003837 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003838 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003839 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003840 }
3841
Anders Carlsson40c1d492009-06-13 18:20:51 +00003842 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003843 if (!ArgExpr) {
3844 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003845 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003846 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003847
3848 // C++ [temp.class.spec]p8:
3849 // A non-type argument is non-specialized if it is the name of a
3850 // non-type parameter. All other non-type arguments are
3851 // specialized.
3852 //
3853 // Below, we check the two conditions that only apply to
3854 // specialized non-type arguments, so skip any non-specialized
3855 // arguments.
3856 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003857 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003858 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003859 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003860 (Param->getIndex() != NTTP->getIndex() ||
3861 Param->getDepth() != NTTP->getDepth()))
3862 MirrorsPrimaryTemplate = false;
3863
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003864 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003865 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003866
3867 // C++ [temp.class.spec]p9:
3868 // Within the argument list of a class template partial
3869 // specialization, the following restrictions apply:
3870 // -- A partially specialized non-type argument expression
3871 // shall not involve a template parameter of the partial
3872 // specialization except when the argument expression is a
3873 // simple identifier.
3874 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003875 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003876 diag::err_dependent_non_type_arg_in_partial_spec)
3877 << ArgExpr->getSourceRange();
3878 return true;
3879 }
3880
3881 // -- The type of a template parameter corresponding to a
3882 // specialized non-type argument shall not be dependent on a
3883 // parameter of the specialization.
3884 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003885 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003886 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3887 << Param->getType()
3888 << ArgExpr->getSourceRange();
3889 Diag(Param->getLocation(), diag::note_template_param_here);
3890 return true;
3891 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003892
3893 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003894 }
3895
3896 return false;
3897}
3898
Douglas Gregorc854c662010-02-26 06:03:23 +00003899/// \brief Retrieve the previous declaration of the given declaration.
3900static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3901 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3902 return VD->getPreviousDeclaration();
3903 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3904 return FD->getPreviousDeclaration();
3905 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3906 return TD->getPreviousDeclaration();
3907 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3908 return TD->getPreviousDeclaration();
3909 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3910 return FTD->getPreviousDeclaration();
3911 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3912 return CTD->getPreviousDeclaration();
3913 return 0;
3914}
3915
John McCall48871652010-08-21 09:40:31 +00003916DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003917Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3918 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003919 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003920 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003921 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003922 SourceLocation TemplateNameLoc,
3923 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003924 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003925 SourceLocation RAngleLoc,
3926 AttributeList *Attr,
3927 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003928 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003929
Douglas Gregor67a65642009-02-17 23:15:12 +00003930 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003931 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003932 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003933 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3934
3935 if (!ClassTemplate) {
3936 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3937 << (Name.getAsTemplateDecl() &&
3938 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3939 return true;
3940 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003941
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003942 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003943 bool isPartialSpecialization = false;
3944
Douglas Gregorf47b9112009-02-25 22:02:03 +00003945 // Check the validity of the template headers that introduce this
3946 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003947 // FIXME: We probably shouldn't complain about these headers for
3948 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003949 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003950 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003951 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3952 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003953 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003954 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003955 isExplicitSpecialization,
3956 Invalid);
3957 if (Invalid)
3958 return true;
3959
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003960 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3961 if (TemplateParams)
3962 --NumMatchedTemplateParamLists;
3963
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003964 if (TemplateParams && TemplateParams->size() > 0) {
3965 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003966
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003967 // C++ [temp.class.spec]p10:
3968 // The template parameter list of a specialization shall not
3969 // contain default template argument values.
3970 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3971 Decl *Param = TemplateParams->getParam(I);
3972 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3973 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003974 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003975 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003976 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003977 }
3978 } else if (NonTypeTemplateParmDecl *NTTP
3979 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3980 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003981 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003982 diag::err_default_arg_in_partial_spec)
3983 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003984 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003985 }
3986 } else {
3987 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003988 if (TTP->hasDefaultArgument()) {
3989 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003990 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003991 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003992 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003993 }
3994 }
3995 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003996 } else if (TemplateParams) {
3997 if (TUK == TUK_Friend)
3998 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003999 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004000 SourceRange(TemplateParams->getTemplateLoc(),
4001 TemplateParams->getRAngleLoc()))
4002 << SourceRange(LAngleLoc, RAngleLoc);
4003 else
4004 isExplicitSpecialization = true;
4005 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004006 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00004007 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004008 isExplicitSpecialization = true;
4009 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00004010
Douglas Gregor67a65642009-02-17 23:15:12 +00004011 // Check that the specialization uses the same tag kind as the
4012 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004013 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4014 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004015 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004016 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004017 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004018 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00004019 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004020 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00004021 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004022 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00004023 diag::note_previous_use);
4024 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4025 }
4026
Douglas Gregorc40290e2009-03-09 23:48:35 +00004027 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004028 TemplateArgumentListInfo TemplateArgs;
4029 TemplateArgs.setLAngleLoc(LAngleLoc);
4030 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004031 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00004032
Douglas Gregor67a65642009-02-17 23:15:12 +00004033 // Check that the template argument list is well-formed for this
4034 // template.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004035 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00004036 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4037 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004038 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004039
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004040 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor67a65642009-02-17 23:15:12 +00004041 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004042
Douglas Gregor2373c592009-05-31 09:31:02 +00004043 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00004044 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00004045 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00004046 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00004047 if (CheckClassTemplatePartialSpecializationArgs(
4048 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004049 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00004050 return true;
4051
Douglas Gregor09a30232009-06-12 22:08:06 +00004052 if (MirrorsPrimaryTemplate) {
4053 // C++ [temp.class.spec]p9b3:
4054 //
Mike Stump11289f42009-09-09 15:08:12 +00004055 // -- The argument list of the specialization shall not be identical
4056 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00004057 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00004058 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00004059 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00004060 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00004061 ClassTemplate->getIdentifier(),
4062 TemplateNameLoc,
4063 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004064 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00004065 AS_none);
4066 }
4067
Douglas Gregor2208a292009-09-26 20:57:03 +00004068 // FIXME: Diagnose friend partial specializations
4069
Douglas Gregor92354b62010-02-09 00:37:32 +00004070 if (!Name.isDependent() &&
4071 !TemplateSpecializationType::anyDependentTemplateArguments(
4072 TemplateArgs.getArgumentArray(),
4073 TemplateArgs.size())) {
4074 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4075 << ClassTemplate->getDeclName();
4076 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00004077 }
4078 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004079
Douglas Gregor67a65642009-02-17 23:15:12 +00004080 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00004081 ClassTemplateSpecializationDecl *PrevDecl = 0;
4082
4083 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004084 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00004085 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004086 = ClassTemplate->findPartialSpecialization(Converted.data(),
4087 Converted.size(),
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004088 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004089 else
4090 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004091 = ClassTemplate->findSpecialization(Converted.data(),
4092 Converted.size(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00004093
4094 ClassTemplateSpecializationDecl *Specialization = 0;
4095
Douglas Gregorf47b9112009-02-25 22:02:03 +00004096 // Check whether we can declare a class template specialization in
4097 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00004098 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00004099 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004100 TemplateNameLoc,
4101 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004102 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004103
Douglas Gregor15301382009-07-30 17:40:51 +00004104 // The canonical type
4105 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00004106 if (PrevDecl &&
4107 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00004108 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004109 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00004110 // arguments was referenced but not declared, or we're only
4111 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00004112 // declaration node as our own, updating its source location to
4113 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004114 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00004115 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00004116 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00004117 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00004118 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00004119 // Build the canonical type that describes the converted template
4120 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00004121 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4122 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004123 Converted.data(),
4124 Converted.size());
Douglas Gregor15301382009-07-30 17:40:51 +00004125
Douglas Gregor2373c592009-05-31 09:31:02 +00004126 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00004127 ClassTemplatePartialSpecializationDecl *PrevPartial
4128 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00004129 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004130 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00004131 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00004132 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00004133 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00004134 TemplateNameLoc,
4135 TemplateParams,
4136 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004137 Converted.data(),
4138 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00004139 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00004140 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00004141 PrevPartial,
4142 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00004143 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004144 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004145 Partial->setTemplateParameterListsInfo(Context,
4146 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004147 (TemplateParameterList**) TemplateParameterLists.release());
4148 }
Douglas Gregor2373c592009-05-31 09:31:02 +00004149
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004150 if (!PrevPartial)
4151 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004152 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00004153
Douglas Gregor21610382009-10-29 00:04:11 +00004154 // If we are providing an explicit specialization of a member class
4155 // template specialization, make a note of that.
4156 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4157 PrevPartial->setMemberSpecialization();
4158
Douglas Gregor91772d12009-06-13 00:26:55 +00004159 // Check that all of the template parameters of the class template
4160 // partial specialization are deducible from the template
4161 // arguments. If not, this class template partial specialization
4162 // will never be used.
4163 llvm::SmallVector<bool, 8> DeducibleParams;
4164 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004165 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00004166 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004167 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00004168 unsigned NumNonDeducible = 0;
4169 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4170 if (!DeducibleParams[I])
4171 ++NumNonDeducible;
4172
4173 if (NumNonDeducible) {
4174 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4175 << (NumNonDeducible > 1)
4176 << SourceRange(TemplateNameLoc, RAngleLoc);
4177 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4178 if (!DeducibleParams[I]) {
4179 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4180 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00004181 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004182 diag::note_partial_spec_unused_parameter)
4183 << Param->getDeclName();
4184 else
Mike Stump11289f42009-09-09 15:08:12 +00004185 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004186 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00004187 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00004188 }
4189 }
4190 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004191 } else {
4192 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00004193 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004194 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004195 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00004196 ClassTemplate->getDeclContext(),
4197 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004198 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004199 Converted.data(),
4200 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00004201 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004202 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004203 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004204 Specialization->setTemplateParameterListsInfo(Context,
4205 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004206 (TemplateParameterList**) TemplateParameterLists.release());
4207 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004208
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004209 if (!PrevDecl)
4210 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00004211
4212 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004213 }
4214
Douglas Gregor06db9f52009-10-12 20:18:28 +00004215 // C++ [temp.expl.spec]p6:
4216 // If a template, a member template or the member of a class template is
4217 // explicitly specialized then that specialization shall be declared
4218 // before the first use of that specialization that would cause an implicit
4219 // instantiation to take place, in every translation unit in which such a
4220 // use occurs; no diagnostic is required.
4221 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00004222 bool Okay = false;
4223 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4224 // Is there any previous explicit specialization declaration?
4225 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4226 Okay = true;
4227 break;
4228 }
4229 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004230
Douglas Gregorc854c662010-02-26 06:03:23 +00004231 if (!Okay) {
4232 SourceRange Range(TemplateNameLoc, RAngleLoc);
4233 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4234 << Context.getTypeDeclType(Specialization) << Range;
4235
4236 Diag(PrevDecl->getPointOfInstantiation(),
4237 diag::note_instantiation_required_here)
4238 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00004239 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00004240 return true;
4241 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004242 }
4243
Douglas Gregor2208a292009-09-26 20:57:03 +00004244 // If this is not a friend, note that this is an explicit specialization.
4245 if (TUK != TUK_Friend)
4246 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004247
4248 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004249 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004250 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004251 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004252 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00004253 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00004254 Diag(Def->getLocation(), diag::note_previous_definition);
4255 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00004256 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004257 }
4258 }
4259
Douglas Gregord56a91e2009-02-26 22:19:44 +00004260 // Build the fully-sugared type for this class template
4261 // specialization as the user wrote in the specialization
4262 // itself. This means that we'll pretty-print the type retrieved
4263 // from the specialization's declaration the way that the user
4264 // actually wrote the specialization, rather than formatting the
4265 // name based on the "canonical" representation used to store the
4266 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004267 TypeSourceInfo *WrittenTy
4268 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4269 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004270 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00004271 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00004272 if (TemplateParams)
4273 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00004274 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00004275 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00004276
Douglas Gregor1e249f82009-02-25 22:18:32 +00004277 // C++ [temp.expl.spec]p9:
4278 // A template explicit specialization is in the scope of the
4279 // namespace in which the template was defined.
4280 //
4281 // We actually implement this paragraph where we set the semantic
4282 // context (in the creation of the ClassTemplateSpecializationDecl),
4283 // but we also maintain the lexical context where the actual
4284 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004285 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004286
Douglas Gregor67a65642009-02-17 23:15:12 +00004287 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004288 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004289 Specialization->startDefinition();
4290
Douglas Gregor2208a292009-09-26 20:57:03 +00004291 if (TUK == TUK_Friend) {
4292 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4293 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004294 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004295 /*FIXME:*/KWLoc);
4296 Friend->setAccess(AS_public);
4297 CurContext->addDecl(Friend);
4298 } else {
4299 // Add the specialization into its lexical context, so that it can
4300 // be seen when iterating through the list of declarations in that
4301 // context. However, specializations are not found by name lookup.
4302 CurContext->addDecl(Specialization);
4303 }
John McCall48871652010-08-21 09:40:31 +00004304 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004305}
Douglas Gregor333489b2009-03-27 23:10:48 +00004306
John McCall48871652010-08-21 09:40:31 +00004307Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004308 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004309 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004310 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4311}
4312
John McCall48871652010-08-21 09:40:31 +00004313Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004314 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004315 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004316 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4317 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4318 "Not a function declarator!");
4319 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004320
Douglas Gregor17a7c122009-06-24 00:54:41 +00004321 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004322 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004323 }
Mike Stump11289f42009-09-09 15:08:12 +00004324
Douglas Gregor17a7c122009-06-24 00:54:41 +00004325 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004326
John McCall48871652010-08-21 09:40:31 +00004327 Decl *DP = HandleDeclarator(ParentScope, D,
4328 move(TemplateParameterLists),
4329 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004330 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004331 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004332 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004333 FunctionTemplate->getTemplatedDecl());
4334 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4335 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4336 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004337}
4338
John McCall4f7ced62010-02-11 01:33:53 +00004339/// \brief Strips various properties off an implicit instantiation
4340/// that has just been explicitly specialized.
4341static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004342 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004343
4344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4345 FD->setInlineSpecified(false);
4346 }
4347}
4348
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004349/// \brief Diagnose cases where we have an explicit template specialization
4350/// before/after an explicit template instantiation, producing diagnostics
4351/// for those cases where they are required and determining whether the
4352/// new specialization/instantiation will have any effect.
4353///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004354/// \param NewLoc the location of the new explicit specialization or
4355/// instantiation.
4356///
4357/// \param NewTSK the kind of the new explicit specialization or instantiation.
4358///
4359/// \param PrevDecl the previous declaration of the entity.
4360///
4361/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4362///
4363/// \param PrevPointOfInstantiation if valid, indicates where the previus
4364/// declaration was instantiated (either implicitly or explicitly).
4365///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004366/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004367/// specialization or instantiation has no effect and should be ignored.
4368///
4369/// \returns true if there was an error that should prevent the introduction of
4370/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004371bool
4372Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4373 TemplateSpecializationKind NewTSK,
4374 NamedDecl *PrevDecl,
4375 TemplateSpecializationKind PrevTSK,
4376 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004377 bool &HasNoEffect) {
4378 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004379
4380 switch (NewTSK) {
4381 case TSK_Undeclared:
4382 case TSK_ImplicitInstantiation:
4383 assert(false && "Don't check implicit instantiations here");
4384 return false;
4385
4386 case TSK_ExplicitSpecialization:
4387 switch (PrevTSK) {
4388 case TSK_Undeclared:
4389 case TSK_ExplicitSpecialization:
4390 // Okay, we're just specializing something that is either already
4391 // explicitly specialized or has merely been mentioned without any
4392 // instantiation.
4393 return false;
4394
4395 case TSK_ImplicitInstantiation:
4396 if (PrevPointOfInstantiation.isInvalid()) {
4397 // The declaration itself has not actually been instantiated, so it is
4398 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004399 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004400 return false;
4401 }
4402 // Fall through
4403
4404 case TSK_ExplicitInstantiationDeclaration:
4405 case TSK_ExplicitInstantiationDefinition:
4406 assert((PrevTSK == TSK_ImplicitInstantiation ||
4407 PrevPointOfInstantiation.isValid()) &&
4408 "Explicit instantiation without point of instantiation?");
4409
4410 // C++ [temp.expl.spec]p6:
4411 // If a template, a member template or the member of a class template
4412 // is explicitly specialized then that specialization shall be declared
4413 // before the first use of that specialization that would cause an
4414 // implicit instantiation to take place, in every translation unit in
4415 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004416 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4417 // Is there any previous explicit specialization declaration?
4418 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4419 return false;
4420 }
4421
Douglas Gregor1d957a32009-10-27 18:42:08 +00004422 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004423 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004424 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004425 << (PrevTSK != TSK_ImplicitInstantiation);
4426
4427 return true;
4428 }
4429 break;
4430
4431 case TSK_ExplicitInstantiationDeclaration:
4432 switch (PrevTSK) {
4433 case TSK_ExplicitInstantiationDeclaration:
4434 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004435 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004436 return false;
4437
4438 case TSK_Undeclared:
4439 case TSK_ImplicitInstantiation:
4440 // We're explicitly instantiating something that may have already been
4441 // implicitly instantiated; that's fine.
4442 return false;
4443
4444 case TSK_ExplicitSpecialization:
4445 // C++0x [temp.explicit]p4:
4446 // For a given set of template parameters, if an explicit instantiation
4447 // of a template appears after a declaration of an explicit
4448 // specialization for that template, the explicit instantiation has no
4449 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004450 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004451 return false;
4452
4453 case TSK_ExplicitInstantiationDefinition:
4454 // C++0x [temp.explicit]p10:
4455 // If an entity is the subject of both an explicit instantiation
4456 // declaration and an explicit instantiation definition in the same
4457 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004458 Diag(NewLoc,
4459 diag::err_explicit_instantiation_declaration_after_definition);
4460 Diag(PrevPointOfInstantiation,
4461 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004462 assert(PrevPointOfInstantiation.isValid() &&
4463 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004464 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004465 return false;
4466 }
4467 break;
4468
4469 case TSK_ExplicitInstantiationDefinition:
4470 switch (PrevTSK) {
4471 case TSK_Undeclared:
4472 case TSK_ImplicitInstantiation:
4473 // We're explicitly instantiating something that may have already been
4474 // implicitly instantiated; that's fine.
4475 return false;
4476
4477 case TSK_ExplicitSpecialization:
4478 // C++ DR 259, C++0x [temp.explicit]p4:
4479 // For a given set of template parameters, if an explicit
4480 // instantiation of a template appears after a declaration of
4481 // an explicit specialization for that template, the explicit
4482 // instantiation has no effect.
4483 //
4484 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004485 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004486 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004487 if (!getLangOptions().CPlusPlus0x) {
4488 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004489 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004490 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004491 diag::note_previous_template_specialization);
4492 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004493 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004494 return false;
4495
4496 case TSK_ExplicitInstantiationDeclaration:
4497 // We're explicity instantiating a definition for something for which we
4498 // were previously asked to suppress instantiations. That's fine.
4499 return false;
4500
4501 case TSK_ExplicitInstantiationDefinition:
4502 // C++0x [temp.spec]p5:
4503 // For a given template and a given set of template-arguments,
4504 // - an explicit instantiation definition shall appear at most once
4505 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004506 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004507 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004508 Diag(PrevPointOfInstantiation,
4509 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004510 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004511 return false;
4512 }
4513 break;
4514 }
4515
4516 assert(false && "Missing specialization/instantiation case?");
4517
4518 return false;
4519}
4520
John McCallb9c78482010-04-08 09:05:18 +00004521/// \brief Perform semantic analysis for the given dependent function
4522/// template specialization. The only possible way to get a dependent
4523/// function template specialization is with a friend declaration,
4524/// like so:
4525///
4526/// template <class T> void foo(T);
4527/// template <class T> class A {
4528/// friend void foo<>(T);
4529/// };
4530///
4531/// There really isn't any useful analysis we can do here, so we
4532/// just store the information.
4533bool
4534Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4535 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4536 LookupResult &Previous) {
4537 // Remove anything from Previous that isn't a function template in
4538 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00004539 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00004540 LookupResult::Filter F = Previous.makeFilter();
4541 while (F.hasNext()) {
4542 NamedDecl *D = F.next()->getUnderlyingDecl();
4543 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00004544 !FDLookupContext->InEnclosingNamespaceSetOf(
4545 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00004546 F.erase();
4547 }
4548 F.done();
4549
4550 // Should this be diagnosed here?
4551 if (Previous.empty()) return true;
4552
4553 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4554 ExplicitTemplateArgs);
4555 return false;
4556}
4557
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004558/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004559/// specialization.
4560///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004561/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004562/// explicit function template specialization. On successful completion,
4563/// the function declaration \p FD will become a function template
4564/// specialization.
4565///
4566/// \param FD the function declaration, which will be updated to become a
4567/// function template specialization.
4568///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004569/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4570/// if any. Note that this may be valid info even when 0 arguments are
4571/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4572/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004573///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004574/// \param PrevDecl the set of declarations that may be specialized by
4575/// this function specialization.
4576bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004577Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004578 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004579 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004580 // The set of function template specializations that could match this
4581 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004582 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004583
Sebastian Redl50c68252010-08-31 00:36:30 +00004584 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00004585 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4586 I != E; ++I) {
4587 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4588 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004589 // Only consider templates found within the same semantic lookup scope as
4590 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00004591 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4592 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004593 continue;
4594
4595 // C++ [temp.expl.spec]p11:
4596 // A trailing template-argument can be left unspecified in the
4597 // template-id naming an explicit function template specialization
4598 // provided it can be deduced from the function argument type.
4599 // Perform template argument deduction to determine whether we may be
4600 // specializing this template.
4601 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004602 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004603 FunctionDecl *Specialization = 0;
4604 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004605 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004606 FD->getType(),
4607 Specialization,
4608 Info)) {
4609 // FIXME: Template argument deduction failed; record why it failed, so
4610 // that we can provide nifty diagnostics.
4611 (void)TDK;
4612 continue;
4613 }
4614
4615 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004616 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004617 }
4618 }
4619
Douglas Gregor5de279c2009-09-26 03:41:46 +00004620 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004621 UnresolvedSetIterator Result
4622 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4623 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004624 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004625 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004626 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004627 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004628 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004629 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004630 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004631
4632 // Ignore access information; it doesn't figure into redeclaration checking.
4633 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004634 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004635
4636 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004637 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004638
4639 // If this is a friend declaration, then we're not really declaring
4640 // an explicit specialization.
4641 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004642
Douglas Gregor54888652009-10-07 00:13:32 +00004643 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004644 if (!isFriend &&
4645 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004646 Specialization->getPrimaryTemplate(),
4647 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004648 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004649 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004650
4651 // C++ [temp.expl.spec]p6:
4652 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004653 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004654 // before the first use of that specialization that would cause an implicit
4655 // instantiation to take place, in every translation unit in which such a
4656 // use occurs; no diagnostic is required.
4657 FunctionTemplateSpecializationInfo *SpecInfo
4658 = Specialization->getTemplateSpecializationInfo();
4659 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004660
Abramo Bagnara8075c852010-06-12 07:44:57 +00004661 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004662 if (!isFriend &&
4663 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004664 TSK_ExplicitSpecialization,
4665 Specialization,
4666 SpecInfo->getTemplateSpecializationKind(),
4667 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004668 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004669 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004670
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004671 // Mark the prior declaration as an explicit specialization, so that later
4672 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004673 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004674 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004675 MarkUnusedFileScopedDecl(Specialization);
4676 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004677
4678 // Turn the given function declaration into a function template
4679 // specialization, with the template arguments from the previous
4680 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004681 // Take copies of (semantic and syntactic) template argument lists.
4682 const TemplateArgumentList* TemplArgs = new (Context)
4683 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4684 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4685 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004686 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004687 TemplArgs, /*InsertPos=*/0,
4688 SpecInfo->getTemplateSpecializationKind(),
4689 TemplArgsAsWritten);
4690
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004691 // The "previous declaration" for this function template specialization is
4692 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004693 Previous.clear();
4694 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004695 return false;
4696}
4697
Douglas Gregor86d142a2009-10-08 07:24:58 +00004698/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004699/// specialization.
4700///
4701/// This routine performs all of the semantic analysis required for an
4702/// explicit member function specialization. On successful completion,
4703/// the function declaration \p FD will become a member function
4704/// specialization.
4705///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004706/// \param Member the member declaration, which will be updated to become a
4707/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004708///
John McCall1f82f242009-11-18 22:49:29 +00004709/// \param Previous the set of declarations, one of which may be specialized
4710/// by this function specialization; the set will be modified to contain the
4711/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004712bool
John McCall1f82f242009-11-18 22:49:29 +00004713Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004714 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004715
Douglas Gregor86d142a2009-10-08 07:24:58 +00004716 // Try to find the member we are instantiating.
4717 NamedDecl *Instantiation = 0;
4718 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004719 MemberSpecializationInfo *MSInfo = 0;
4720
John McCall1f82f242009-11-18 22:49:29 +00004721 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004722 // Nowhere to look anyway.
4723 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004724 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4725 I != E; ++I) {
4726 NamedDecl *D = (*I)->getUnderlyingDecl();
4727 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004728 if (Context.hasSameType(Function->getType(), Method->getType())) {
4729 Instantiation = Method;
4730 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004731 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004732 break;
4733 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004734 }
4735 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004736 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004737 VarDecl *PrevVar;
4738 if (Previous.isSingleResult() &&
4739 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004740 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004741 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004742 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004743 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004744 }
4745 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004746 CXXRecordDecl *PrevRecord;
4747 if (Previous.isSingleResult() &&
4748 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4749 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004750 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004751 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004752 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004753 }
4754
4755 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004756 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004757 // specializations are always out-of-line, the caller will complain about
4758 // this mismatch later.
4759 return false;
4760 }
John McCalle820e5e2010-04-13 20:37:33 +00004761
4762 // If this is a friend, just bail out here before we start turning
4763 // things into explicit specializations.
4764 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4765 // Preserve instantiation information.
4766 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4767 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4768 cast<CXXMethodDecl>(InstantiatedFrom),
4769 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4770 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4771 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4772 cast<CXXRecordDecl>(InstantiatedFrom),
4773 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4774 }
4775
4776 Previous.clear();
4777 Previous.addDecl(Instantiation);
4778 return false;
4779 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004780
Douglas Gregor86d142a2009-10-08 07:24:58 +00004781 // Make sure that this is a specialization of a member.
4782 if (!InstantiatedFrom) {
4783 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4784 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004785 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4786 return true;
4787 }
4788
Douglas Gregor06db9f52009-10-12 20:18:28 +00004789 // C++ [temp.expl.spec]p6:
4790 // If a template, a member template or the member of a class template is
4791 // explicitly specialized then that spe- cialization shall be declared
4792 // before the first use of that specialization that would cause an implicit
4793 // instantiation to take place, in every translation unit in which such a
4794 // use occurs; no diagnostic is required.
4795 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004796
Abramo Bagnara8075c852010-06-12 07:44:57 +00004797 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004798 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4799 TSK_ExplicitSpecialization,
4800 Instantiation,
4801 MSInfo->getTemplateSpecializationKind(),
4802 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004803 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004804 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004805
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004806 // Check the scope of this explicit specialization.
4807 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004808 InstantiatedFrom,
4809 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004810 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004811 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004812
Douglas Gregor86d142a2009-10-08 07:24:58 +00004813 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004814 // the original declaration to note that it is an explicit specialization
4815 // (if it was previously an implicit instantiation). This latter step
4816 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004817 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004818 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4819 if (InstantiationFunction->getTemplateSpecializationKind() ==
4820 TSK_ImplicitInstantiation) {
4821 InstantiationFunction->setTemplateSpecializationKind(
4822 TSK_ExplicitSpecialization);
4823 InstantiationFunction->setLocation(Member->getLocation());
4824 }
4825
Douglas Gregor86d142a2009-10-08 07:24:58 +00004826 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4827 cast<CXXMethodDecl>(InstantiatedFrom),
4828 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004829 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004830 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004831 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4832 if (InstantiationVar->getTemplateSpecializationKind() ==
4833 TSK_ImplicitInstantiation) {
4834 InstantiationVar->setTemplateSpecializationKind(
4835 TSK_ExplicitSpecialization);
4836 InstantiationVar->setLocation(Member->getLocation());
4837 }
4838
Douglas Gregor86d142a2009-10-08 07:24:58 +00004839 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4840 cast<VarDecl>(InstantiatedFrom),
4841 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004842 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004843 } else {
4844 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004845 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4846 if (InstantiationClass->getTemplateSpecializationKind() ==
4847 TSK_ImplicitInstantiation) {
4848 InstantiationClass->setTemplateSpecializationKind(
4849 TSK_ExplicitSpecialization);
4850 InstantiationClass->setLocation(Member->getLocation());
4851 }
4852
Douglas Gregor86d142a2009-10-08 07:24:58 +00004853 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004854 cast<CXXRecordDecl>(InstantiatedFrom),
4855 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004856 }
4857
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004858 // Save the caller the trouble of having to figure out which declaration
4859 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004860 Previous.clear();
4861 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004862 return false;
4863}
4864
Douglas Gregore47f5a72009-10-14 23:41:34 +00004865/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004866///
4867/// \returns true if a serious error occurs, false otherwise.
4868static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004869 SourceLocation InstLoc,
4870 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00004871 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4872 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004873
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004874 if (CurContext->isRecord()) {
4875 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4876 << D;
4877 return true;
4878 }
4879
Douglas Gregore47f5a72009-10-14 23:41:34 +00004880 // C++0x [temp.explicit]p2:
4881 // An explicit instantiation shall appear in an enclosing namespace of its
4882 // template.
4883 //
4884 // This is DR275, which we do not retroactively apply to C++98/03.
4885 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004886 !CurContext->Encloses(OrigContext)) {
4887 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004888 S.Diag(InstLoc,
4889 S.getLangOptions().CPlusPlus0x?
4890 diag::err_explicit_instantiation_out_of_scope
4891 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004892 << D << NS;
4893 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004894 S.Diag(InstLoc,
4895 S.getLangOptions().CPlusPlus0x?
4896 diag::err_explicit_instantiation_must_be_global
4897 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004898 << D;
4899 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004900 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004901 }
Sebastian Redl50c68252010-08-31 00:36:30 +00004902
Douglas Gregore47f5a72009-10-14 23:41:34 +00004903 // C++0x [temp.explicit]p2:
4904 // If the name declared in the explicit instantiation is an unqualified
4905 // name, the explicit instantiation shall appear in the namespace where
4906 // its template is declared or, if that namespace is inline (7.3.1), any
4907 // namespace from its enclosing namespace set.
4908 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004909 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004910
4911 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004912 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004913
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004914 S.Diag(InstLoc,
4915 S.getLangOptions().CPlusPlus0x?
4916 diag::err_explicit_instantiation_unqualified_wrong_namespace
4917 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl50c68252010-08-31 00:36:30 +00004918 << D << OrigContext;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004919 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004920 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004921}
4922
4923/// \brief Determine whether the given scope specifier has a template-id in it.
4924static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4925 if (!SS.isSet())
4926 return false;
4927
4928 // C++0x [temp.explicit]p2:
4929 // If the explicit instantiation is for a member function, a member class
4930 // or a static data member of a class template specialization, the name of
4931 // the class template specialization in the qualified-id for the member
4932 // name shall be a simple-template-id.
4933 //
4934 // C++98 has the same restriction, just worded differently.
4935 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4936 NNS; NNS = NNS->getPrefix())
4937 if (Type *T = NNS->getAsType())
4938 if (isa<TemplateSpecializationType>(T))
4939 return true;
4940
4941 return false;
4942}
4943
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004944// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004945DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004946Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004947 SourceLocation ExternLoc,
4948 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004949 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004950 SourceLocation KWLoc,
4951 const CXXScopeSpec &SS,
4952 TemplateTy TemplateD,
4953 SourceLocation TemplateNameLoc,
4954 SourceLocation LAngleLoc,
4955 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004956 SourceLocation RAngleLoc,
4957 AttributeList *Attr) {
4958 // Find the class template we're specializing
4959 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004960 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004961 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4962
4963 // Check that the specialization uses the same tag kind as the
4964 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004965 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4966 assert(Kind != TTK_Enum &&
4967 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004968 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004969 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004970 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004971 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004972 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004973 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004974 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004975 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004976 diag::note_previous_use);
4977 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4978 }
4979
Douglas Gregore47f5a72009-10-14 23:41:34 +00004980 // C++0x [temp.explicit]p2:
4981 // There are two forms of explicit instantiation: an explicit instantiation
4982 // definition and an explicit instantiation declaration. An explicit
4983 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004984 TemplateSpecializationKind TSK
4985 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4986 : TSK_ExplicitInstantiationDeclaration;
4987
Douglas Gregora1f49972009-05-13 00:25:59 +00004988 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004989 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004990 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004991
4992 // Check that the template argument list is well-formed for this
4993 // template.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004994 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00004995 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4996 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004997 return true;
4998
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004999 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregora1f49972009-05-13 00:25:59 +00005000 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00005001
Douglas Gregora1f49972009-05-13 00:25:59 +00005002 // Find the class template specialization declaration that
5003 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00005004 void *InsertPos = 0;
5005 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005006 = ClassTemplate->findSpecialization(Converted.data(),
5007 Converted.size(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00005008
Abramo Bagnara8075c852010-06-12 07:44:57 +00005009 TemplateSpecializationKind PrevDecl_TSK
5010 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5011
Douglas Gregor54888652009-10-07 00:13:32 +00005012 // C++0x [temp.explicit]p2:
5013 // [...] An explicit instantiation shall appear in an enclosing
5014 // namespace of its template. [...]
5015 //
5016 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00005017 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5018 SS.isSet()))
5019 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00005020
Douglas Gregora1f49972009-05-13 00:25:59 +00005021 ClassTemplateSpecializationDecl *Specialization = 0;
5022
Douglas Gregor0681a352009-11-25 06:01:46 +00005023 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005024 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00005025 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00005026 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00005027 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00005028 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005029 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00005030 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00005031
Abramo Bagnara8075c852010-06-12 07:44:57 +00005032 // Even though HasNoEffect == true means that this explicit instantiation
5033 // has no effect on semantics, we go on to put its syntax in the AST.
5034
5035 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5036 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005037 // Since the only prior class template specialization with these
5038 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00005039 // declaration node as our own, updating the source location
5040 // for the template name to reflect our new declaration.
5041 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005042 Specialization = PrevDecl;
5043 Specialization->setLocation(TemplateNameLoc);
5044 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00005045 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005046 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00005047 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00005048
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005049 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00005050 // Create a new class template specialization declaration node for
5051 // this explicit specialization.
5052 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00005053 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00005054 ClassTemplate->getDeclContext(),
5055 TemplateNameLoc,
5056 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005057 Converted.data(),
5058 Converted.size(),
5059 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00005060 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00005061
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00005062 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005063 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00005064 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005065 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005066 }
5067
5068 // Build the fully-sugared type for this explicit instantiation as
5069 // the user wrote in the explicit instantiation itself. This means
5070 // that we'll pretty-print the type retrieved from the
5071 // specialization's declaration the way that the user actually wrote
5072 // the explicit instantiation, rather than formatting the name based
5073 // on the "canonical" representation used to store the template
5074 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00005075 TypeSourceInfo *WrittenTy
5076 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5077 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00005078 Context.getTypeDeclType(Specialization));
5079 Specialization->setTypeAsWritten(WrittenTy);
5080 TemplateArgsIn.release();
5081
Abramo Bagnara8075c852010-06-12 07:44:57 +00005082 // Set source locations for keywords.
5083 Specialization->setExternLoc(ExternLoc);
5084 Specialization->setTemplateKeywordLoc(TemplateLoc);
5085
5086 // Add the explicit instantiation into its lexical context. However,
5087 // since explicit instantiations are never found by name lookup, we
5088 // just put it into the declaration context directly.
5089 Specialization->setLexicalDeclContext(CurContext);
5090 CurContext->addDecl(Specialization);
5091
5092 // Syntax is now OK, so return if it has no other effect on semantics.
5093 if (HasNoEffect) {
5094 // Set the template specialization kind.
5095 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005096 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00005097 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005098
5099 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00005100 // A definition of a class template or class member template
5101 // shall be in scope at the point of the explicit instantiation of
5102 // the class template or class member template.
5103 //
5104 // This check comes when we actually try to perform the
5105 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00005106 ClassTemplateSpecializationDecl *Def
5107 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005108 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005109 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00005110 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005111 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00005112 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005113 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5114 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005115
Douglas Gregor1d957a32009-10-27 18:42:08 +00005116 // Instantiate the members of this class template specialization.
5117 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005118 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00005119 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00005120 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5121
5122 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5123 // TSK_ExplicitInstantiationDefinition
5124 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5125 TSK == TSK_ExplicitInstantiationDefinition)
5126 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005127
Douglas Gregor12e49d32009-10-15 22:53:21 +00005128 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005129 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005130
Abramo Bagnara8075c852010-06-12 07:44:57 +00005131 // Set the template specialization kind.
5132 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005133 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00005134}
5135
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005136// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00005137DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00005138Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00005139 SourceLocation ExternLoc,
5140 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005141 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005142 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005143 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005144 IdentifierInfo *Name,
5145 SourceLocation NameLoc,
5146 AttributeList *Attr) {
5147
Douglas Gregord6ab8742009-05-28 23:31:59 +00005148 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00005149 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00005150 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00005151 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5152 MultiTemplateParamsArg(*this, 0, 0),
Douglas Gregor0bf31402010-10-08 23:50:27 +00005153 Owned, IsDependent, false,
5154 TypeResult());
John McCall7f41d982009-09-11 04:59:25 +00005155 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5156
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005157 if (!TagD)
5158 return true;
5159
John McCall48871652010-08-21 09:40:31 +00005160 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005161 if (Tag->isEnum()) {
5162 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5163 << Context.getTypeDeclType(Tag);
5164 return true;
5165 }
5166
Douglas Gregorb8006faf2009-05-27 17:30:49 +00005167 if (Tag->isInvalidDecl())
5168 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005169
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005170 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5171 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5172 if (!Pattern) {
5173 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5174 << Context.getTypeDeclType(Record);
5175 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5176 return true;
5177 }
5178
Douglas Gregore47f5a72009-10-14 23:41:34 +00005179 // C++0x [temp.explicit]p2:
5180 // If the explicit instantiation is for a class or member class, the
5181 // elaborated-type-specifier in the declaration shall include a
5182 // simple-template-id.
5183 //
5184 // C++98 has the same restriction, just worded differently.
5185 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00005186 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005187 << Record << SS.getRange();
5188
5189 // C++0x [temp.explicit]p2:
5190 // There are two forms of explicit instantiation: an explicit instantiation
5191 // definition and an explicit instantiation declaration. An explicit
5192 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00005193 TemplateSpecializationKind TSK
5194 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5195 : TSK_ExplicitInstantiationDeclaration;
5196
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005197 // C++0x [temp.explicit]p2:
5198 // [...] An explicit instantiation shall appear in an enclosing
5199 // namespace of its template. [...]
5200 //
5201 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00005202 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005203
5204 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00005205 CXXRecordDecl *PrevDecl
5206 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005207 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00005208 PrevDecl = Record;
5209 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005210 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00005211 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005212 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00005213 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005214 PrevDecl,
5215 MSInfo->getTemplateSpecializationKind(),
5216 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005217 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005218 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005219 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005220 return TagD;
5221 }
5222
Douglas Gregor12e49d32009-10-15 22:53:21 +00005223 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005224 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005225 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00005226 // C++ [temp.explicit]p3:
5227 // A definition of a member class of a class template shall be in scope
5228 // at the point of an explicit instantiation of the member class.
5229 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005230 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00005231 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00005232 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5233 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00005234 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5235 << Pattern;
5236 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005237 } else {
5238 if (InstantiateClass(NameLoc, Record, Def,
5239 getTemplateInstantiationArgs(Record),
5240 TSK))
5241 return true;
5242
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005243 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00005244 if (!RecordDef)
5245 return true;
5246 }
5247 }
5248
5249 // Instantiate all of the members of the class.
5250 InstantiateClassMembers(NameLoc, RecordDef,
5251 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005252
Douglas Gregor88d292c2010-05-13 16:44:06 +00005253 if (TSK == TSK_ExplicitInstantiationDefinition)
5254 MarkVTableUsed(NameLoc, RecordDef, true);
5255
Mike Stump87c57ac2009-05-16 07:39:55 +00005256 // FIXME: We don't have any representation for explicit instantiations of
5257 // member classes. Such a representation is not needed for compilation, but it
5258 // should be available for clients that want to see all of the declarations in
5259 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005260 return TagD;
5261}
5262
John McCallfaf5fb42010-08-26 23:41:50 +00005263DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5264 SourceLocation ExternLoc,
5265 SourceLocation TemplateLoc,
5266 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005267 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005268 // TODO: check if/when DNInfo should replace Name.
5269 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5270 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00005271 if (!Name) {
5272 if (!D.isInvalidType())
5273 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5274 diag::err_explicit_instantiation_requires_name)
5275 << D.getDeclSpec().getSourceRange()
5276 << D.getSourceRange();
5277
5278 return true;
5279 }
5280
5281 // The scope passed in may not be a decl scope. Zip up the scope tree until
5282 // we find one that is.
5283 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5284 (S->getFlags() & Scope::TemplateParamScope) != 0)
5285 S = S->getParent();
5286
5287 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005288 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5289 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005290 if (R.isNull())
5291 return true;
5292
5293 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5294 // Cannot explicitly instantiate a typedef.
5295 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5296 << Name;
5297 return true;
5298 }
5299
Douglas Gregor3c74d412009-10-14 20:14:33 +00005300 // C++0x [temp.explicit]p1:
5301 // [...] An explicit instantiation of a function template shall not use the
5302 // inline or constexpr specifiers.
5303 // Presumably, this also applies to member functions of class templates as
5304 // well.
5305 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5306 Diag(D.getDeclSpec().getInlineSpecLoc(),
5307 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005308 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005309
5310 // FIXME: check for constexpr specifier.
5311
Douglas Gregore47f5a72009-10-14 23:41:34 +00005312 // C++0x [temp.explicit]p2:
5313 // There are two forms of explicit instantiation: an explicit instantiation
5314 // definition and an explicit instantiation declaration. An explicit
5315 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005316 TemplateSpecializationKind TSK
5317 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5318 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005319
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005320 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005321 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005322
5323 if (!R->isFunctionType()) {
5324 // C++ [temp.explicit]p1:
5325 // A [...] static data member of a class template can be explicitly
5326 // instantiated from the member definition associated with its class
5327 // template.
John McCall27b18f82009-11-17 02:14:36 +00005328 if (Previous.isAmbiguous())
5329 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005330
John McCall67c00872009-12-02 08:25:40 +00005331 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005332 if (!Prev || !Prev->isStaticDataMember()) {
5333 // We expect to see a data data member here.
5334 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5335 << Name;
5336 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5337 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005338 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005339 return true;
5340 }
5341
5342 if (!Prev->getInstantiatedFromStaticDataMember()) {
5343 // FIXME: Check for explicit specialization?
5344 Diag(D.getIdentifierLoc(),
5345 diag::err_explicit_instantiation_data_member_not_instantiated)
5346 << Prev;
5347 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5348 // FIXME: Can we provide a note showing where this was declared?
5349 return true;
5350 }
5351
Douglas Gregore47f5a72009-10-14 23:41:34 +00005352 // C++0x [temp.explicit]p2:
5353 // If the explicit instantiation is for a member function, a member class
5354 // or a static data member of a class template specialization, the name of
5355 // the class template specialization in the qualified-id for the member
5356 // name shall be a simple-template-id.
5357 //
5358 // C++98 has the same restriction, just worded differently.
5359 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5360 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005361 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005362 << Prev << D.getCXXScopeSpec().getRange();
5363
5364 // Check the scope of this explicit instantiation.
5365 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5366
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005367 // Verify that it is okay to explicitly instantiate here.
5368 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5369 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005370 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005371 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005372 MSInfo->getTemplateSpecializationKind(),
5373 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005374 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005375 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005376 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005377 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005378
Douglas Gregor450f00842009-09-25 18:43:00 +00005379 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005380 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005381 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005382 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005383
5384 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005385 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005386 }
5387
Douglas Gregor0e876e02009-09-25 23:53:26 +00005388 // If the declarator is a template-id, translate the parser's template
5389 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005390 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005391 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005392 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5393 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005394 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5395 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005396 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5397 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005398 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005399 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005400 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005401 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005402 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005403
Douglas Gregor450f00842009-09-25 18:43:00 +00005404 // C++ [temp.explicit]p1:
5405 // A [...] function [...] can be explicitly instantiated from its template.
5406 // A member function [...] of a class template can be explicitly
5407 // instantiated from the member definition associated with its class
5408 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005409 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005410 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5411 P != PEnd; ++P) {
5412 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005413 if (!HasExplicitTemplateArgs) {
5414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5415 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5416 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005417
John McCall58cc69d2010-01-27 01:50:18 +00005418 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005419 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5420 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005421 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005422 }
5423 }
5424
5425 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5426 if (!FunTmpl)
5427 continue;
5428
John McCallbc077cf2010-02-08 23:07:23 +00005429 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005430 FunctionDecl *Specialization = 0;
5431 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005432 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005433 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005434 R, Specialization, Info)) {
5435 // FIXME: Keep track of almost-matches?
5436 (void)TDK;
5437 continue;
5438 }
5439
John McCall58cc69d2010-01-27 01:50:18 +00005440 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005441 }
5442
5443 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005444 UnresolvedSetIterator Result
5445 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005446 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005447 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5448 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5449 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005450
John McCall58cc69d2010-01-27 01:50:18 +00005451 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005452 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005453
5454 // Ignore access control bits, we don't need them for redeclaration checking.
5455 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005456
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005457 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005458 Diag(D.getIdentifierLoc(),
5459 diag::err_explicit_instantiation_member_function_not_instantiated)
5460 << Specialization
5461 << (Specialization->getTemplateSpecializationKind() ==
5462 TSK_ExplicitSpecialization);
5463 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5464 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005465 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005466
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005467 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005468 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5469 PrevDecl = Specialization;
5470
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005471 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005472 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005473 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005474 PrevDecl,
5475 PrevDecl->getTemplateSpecializationKind(),
5476 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005477 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005478 return true;
5479
5480 // FIXME: We may still want to build some representation of this
5481 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005482 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005483 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005484 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005485
5486 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005487
5488 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005489 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005490
Douglas Gregore47f5a72009-10-14 23:41:34 +00005491 // C++0x [temp.explicit]p2:
5492 // If the explicit instantiation is for a member function, a member class
5493 // or a static data member of a class template specialization, the name of
5494 // the class template specialization in the qualified-id for the member
5495 // name shall be a simple-template-id.
5496 //
5497 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005498 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005499 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005500 D.getCXXScopeSpec().isSet() &&
5501 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5502 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005503 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005504 << Specialization << D.getCXXScopeSpec().getRange();
5505
5506 CheckExplicitInstantiationScope(*this,
5507 FunTmpl? (NamedDecl *)FunTmpl
5508 : Specialization->getInstantiatedFromMemberFunction(),
5509 D.getIdentifierLoc(),
5510 D.getCXXScopeSpec().isSet());
5511
Douglas Gregor450f00842009-09-25 18:43:00 +00005512 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005513 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005514}
5515
John McCallfaf5fb42010-08-26 23:41:50 +00005516TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005517Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5518 const CXXScopeSpec &SS, IdentifierInfo *Name,
5519 SourceLocation TagLoc, SourceLocation NameLoc) {
5520 // This has to hold, because SS is expected to be defined.
5521 assert(Name && "Expected a name in a dependent tag");
5522
5523 NestedNameSpecifier *NNS
5524 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5525 if (!NNS)
5526 return true;
5527
Abramo Bagnara6150c882010-05-11 21:36:43 +00005528 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005529
Douglas Gregorba41d012010-04-24 16:38:41 +00005530 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5531 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005532 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005533 return true;
5534 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005535
5536 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005537 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005538}
5539
John McCallfaf5fb42010-08-26 23:41:50 +00005540TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005541Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5542 const CXXScopeSpec &SS, const IdentifierInfo &II,
5543 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005544 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005545 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5546 if (!NNS)
5547 return true;
5548
Douglas Gregorf7d77712010-06-16 22:31:08 +00005549 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5550 !getLangOptions().CPlusPlus0x)
5551 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5552 << FixItHint::CreateRemoval(TypenameLoc);
5553
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005554 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005555 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005556 if (T.isNull())
5557 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005558
5559 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5560 if (isa<DependentNameType>(T)) {
5561 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005562 TL.setKeywordLoc(TypenameLoc);
5563 TL.setQualifierRange(SS.getRange());
5564 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005565 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005566 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005567 TL.setKeywordLoc(TypenameLoc);
5568 TL.setQualifierRange(SS.getRange());
5569 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005570 }
5571
John McCallba7bf592010-08-24 05:47:05 +00005572 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005573}
5574
John McCallfaf5fb42010-08-26 23:41:50 +00005575TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005576Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5577 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005578 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005579 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5580 !getLangOptions().CPlusPlus0x)
5581 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5582 << FixItHint::CreateRemoval(TypenameLoc);
5583
John McCallf7bcc812010-05-28 23:32:21 +00005584 TypeSourceInfo *InnerTSI = 0;
5585 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005586
5587 assert(isa<TemplateSpecializationType>(T) &&
5588 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005589
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005590 if (computeDeclContext(SS, false)) {
5591 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005592 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005593 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005594
5595 // Push the inner type, preserving its source locations if possible.
5596 TypeLocBuilder Builder;
5597 if (InnerTSI)
5598 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5599 else
5600 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5601
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005602 /* Note: NNS already embedded in template specialization type T. */
5603 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005604 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5605 TL.setKeywordLoc(TypenameLoc);
5606 TL.setQualifierRange(SS.getRange());
5607
5608 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005609 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005610 }
Mike Stump11289f42009-09-09 15:08:12 +00005611
John McCallc392f372010-06-11 00:33:02 +00005612 // TODO: it's really silly that we make a template specialization
5613 // type earlier only to drop it again here.
5614 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5615 DependentTemplateName *DTN =
5616 TST->getTemplateName().getAsDependentTemplateName();
5617 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005618 assert(DTN->getQualifier()
5619 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5620 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5621 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005622 DTN->getIdentifier(),
5623 TST->getNumArgs(),
5624 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005625 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005626 DependentTemplateSpecializationTypeLoc TL =
5627 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5628 if (InnerTSI) {
5629 TemplateSpecializationTypeLoc TSTL =
5630 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5631 TL.setLAngleLoc(TSTL.getLAngleLoc());
5632 TL.setRAngleLoc(TSTL.getRAngleLoc());
5633 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5634 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5635 } else {
5636 TL.initializeLocal(SourceLocation());
5637 }
John McCallf7bcc812010-05-28 23:32:21 +00005638 TL.setKeywordLoc(TypenameLoc);
5639 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005640 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005641}
5642
Douglas Gregor333489b2009-03-27 23:10:48 +00005643/// \brief Build the type that describes a C++ typename specifier,
5644/// e.g., "typename T::type".
5645QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005646Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5647 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005648 SourceLocation KeywordLoc, SourceRange NNSRange,
5649 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005650 CXXScopeSpec SS;
5651 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005652 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005653
John McCall0b66eb32010-05-01 00:40:08 +00005654 DeclContext *Ctx = computeDeclContext(SS);
5655 if (!Ctx) {
5656 // If the nested-name-specifier is dependent and couldn't be
5657 // resolved to a type, build a typename type.
5658 assert(NNS->isDependent());
5659 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005660 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005661
John McCall0b66eb32010-05-01 00:40:08 +00005662 // If the nested-name-specifier refers to the current instantiation,
5663 // the "typename" keyword itself is superfluous. In C++03, the
5664 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5665 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005666 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005667
John McCall0b66eb32010-05-01 00:40:08 +00005668 if (RequireCompleteDeclContext(SS, Ctx))
5669 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005670
5671 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005672 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005673 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005674 unsigned DiagID = 0;
5675 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005676 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005677 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005678 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005679 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005680
5681 case LookupResult::NotFoundInCurrentInstantiation:
5682 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005683 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005684
5685 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005686 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005687 // We found a type. Build an ElaboratedType, since the
5688 // typename-specifier was just sugar.
5689 return Context.getElaboratedType(ETK_Typename, NNS,
5690 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005691 }
5692
5693 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005694 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005695 break;
5696
John McCalle61f2ba2009-11-18 02:36:19 +00005697 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005698 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005699 return QualType();
5700
Douglas Gregor333489b2009-03-27 23:10:48 +00005701 case LookupResult::FoundOverloaded:
5702 DiagID = diag::err_typename_nested_not_type;
5703 Referenced = *Result.begin();
5704 break;
5705
John McCall6538c932009-10-10 05:48:19 +00005706 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005707 return QualType();
5708 }
5709
5710 // If we get here, it's because name lookup did not find a
5711 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005712 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5713 IILoc);
5714 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005715 if (Referenced)
5716 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5717 << Name;
5718 return QualType();
5719}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005720
5721namespace {
5722 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005723 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005724 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005725 SourceLocation Loc;
5726 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005727
Douglas Gregor15acfb92009-08-06 16:20:37 +00005728 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005729 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5730
Mike Stump11289f42009-09-09 15:08:12 +00005731 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005732 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005733 DeclarationName Entity)
5734 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005735 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005736
5737 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005738 /// transformed.
5739 ///
5740 /// For the purposes of type reconstruction, a type has already been
5741 /// transformed if it is NULL or if it is not dependent.
5742 bool AlreadyTransformed(QualType T) {
5743 return T.isNull() || !T->isDependentType();
5744 }
Mike Stump11289f42009-09-09 15:08:12 +00005745
5746 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005747 /// rebuilt.
5748 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005749
Douglas Gregor15acfb92009-08-06 16:20:37 +00005750 /// \brief Returns the name of the entity whose type is being rebuilt.
5751 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005752
Douglas Gregoref6ab412009-10-27 06:26:26 +00005753 /// \brief Sets the "base" location and entity when that
5754 /// information is known based on another transformation.
5755 void setBase(SourceLocation Loc, DeclarationName Entity) {
5756 this->Loc = Loc;
5757 this->Entity = Entity;
5758 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005759 };
5760}
5761
Douglas Gregor15acfb92009-08-06 16:20:37 +00005762/// \brief Rebuilds a type within the context of the current instantiation.
5763///
Mike Stump11289f42009-09-09 15:08:12 +00005764/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005765/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005766/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005767/// partial specialization thereof). This routine will rebuild that type now
5768/// that we have entered the declarator's scope, which may produce different
5769/// canonical types, e.g.,
5770///
5771/// \code
5772/// template<typename T>
5773/// struct X {
5774/// typedef T* pointer;
5775/// pointer data();
5776/// };
5777///
5778/// template<typename T>
5779/// typename X<T>::pointer X<T>::data() { ... }
5780/// \endcode
5781///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005782/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005783/// since we do not know that we can look into X<T> when we parsed the type.
5784/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005785/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005786/// as the canonical type of T*, allowing the return types of the out-of-line
5787/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005788TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5789 SourceLocation Loc,
5790 DeclarationName Name) {
5791 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005792 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005793
Douglas Gregor15acfb92009-08-06 16:20:37 +00005794 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5795 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005796}
Douglas Gregorbe999392009-09-15 16:23:51 +00005797
John McCalldadc5752010-08-24 06:29:42 +00005798ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005799 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5800 DeclarationName());
5801 return Rebuilder.TransformExpr(E);
5802}
5803
John McCall99b2fe52010-04-29 23:50:39 +00005804bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5805 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005806
5807 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5808 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5809 DeclarationName());
5810 NestedNameSpecifier *Rebuilt =
5811 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005812 if (!Rebuilt) return true;
5813
5814 SS.setScopeRep(Rebuilt);
5815 return false;
John McCall2408e322010-04-27 00:57:59 +00005816}
5817
Douglas Gregorbe999392009-09-15 16:23:51 +00005818/// \brief Produces a formatted string that describes the binding of
5819/// template parameters to template arguments.
5820std::string
5821Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5822 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005823 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00005824}
5825
5826std::string
5827Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5828 const TemplateArgument *Args,
5829 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005830 std::string Result;
5831
Douglas Gregore62e6a02009-11-11 19:13:48 +00005832 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005833 return Result;
5834
5835 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005836 if (I >= NumArgs)
5837 break;
5838
Douglas Gregorbe999392009-09-15 16:23:51 +00005839 if (I == 0)
5840 Result += "[with ";
5841 else
5842 Result += ", ";
5843
5844 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5845 Result += Id->getName();
5846 } else {
5847 Result += '$';
5848 Result += llvm::utostr(I);
5849 }
5850
5851 Result += " = ";
5852
5853 switch (Args[I].getKind()) {
5854 case TemplateArgument::Null:
5855 Result += "<no value>";
5856 break;
5857
5858 case TemplateArgument::Type: {
5859 std::string TypeStr;
5860 Args[I].getAsType().getAsStringInternal(TypeStr,
5861 Context.PrintingPolicy);
5862 Result += TypeStr;
5863 break;
5864 }
5865
5866 case TemplateArgument::Declaration: {
5867 bool Unnamed = true;
5868 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5869 if (ND->getDeclName()) {
5870 Unnamed = false;
5871 Result += ND->getNameAsString();
5872 }
5873 }
5874
5875 if (Unnamed) {
5876 Result += "<anonymous>";
5877 }
5878 break;
5879 }
5880
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005881 case TemplateArgument::Template: {
5882 std::string Str;
5883 llvm::raw_string_ostream OS(Str);
5884 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5885 Result += OS.str();
5886 break;
5887 }
5888
Douglas Gregorbe999392009-09-15 16:23:51 +00005889 case TemplateArgument::Integral: {
5890 Result += Args[I].getAsIntegral()->toString(10);
5891 break;
5892 }
5893
5894 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005895 // FIXME: This is non-optimal, since we're regurgitating the
5896 // expression we were given.
5897 std::string Str;
5898 {
5899 llvm::raw_string_ostream OS(Str);
5900 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5901 Context.PrintingPolicy);
5902 }
5903 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005904 break;
5905 }
5906
5907 case TemplateArgument::Pack:
5908 // FIXME: Format template argument packs
5909 Result += "<template argument pack>";
5910 break;
5911 }
5912 }
5913
5914 Result += ']';
5915 return Result;
5916}