blob: 3b1a03d9c508703af30093b29d6d76ec96c5ec9c [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall4e2cbb22010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor5f3aeb62010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall19510852010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000032
John McCall78b81052010-11-10 02:40:36 +000033// Exported for use by Parser.
34SourceRange
35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39}
40
Douglas Gregor2dd078a2009-09-02 22:59:36 +000041/// \brief Determine whether the declaration found is acceptable as the name
42/// of a template and, if so, return that template declaration. Otherwise,
43/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000047
Douglas Gregor2dd078a2009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000049 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
67
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor2dd078a2009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 return 0;
77}
78
Douglas Gregor312eadb2011-04-24 05:37:28 +000079void Sema::FilterAcceptableTemplateNames(LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
Douglas Gregor312eadb2011-04-24 05:37:28 +000085 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000088 else if (Repl != Orig) {
89
90 // C++ [temp.local]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000091 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor01e56ae2010-04-12 20:54:26 +000092 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
Richard Smith3e4c6c42011-05-05 21:57:07 +000095 // is used as a template-name, the reference refers to the class
96 // template itself and not a specialization thereof, and is not
Douglas Gregor01e56ae2010-04-12 20:54:26 +000097 // ambiguous.
Douglas Gregor01e56ae2010-04-12 20:54:26 +000098 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
99 if (!ClassTemplates.insert(ClassTmpl)) {
100 filter.erase();
101 continue;
102 }
John McCall8ba66912010-08-13 07:02:08 +0000103
104 // FIXME: we promote access to public here as a workaround to
105 // the fact that LookupResult doesn't let us remember that we
106 // found this template through a particular injected class name,
107 // which means we end up doing nasty things to the invariants.
108 // Pretending that access is public is *much* safer.
109 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000110 }
John McCallf7a1a742009-11-24 19:00:30 +0000111 }
112 filter.done();
113}
114
Douglas Gregor312eadb2011-04-24 05:37:28 +0000115bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R) {
116 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
117 if (isAcceptableTemplateName(Context, *I))
118 return true;
119
Douglas Gregor3b887352011-04-27 04:48:22 +0000120 return false;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000121}
122
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000123TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000124 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000125 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000126 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000127 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000128 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000129 TemplateTy &TemplateResult,
130 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000131 assert(getLangOptions().CPlusPlus && "No template names in C!");
132
Douglas Gregor014e88d2009-11-03 23:16:33 +0000133 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000134 MemberOfUnknownSpecialization = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000135
Douglas Gregor014e88d2009-11-03 23:16:33 +0000136 switch (Name.getKind()) {
137 case UnqualifiedId::IK_Identifier:
138 TName = DeclarationName(Name.Identifier);
139 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000140
Douglas Gregor014e88d2009-11-03 23:16:33 +0000141 case UnqualifiedId::IK_OperatorFunctionId:
142 TName = Context.DeclarationNames.getCXXOperatorName(
143 Name.OperatorFunctionId.Operator);
144 break;
145
Sean Hunte6252d12009-11-28 08:58:14 +0000146 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000147 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
148 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000149
Douglas Gregor014e88d2009-11-03 23:16:33 +0000150 default:
151 return TNK_Non_template;
152 }
Mike Stump1eb44332009-09-09 15:08:12 +0000153
John McCallb3d87482010-08-24 05:47:05 +0000154 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000155
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000156 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000157 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000158 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
159 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000160 if (R.empty()) return TNK_Non_template;
161 if (R.isAmbiguous()) {
162 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000163 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000164
165 // FIXME: we might have ambiguous templates, in which case we
166 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000167 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000168 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000169
John McCall0bd6feb2009-12-02 08:04:21 +0000170 TemplateName Template;
171 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000172
John McCall0bd6feb2009-12-02 08:04:21 +0000173 unsigned ResultCount = R.end() - R.begin();
174 if (ResultCount > 1) {
175 // We assume that we'll preserve the qualifier from a function
176 // template name in other ways.
177 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
178 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000179
180 // We'll do this lookup again later.
181 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000182 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000183 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
184
185 if (SS.isSet() && !SS.isInvalid()) {
186 NestedNameSpecifier *Qualifier
187 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000188 Template = Context.getQualifiedTemplateName(Qualifier,
189 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000190 } else {
191 Template = TemplateName(TD);
192 }
193
John McCallb8592062010-08-13 02:23:42 +0000194 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000195 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000196
197 // We'll do this lookup again later.
198 R.suppressDiagnostics();
199 } else {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000200 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
201 isa<TypeAliasTemplateDecl>(TD));
John McCall0bd6feb2009-12-02 08:04:21 +0000202 TemplateKind = TNK_Type_template;
203 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000204 }
Mike Stump1eb44332009-09-09 15:08:12 +0000205
John McCall0bd6feb2009-12-02 08:04:21 +0000206 TemplateResult = TemplateTy::make(Template);
207 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000208}
209
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000210bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor84d0a192010-01-12 21:28:44 +0000211 SourceLocation IILoc,
212 Scope *S,
213 const CXXScopeSpec *SS,
214 TemplateTy &SuggestedTemplate,
215 TemplateNameKind &SuggestedKind) {
216 // We can't recover unless there's a dependent scope specifier preceding the
217 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000218 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000219 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
220 computeDeclContext(*SS))
221 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000222
Douglas Gregor84d0a192010-01-12 21:28:44 +0000223 // The code is missing a 'template' keyword prior to the dependent template
224 // name.
225 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
226 Diag(IILoc, diag::err_template_kw_missing)
227 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000228 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000229 SuggestedTemplate
Douglas Gregor84d0a192010-01-12 21:28:44 +0000230 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
231 SuggestedKind = TNK_Dependent_template_name;
232 return true;
233}
234
John McCallf7a1a742009-11-24 19:00:30 +0000235void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000236 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000237 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000238 bool EnteringContext,
239 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000240 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000241 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000242 DeclContext *LookupCtx = 0;
243 bool isDependent = false;
244 if (!ObjectType.isNull()) {
245 // This nested-name-specifier occurs in a member access expression, e.g.,
246 // x->B::f, and we are looking into the type of the object.
247 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
248 LookupCtx = computeDeclContext(ObjectType);
249 isDependent = ObjectType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000250 assert((isDependent || !ObjectType->isIncompleteType()) &&
John McCallf7a1a742009-11-24 19:00:30 +0000251 "Caller should have completed object type");
Douglas Gregor1d7049a2012-01-12 16:11:24 +0000252
253 // Template names cannot appear inside an Objective-C class or object type.
254 if (ObjectType->isObjCObjectOrInterfaceType()) {
255 Found.clear();
256 return;
257 }
John McCallf7a1a742009-11-24 19:00:30 +0000258 } else if (SS.isSet()) {
259 // This nested-name-specifier occurs after another nested-name-specifier,
260 // so long into the context associated with the prior nested-name-specifier.
261 LookupCtx = computeDeclContext(SS, EnteringContext);
262 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000263
John McCallf7a1a742009-11-24 19:00:30 +0000264 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000265 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000266 return;
267 }
268
269 bool ObjectTypeSearchedInScope = false;
270 if (LookupCtx) {
271 // Perform "qualified" name lookup into the declaration context we
272 // computed, which is either the type of the base of a member access
273 // expression or the declaration context associated with a prior
274 // nested-name-specifier.
275 LookupQualifiedName(Found, LookupCtx);
276
277 if (!ObjectType.isNull() && Found.empty()) {
278 // C++ [basic.lookup.classref]p1:
279 // In a class member access expression (5.2.5), if the . or -> token is
280 // immediately followed by an identifier followed by a <, the
281 // identifier must be looked up to determine whether the < is the
282 // beginning of a template argument list (14.2) or a less-than operator.
283 // The identifier is first looked up in the class of the object
284 // expression. If the identifier is not found, it is then looked up in
285 // the context of the entire postfix-expression and shall name a class
286 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000287 if (S) LookupName(Found, S);
288 ObjectTypeSearchedInScope = true;
289 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000290 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000291 // We cannot look into a dependent object type or nested nme
292 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000293 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000294 return;
295 } else {
296 // Perform unqualified name lookup in the current scope.
297 LookupName(Found, S);
298 }
299
Douglas Gregor2e933882010-01-12 17:06:20 +0000300 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000301 // If we did not find any names, attempt to correct any typos.
302 DeclarationName Name = Found.getLookupName();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000303 Found.clear();
Kaelyn Uhrainf8ec8c92012-01-13 23:10:36 +0000304 // Simple filter callback that, for keywords, only accepts the C++ *_cast
305 CorrectionCandidateCallback FilterCCC;
306 FilterCCC.WantTypeSpecifiers = false;
307 FilterCCC.WantExpressionKeywords = false;
308 FilterCCC.WantRemainingKeywords = false;
309 FilterCCC.WantCXXNamedCasts = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000310 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
311 Found.getLookupKind(), S, &SS,
Kaelyn Uhrainf8ec8c92012-01-13 23:10:36 +0000312 &FilterCCC, LookupCtx)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000313 Found.setLookupName(Corrected.getCorrection());
314 if (Corrected.getCorrectionDecl())
315 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000316 FilterAcceptableTemplateNames(Found);
John McCallad00b772010-06-16 08:42:20 +0000317 if (!Found.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000318 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
319 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregorbfea2392009-12-31 08:11:17 +0000320 if (LookupCtx)
321 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000322 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
323 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000324 else
325 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000326 << Name << CorrectedQuotedStr
327 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000328 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
329 Diag(Template->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000330 << CorrectedQuotedStr;
John McCallad00b772010-06-16 08:42:20 +0000331 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000332 } else {
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000333 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000334 }
335 }
336
Douglas Gregor312eadb2011-04-24 05:37:28 +0000337 FilterAcceptableTemplateNames(Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000338 if (Found.empty()) {
339 if (isDependent)
340 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000341 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000342 }
John McCallf7a1a742009-11-24 19:00:30 +0000343
344 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
345 // C++ [basic.lookup.classref]p1:
346 // [...] If the lookup in the class of the object expression finds a
347 // template, the name is also looked up in the context of the entire
348 // postfix-expression and [...]
349 //
350 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
351 LookupOrdinaryName);
352 LookupName(FoundOuter, S);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000353 FilterAcceptableTemplateNames(FoundOuter);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354
John McCallf7a1a742009-11-24 19:00:30 +0000355 if (FoundOuter.empty()) {
356 // - if the name is not found, the name found in the class of the
357 // object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000358 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
359 FoundOuter.isAmbiguous()) {
John McCallf7a1a742009-11-24 19:00:30 +0000360 // - if the name is found in the context of the entire
361 // postfix-expression and does not name a class template, the name
362 // found in the class of the object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000363 FoundOuter.clear();
John McCallad00b772010-06-16 08:42:20 +0000364 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000365 // - if the name found is a class template, it must refer to the same
366 // entity as the one found in the class of the object expression,
367 // otherwise the program is ill-formed.
368 if (!Found.isSingleResult() ||
369 Found.getFoundDecl()->getCanonicalDecl()
370 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000372 diag::ext_nested_name_member_ref_lookup_ambiguous)
373 << Found.getLookupName()
374 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000375 Diag(Found.getRepresentativeDecl()->getLocation(),
376 diag::note_ambig_member_ref_object_type)
377 << ObjectType;
378 Diag(FoundOuter.getFoundDecl()->getLocation(),
379 diag::note_ambig_member_ref_scope);
380
381 // Recover by taking the template that we found in the object
382 // expression's type.
383 }
384 }
385 }
386}
387
John McCall2f841ba2009-12-02 03:53:29 +0000388/// ActOnDependentIdExpression - Handle a dependent id-expression that
389/// was just parsed. This is only possible with an explicit scope
390/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000391ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000392Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000393 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000394 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000395 const TemplateArgumentListInfo *TemplateArgs) {
John McCallea1471e2010-05-20 01:18:31 +0000396 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000397
John McCall2f841ba2009-12-02 03:53:29 +0000398 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000399 isa<CXXMethodDecl>(DC) &&
400 cast<CXXMethodDecl>(DC)->isInstance()) {
401 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000402
John McCallf7a1a742009-11-24 19:00:30 +0000403 // Since the 'this' expression is synthesized, we don't need to
404 // perform the double-lookup check.
405 NamedDecl *FirstQualifierInScope = 0;
406
John McCallaa81e162009-12-01 22:10:20 +0000407 return Owned(CXXDependentScopeMemberExpr::Create(Context,
408 /*This*/ 0, ThisType,
409 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000410 /*Op*/ SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +0000411 SS.getWithLocInContext(Context),
John McCallf7a1a742009-11-24 19:00:30 +0000412 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000413 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000414 TemplateArgs));
415 }
416
Abramo Bagnara25777432010-08-11 22:01:17 +0000417 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000418}
419
John McCall60d7b3a2010-08-24 06:29:42 +0000420ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000421Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000422 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000423 const TemplateArgumentListInfo *TemplateArgs) {
424 return Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +0000425 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +0000426 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000427 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000428}
429
Douglas Gregor72c3f312008-12-05 18:15:24 +0000430/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
431/// that the template parameter 'PrevDecl' is being shadowed by a new
432/// declaration at location Loc. Returns true to indicate that this is
433/// an error, and false otherwise.
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000434void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000435 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000436
437 // Microsoft Visual C++ permits template parameters to be shadowed.
Francois Pichet62ec1f22011-09-17 17:15:52 +0000438 if (getLangOptions().MicrosoftExt)
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000439 return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000440
441 // C++ [temp.local]p4:
442 // A template-parameter shall not be redeclared within its
443 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000444 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000445 << cast<NamedDecl>(PrevDecl)->getDeclName();
446 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000447 return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000448}
449
Douglas Gregor2943aed2009-03-03 04:44:36 +0000450/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000451/// the parameter D to reference the templated declaration and return a pointer
452/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000453TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
454 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
455 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000456 return Temp;
457 }
458 return 0;
459}
460
Douglas Gregorba68eca2011-01-05 17:40:24 +0000461ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
462 SourceLocation EllipsisLoc) const {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463 assert(Kind == Template &&
Douglas Gregorba68eca2011-01-05 17:40:24 +0000464 "Only template template arguments can be pack expansions here");
465 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
466 "Template template argument pack expansion without packs");
467 ParsedTemplateArgument Result(*this);
468 Result.EllipsisLoc = EllipsisLoc;
469 return Result;
470}
471
Douglas Gregor788cd062009-11-11 01:00:40 +0000472static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
473 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000474
Douglas Gregor788cd062009-11-11 01:00:40 +0000475 switch (Arg.getKind()) {
476 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000477 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000478 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000479 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000480 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000481 return TemplateArgumentLoc(TemplateArgument(T), DI);
482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000483
Douglas Gregor788cd062009-11-11 01:00:40 +0000484 case ParsedTemplateArgument::NonType: {
485 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
486 return TemplateArgumentLoc(TemplateArgument(E), E);
487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488
Douglas Gregor788cd062009-11-11 01:00:40 +0000489 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000490 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor2be29f42011-01-14 23:41:42 +0000491 TemplateArgument TArg;
492 if (Arg.getEllipsisLoc().isValid())
493 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
494 else
495 TArg = Template;
496 return TemplateArgumentLoc(TArg,
Douglas Gregorb6744ef2011-03-02 17:09:35 +0000497 Arg.getScopeSpec().getWithLocInContext(
498 SemaRef.Context),
Douglas Gregorba68eca2011-01-05 17:40:24 +0000499 Arg.getLocation(),
500 Arg.getEllipsisLoc());
Douglas Gregor788cd062009-11-11 01:00:40 +0000501 }
502 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000503
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000504 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000505}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000506
Douglas Gregor788cd062009-11-11 01:00:40 +0000507/// \brief Translates template arguments as provided by the parser
508/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000509void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
510 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000511 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000512 TemplateArgs.addArgument(translateTemplateArgument(*this,
513 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000514}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000515
Douglas Gregor72c3f312008-12-05 18:15:24 +0000516/// ActOnTypeParameter - Called when a C++ template type parameter
517/// (e.g., "typename T") has been parsed. Typename specifies whether
518/// the keyword "typename" was used to declare the type parameter
519/// (otherwise, "class" was used), and KeyLoc is the location of the
520/// "class" or "typename" keyword. ParamName is the name of the
521/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000522/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000523/// If the type parameter has a default argument, it will be added
524/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000525Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
526 SourceLocation EllipsisLoc,
527 SourceLocation KeyLoc,
528 IdentifierInfo *ParamName,
529 SourceLocation ParamNameLoc,
530 unsigned Depth, unsigned Position,
531 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000532 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000533 assert(S->isTemplateParamScope() &&
534 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000535 bool Invalid = false;
536
537 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000538 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000539 LookupOrdinaryName,
540 ForRedeclaration);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000541 if (PrevDecl && PrevDecl->isTemplateParameter()) {
542 DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl);
543 PrevDecl = 0;
544 }
Douglas Gregor72c3f312008-12-05 18:15:24 +0000545 }
546
Douglas Gregorddc29e12009-02-06 22:42:48 +0000547 SourceLocation Loc = ParamNameLoc;
548 if (!ParamName)
549 Loc = KeyLoc;
550
Douglas Gregor72c3f312008-12-05 18:15:24 +0000551 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000552 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000553 KeyLoc, Loc, Depth, Position, ParamName,
554 Typename, Ellipsis);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000555 Param->setAccess(AS_public);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000556 if (Invalid)
557 Param->setInvalidDecl();
558
559 if (ParamName) {
560 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000561 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000562 IdResolver.AddDecl(Param);
563 }
564
Douglas Gregor61c4d282011-01-05 15:48:55 +0000565 // C++0x [temp.param]p9:
566 // A default template-argument may be specified for any kind of
567 // template-parameter that is not a template parameter pack.
568 if (DefaultArg && Ellipsis) {
569 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
570 DefaultArg = ParsedType();
571 }
572
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000573 // Handle the default argument, if provided.
574 if (DefaultArg) {
575 TypeSourceInfo *DefaultTInfo;
576 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000577
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000578 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579
Douglas Gregor6f526752010-12-16 08:48:57 +0000580 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6f526752010-12-16 08:48:57 +0000582 UPPC_DefaultArgument))
583 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000585 // Check the template argument itself.
586 if (CheckTemplateArgument(Param, DefaultTInfo)) {
587 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000588 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000591 Param->setDefaultArgument(DefaultTInfo, false);
592 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593
John McCalld226f652010-08-21 09:40:31 +0000594 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000595}
596
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597/// \brief Check that the type of a non-type template parameter is
598/// well-formed.
599///
600/// \returns the (possibly-promoted) parameter type if valid;
601/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000602QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000604 // We don't allow variably-modified types as the type of non-type template
605 // parameters.
606 if (T->isVariablyModifiedType()) {
607 Diag(Loc, diag::err_variably_modified_nontype_template_param)
608 << T;
609 return QualType();
610 }
611
Douglas Gregor2943aed2009-03-03 04:44:36 +0000612 // C++ [temp.param]p4:
613 //
614 // A non-type template-parameter shall have one of the following
615 // (optionally cv-qualified) types:
616 //
617 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000618 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000619 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000620 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000621 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000622 T->isReferenceType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000623 // -- pointer to member,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 T->isMemberPointerType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000625 // -- std::nullptr_t.
626 T->isNullPtrType() ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 // If T is a dependent type, we can't do the check now, so we
628 // assume that it is well-formed.
629 T->isDependentType())
630 return T;
631 // C++ [temp.param]p8:
632 //
633 // A non-type template-parameter of type "array of T" or
634 // "function returning T" is adjusted to be of type "pointer to
635 // T" or "pointer to function returning T", respectively.
636 else if (T->isArrayType())
637 // FIXME: Keep the type prior to promotion?
638 return Context.getArrayDecayedType(T);
639 else if (T->isFunctionType())
640 // FIXME: Keep the type prior to promotion?
641 return Context.getPointerType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642
Douglas Gregor2943aed2009-03-03 04:44:36 +0000643 Diag(Loc, diag::err_template_nontype_parm_bad_type)
644 << T;
645
646 return QualType();
647}
648
John McCalld226f652010-08-21 09:40:31 +0000649Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
650 unsigned Depth,
651 unsigned Position,
652 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000653 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000654 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
655 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000656
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000657 assert(S->isTemplateParamScope() &&
658 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000659 bool Invalid = false;
660
661 IdentifierInfo *ParamName = D.getIdentifier();
662 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000663 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000664 LookupOrdinaryName,
665 ForRedeclaration);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000666 if (PrevDecl && PrevDecl->isTemplateParameter()) {
667 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
668 PrevDecl = 0;
669 }
Douglas Gregor72c3f312008-12-05 18:15:24 +0000670 }
671
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000672 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
673 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000674 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000675 Invalid = true;
676 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000677
Douglas Gregor10738d32010-12-23 23:51:58 +0000678 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000679 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000680 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000681 D.getSourceRange().getBegin(),
John McCall7a9813c2010-01-22 00:28:27 +0000682 D.getIdentifierLoc(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000683 Depth, Position, ParamName, T,
Douglas Gregor10738d32010-12-23 23:51:58 +0000684 IsParameterPack, TInfo);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000685 Param->setAccess(AS_public);
686
Douglas Gregor72c3f312008-12-05 18:15:24 +0000687 if (Invalid)
688 Param->setInvalidDecl();
689
690 if (D.getIdentifier()) {
691 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000692 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000693 IdResolver.AddDecl(Param);
694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000695
Douglas Gregor61c4d282011-01-05 15:48:55 +0000696 // C++0x [temp.param]p9:
697 // A default template-argument may be specified for any kind of
698 // template-parameter that is not a template parameter pack.
699 if (Default && IsParameterPack) {
700 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
701 Default = 0;
702 }
703
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000704 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000705 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000706 // Check for unexpanded parameter packs.
707 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
708 return Param;
709
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000710 TemplateArgument Converted;
John Wiegley429bb272011-04-08 18:41:53 +0000711 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
712 if (DefaultRes.isInvalid()) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000713 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000714 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000715 }
John Wiegley429bb272011-04-08 18:41:53 +0000716 Default = DefaultRes.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000717
John McCall9ae2f072010-08-23 23:25:46 +0000718 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000719 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000720
John McCalld226f652010-08-21 09:40:31 +0000721 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000722}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000723
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000724/// ActOnTemplateTemplateParameter - Called when a C++ template template
725/// parameter (e.g. T in template <template <typename> class T> class array)
726/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000727Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
728 SourceLocation TmpLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +0000729 TemplateParameterList *Params,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000730 SourceLocation EllipsisLoc,
John McCalld226f652010-08-21 09:40:31 +0000731 IdentifierInfo *Name,
732 SourceLocation NameLoc,
733 unsigned Depth,
734 unsigned Position,
735 SourceLocation EqualLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000736 ParsedTemplateArgument Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000737 assert(S->isTemplateParamScope() &&
738 "Template template parameter not in template parameter scope!");
739
740 // Construct the parameter object.
Douglas Gregor61c4d282011-01-05 15:48:55 +0000741 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000742 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000743 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000744 NameLoc.isInvalid()? TmpLoc : NameLoc,
745 Depth, Position, IsParameterPack,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000746 Name, Params);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000747 Param->setAccess(AS_public);
748
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000749 // If the template template parameter has a name, then link the identifier
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000750 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000751 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000752 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000753 IdResolver.AddDecl(Param);
754 }
755
Douglas Gregor6f526752010-12-16 08:48:57 +0000756 if (Params->size() == 0) {
757 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
758 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
759 Param->setInvalidDecl();
760 }
761
Douglas Gregor61c4d282011-01-05 15:48:55 +0000762 // C++0x [temp.param]p9:
763 // A default template-argument may be specified for any kind of
764 // template-parameter that is not a template parameter pack.
765 if (IsParameterPack && !Default.isInvalid()) {
766 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
767 Default = ParsedTemplateArgument();
768 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000770 if (!Default.isInvalid()) {
771 // Check only that we have a template template argument. We don't want to
772 // try to check well-formedness now, because our template template parameter
773 // might have dependent types in its template parameters, which we wouldn't
774 // be able to match now.
775 //
776 // If none of the template template parameter's template arguments mention
777 // other template parameters, we could actually perform more checking here.
778 // However, it isn't worth doing.
779 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
780 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
781 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
782 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000783 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000784 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000785
Douglas Gregor6f526752010-12-16 08:48:57 +0000786 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000787 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6f526752010-12-16 08:48:57 +0000788 DefaultArg.getArgument().getAsTemplate(),
789 UPPC_DefaultArgument))
790 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000791
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000792 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000793 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000794
John McCalld226f652010-08-21 09:40:31 +0000795 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000796}
797
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000798/// ActOnTemplateParameterList - Builds a TemplateParameterList that
799/// contains the template parameters in Params/NumParams.
Richard Trieu90ab75b2011-09-09 03:18:59 +0000800TemplateParameterList *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000801Sema::ActOnTemplateParameterList(unsigned Depth,
802 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000803 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000804 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000805 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000806 SourceLocation RAngleLoc) {
807 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000808 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000809
Douglas Gregorddc29e12009-02-06 22:42:48 +0000810 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000811 (NamedDecl**)Params, NumParams,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000812 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000813}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000814
John McCallb6217662010-03-15 10:12:16 +0000815static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
816 if (SS.isSet())
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000817 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +0000818}
819
John McCallf312b1e2010-08-26 23:41:50 +0000820DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000821Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000822 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000823 IdentifierInfo *Name, SourceLocation NameLoc,
824 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000825 TemplateParameterList *TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +0000826 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +0000827 unsigned NumOuterTemplateParamLists,
828 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump1eb44332009-09-09 15:08:12 +0000829 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000830 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000831 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000832 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000833
834 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000835 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000836 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000837
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000838 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
839 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000840
841 // There is no such thing as an unnamed class template.
842 if (!Name) {
843 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000844 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000845 }
846
847 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000848 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000849 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000850 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000851 if (SS.isNotEmpty() && !SS.isInvalid()) {
852 SemanticContext = computeDeclContext(SS, true);
853 if (!SemanticContext) {
854 // FIXME: Produce a reasonable diagnostic here
855 return true;
856 }
Mike Stump1eb44332009-09-09 15:08:12 +0000857
John McCall77bb1aa2010-05-01 00:40:08 +0000858 if (RequireCompleteDeclContext(SS, SemanticContext))
859 return true;
860
Douglas Gregor20606502011-10-14 15:31:12 +0000861 // If we're adding a template to a dependent context, we may need to
862 // rebuilding some of the types used within the template parameter list,
863 // now that we know what the current instantiation is.
864 if (SemanticContext->isDependentContext()) {
865 ContextRAII SavedContext(*this, SemanticContext);
866 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
867 Invalid = true;
868 }
869
John McCalla24dc2e2009-11-17 02:14:36 +0000870 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000871 } else {
872 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000873 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Douglas Gregor57265e32010-04-12 16:00:01 +0000876 if (Previous.isAmbiguous())
877 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000878
Douglas Gregorddc29e12009-02-06 22:42:48 +0000879 NamedDecl *PrevDecl = 0;
880 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000881 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000882
Douglas Gregorddc29e12009-02-06 22:42:48 +0000883 // If there is a previous declaration with the same name, check
884 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000885 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000886 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000887
888 // We may have found the injected-class-name of a class template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000889 // class template partial specialization, or class template specialization.
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000890 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000891 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000892 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
893 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000894 PrevClassTemplate
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000895 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
896 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
897 PrevClassTemplate
898 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
899 ->getSpecializedTemplate();
900 }
901 }
902
John McCall65c49462009-12-18 11:25:59 +0000903 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000904 // C++ [namespace.memdef]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000905 // [...] When looking for a prior declaration of a class or a function
906 // declared as a friend, and when the name of the friend class or
John McCalle129d442009-12-17 23:21:11 +0000907 // function is neither a qualified name nor a template-id, scopes outside
908 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000909 if (!SS.isSet()) {
910 DeclContext *OutermostContext = CurContext;
911 while (!OutermostContext->isFileContext())
912 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000913
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000914 if (PrevDecl &&
915 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
916 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
917 SemanticContext = PrevDecl->getDeclContext();
918 } else {
919 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000920 // context we computed is the semantic context for our new
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000921 // declaration.
922 PrevDecl = PrevClassTemplate = 0;
923 SemanticContext = OutermostContext;
924 }
John McCalle129d442009-12-17 23:21:11 +0000925 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000926
John McCalle129d442009-12-17 23:21:11 +0000927 if (CurContext->isDependentContext()) {
928 // If this is a dependent context, we don't want to link the friend
929 // class template to the template in scope, because that would perform
930 // checking of the template parameter lists that can't be performed
931 // until the outer context is instantiated.
932 PrevDecl = PrevClassTemplate = 0;
933 }
934 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
935 PrevDecl = PrevClassTemplate = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000936
Douglas Gregorddc29e12009-02-06 22:42:48 +0000937 if (PrevClassTemplate) {
938 // Ensure that the template parameter lists are compatible.
939 if (!TemplateParameterListsAreEqual(TemplateParams,
940 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000941 /*Complain=*/true,
942 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000943 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000944
945 // C++ [temp.class]p4:
946 // In a redeclaration, partial specialization, explicit
947 // specialization or explicit instantiation of a class template,
948 // the class-key shall agree in kind with the original class
949 // template declaration (7.1.5.3).
950 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieubbf34c02011-06-10 03:11:26 +0000951 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
952 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000953 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000954 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000955 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000956 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000957 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000958 }
959
Douglas Gregorddc29e12009-02-06 22:42:48 +0000960 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000961 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000962 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000963 Diag(NameLoc, diag::err_redefinition) << Name;
964 Diag(Def->getLocation(), diag::note_previous_definition);
965 // FIXME: Would it make sense to try to "forget" the previous
966 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000967 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000968 }
Douglas Gregor6311d2b2011-09-09 18:32:39 +0000969 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000970 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
971 // Maybe we will complain about the shadowed template parameter.
972 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
973 // Just pretend that we didn't see the previous declaration.
974 PrevDecl = 0;
975 } else if (PrevDecl) {
976 // C++ [temp]p5:
977 // A class template shall not have the same name as any other
978 // template, class, function, object, enumeration, enumerator,
979 // namespace, or type in the same scope (3.3), except as specified
980 // in (14.5.4).
981 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
982 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000983 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000984 }
985
Douglas Gregord684b002009-02-10 19:49:53 +0000986 // Check the template parameter list of this declaration, possibly
987 // merging in the template parameter list from the previous class
988 // template declaration.
989 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000990 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +0000991 (SS.isSet() && SemanticContext &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +0000992 SemanticContext->isRecord() &&
993 SemanticContext->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +0000994 ? TPC_ClassTemplateMember
995 : TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000996 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Douglas Gregor57265e32010-04-12 16:00:01 +0000998 if (SS.isSet()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000999 // If the name of the template was qualified, we must be defining the
Douglas Gregor57265e32010-04-12 16:00:01 +00001000 // template out-of-line.
1001 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
Douglas Gregorea9f54a2011-11-01 21:35:16 +00001002 !(TUK == TUK_Friend && CurContext->isDependentContext())) {
Douglas Gregor57265e32010-04-12 16:00:01 +00001003 Diag(NameLoc, diag::err_member_def_does_not_match)
1004 << Name << SemanticContext << SS.getRange();
Douglas Gregorea9f54a2011-11-01 21:35:16 +00001005 Invalid = true;
1006 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007 }
1008
Mike Stump1eb44332009-09-09 15:08:12 +00001009 CXXRecordDecl *NewClass =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001010 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump1eb44332009-09-09 15:08:12 +00001011 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001012 PrevClassTemplate->getTemplatedDecl() : 0,
1013 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +00001014 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00001015 if (NumOuterTemplateParamLists > 0)
1016 NewClass->setTemplateParameterListsInfo(Context,
1017 NumOuterTemplateParamLists,
1018 OuterTemplateParamLists);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001019
1020 ClassTemplateDecl *NewTemplate
1021 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1022 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001023 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +00001024 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001025
Douglas Gregor2ccd89c2011-12-20 18:11:52 +00001026 if (ModulePrivateLoc.isValid())
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001027 NewTemplate->setModulePrivate();
Douglas Gregor8d267c52011-09-09 02:06:17 +00001028
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001029 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +00001030 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +00001031 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001032 assert(T->isDependentType() && "Class template type is not dependent?");
1033 (void)T;
1034
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035 // If we are providing an explicit specialization of a member that is a
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001036 // class template, make a note of that.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001037 if (PrevClassTemplate &&
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001038 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1039 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040
Anders Carlsson4cbe82c2009-03-26 01:24:28 +00001041 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +00001042 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +00001043 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Douglas Gregorddc29e12009-02-06 22:42:48 +00001045 // Set the lexical context of these templates
1046 NewClass->setLexicalDeclContext(CurContext);
1047 NewTemplate->setLexicalDeclContext(CurContext);
1048
John McCall0f434ec2009-07-31 02:45:11 +00001049 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001050 NewClass->startDefinition();
1051
1052 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001053 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001054
John McCall05b23ea2009-09-14 21:59:20 +00001055 if (TUK != TUK_Friend)
1056 PushOnScopeChains(NewTemplate, S);
1057 else {
Douglas Gregord85bea22009-09-26 06:47:28 +00001058 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +00001059 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +00001060 NewClass->setAccess(PrevClassTemplate->getAccess());
1061 }
John McCall05b23ea2009-09-14 21:59:20 +00001062
Douglas Gregord85bea22009-09-26 06:47:28 +00001063 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1064 PrevClassTemplate != NULL);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001065
John McCall05b23ea2009-09-14 21:59:20 +00001066 // Friend templates are visible in fairly strange ways.
1067 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001068 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +00001069 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1070 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1071 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001072 /* AddToContext = */ false);
John McCall05b23ea2009-09-14 21:59:20 +00001073 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074
Douglas Gregord85bea22009-09-26 06:47:28 +00001075 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1076 NewClass->getLocation(),
1077 NewTemplate,
1078 /*FIXME:*/NewClass->getLocation());
1079 Friend->setAccess(AS_public);
1080 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001081 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001082
Douglas Gregord684b002009-02-10 19:49:53 +00001083 if (Invalid) {
1084 NewTemplate->setInvalidDecl();
1085 NewClass->setInvalidDecl();
1086 }
John McCalld226f652010-08-21 09:40:31 +00001087 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001088}
1089
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001090/// \brief Diagnose the presence of a default template argument on a
1091/// template parameter, which is ill-formed in certain contexts.
1092///
1093/// \returns true if the default template argument should be dropped.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001094static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001095 Sema::TemplateParamListContext TPC,
1096 SourceLocation ParamLoc,
1097 SourceRange DefArgRange) {
1098 switch (TPC) {
1099 case Sema::TPC_ClassTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001100 case Sema::TPC_TypeAliasTemplate:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001101 return false;
1102
1103 case Sema::TPC_FunctionTemplate:
Douglas Gregord89d86f2011-02-04 04:20:44 +00001104 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001105 // C++ [temp.param]p9:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001106 // A default template-argument shall not be specified in a
1107 // function template declaration or a function template
1108 // definition [...]
Douglas Gregord89d86f2011-02-04 04:20:44 +00001109 // If a friend function template declaration specifies a default
1110 // template-argument, that declaration shall be a definition and shall be
1111 // the only declaration of the function template in the translation unit.
1112 // (C++98/03 doesn't have this wording; see DR226).
Richard Smithebaf0e62011-10-18 20:49:44 +00001113 S.Diag(ParamLoc, S.getLangOptions().CPlusPlus0x ?
1114 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1115 : diag::ext_template_parameter_default_in_function_template)
1116 << DefArgRange;
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001117 return false;
1118
1119 case Sema::TPC_ClassTemplateMember:
1120 // C++0x [temp.param]p9:
1121 // A default template-argument shall not be specified in the
1122 // template-parameter-lists of the definition of a member of a
1123 // class template that appears outside of the member's class.
1124 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1125 << DefArgRange;
1126 return true;
1127
1128 case Sema::TPC_FriendFunctionTemplate:
1129 // C++ [temp.param]p9:
1130 // A default template-argument shall not be specified in a
1131 // friend template declaration.
1132 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1133 << DefArgRange;
1134 return true;
1135
1136 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1137 // for friend function templates if there is only a single
1138 // declaration (and it is a definition). Strange!
1139 }
1140
David Blaikie7530c032012-01-17 06:56:22 +00001141 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001142}
1143
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001144/// \brief Check for unexpanded parameter packs within the template parameters
1145/// of a template template parameter, recursively.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001146static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1147 TemplateTemplateParmDecl *TTP) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001148 TemplateParameterList *Params = TTP->getTemplateParameters();
1149 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1150 NamedDecl *P = Params->getParam(I);
1151 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001152 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001153 NTTP->getTypeSourceInfo(),
1154 Sema::UPPC_NonTypeTemplateParameterType))
1155 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001156
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001157 continue;
1158 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001159
1160 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001161 = dyn_cast<TemplateTemplateParmDecl>(P))
1162 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1163 return true;
1164 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001165
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001166 return false;
1167}
1168
Douglas Gregord684b002009-02-10 19:49:53 +00001169/// \brief Checks the validity of a template parameter list, possibly
1170/// considering the template parameter list from a previous
1171/// declaration.
1172///
1173/// If an "old" template parameter list is provided, it must be
1174/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1175/// template parameter list.
1176///
1177/// \param NewParams Template parameter list for a new template
1178/// declaration. This template parameter list will be updated with any
1179/// default arguments that are carried through from the previous
1180/// template parameter list.
1181///
1182/// \param OldParams If provided, template parameter list from a
1183/// previous declaration of the same template. Default template
1184/// arguments will be merged from the old template parameter list to
1185/// the new template parameter list.
1186///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001187/// \param TPC Describes the context in which we are checking the given
1188/// template parameter list.
1189///
Douglas Gregord684b002009-02-10 19:49:53 +00001190/// \returns true if an error occurred, false otherwise.
1191bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001192 TemplateParameterList *OldParams,
1193 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001194 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Douglas Gregord684b002009-02-10 19:49:53 +00001196 // C++ [temp.param]p10:
1197 // The set of default template-arguments available for use with a
1198 // template declaration or definition is obtained by merging the
1199 // default arguments from the definition (if in scope) and all
1200 // declarations in scope in the same way default function
1201 // arguments are (8.3.6).
1202 bool SawDefaultArgument = false;
1203 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001204
Mike Stump1a35fde2009-02-11 23:03:27 +00001205 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001206 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001207 if (OldParams)
1208 OldParam = OldParams->begin();
1209
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001210 bool RemoveDefaultArguments = false;
Douglas Gregord684b002009-02-10 19:49:53 +00001211 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1212 NewParamEnd = NewParams->end();
1213 NewParam != NewParamEnd; ++NewParam) {
1214 // Variables used to diagnose redundant default arguments
1215 bool RedundantDefaultArg = false;
1216 SourceLocation OldDefaultLoc;
1217 SourceLocation NewDefaultLoc;
1218
David Blaikie1368e582011-10-19 05:19:50 +00001219 // Variable used to diagnose missing default arguments
Douglas Gregord684b002009-02-10 19:49:53 +00001220 bool MissingDefaultArg = false;
1221
David Blaikie1368e582011-10-19 05:19:50 +00001222 // Variable used to diagnose non-final parameter packs
1223 bool SawParameterPack = false;
Anders Carlsson49d25572009-06-12 23:20:15 +00001224
Douglas Gregord684b002009-02-10 19:49:53 +00001225 if (TemplateTypeParmDecl *NewTypeParm
1226 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001227 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001228 if (NewTypeParm->hasDefaultArgument() &&
1229 DiagnoseDefaultTemplateArgument(*this, TPC,
1230 NewTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001231 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001232 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001233 NewTypeParm->removeDefaultArgument();
1234
1235 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001236 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001237 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Anders Carlsson49d25572009-06-12 23:20:15 +00001239 if (NewTypeParm->isParameterPack()) {
1240 assert(!NewTypeParm->hasDefaultArgument() &&
1241 "Parameter packs can't have a default argument!");
1242 SawParameterPack = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001243 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001244 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001245 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1246 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1247 SawDefaultArgument = true;
1248 RedundantDefaultArg = true;
1249 PreviousDefaultArgLoc = NewDefaultLoc;
1250 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1251 // Merge the default argument from the old declaration to the
1252 // new declaration.
1253 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001254 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001255 true);
1256 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1257 } else if (NewTypeParm->hasDefaultArgument()) {
1258 SawDefaultArgument = true;
1259 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1260 } else if (SawDefaultArgument)
1261 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001262 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001263 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001264 // Check for unexpanded parameter packs.
1265 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001267 UPPC_NonTypeTemplateParameterType)) {
1268 Invalid = true;
1269 continue;
1270 }
1271
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001272 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001273 if (NewNonTypeParm->hasDefaultArgument() &&
1274 DiagnoseDefaultTemplateArgument(*this, TPC,
1275 NewNonTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001276 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001277 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001278 }
1279
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001280 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001281 NonTypeTemplateParmDecl *OldNonTypeParm
1282 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001283 if (NewNonTypeParm->isParameterPack()) {
1284 assert(!NewNonTypeParm->hasDefaultArgument() &&
1285 "Parameter packs can't have a default argument!");
1286 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001287 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001288 NewNonTypeParm->hasDefaultArgument()) {
1289 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1290 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1291 SawDefaultArgument = true;
1292 RedundantDefaultArg = true;
1293 PreviousDefaultArgLoc = NewDefaultLoc;
1294 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1295 // Merge the default argument from the old declaration to the
1296 // new declaration.
1297 SawDefaultArgument = true;
1298 // FIXME: We need to create a new kind of "default argument"
Douglas Gregor61c4d282011-01-05 15:48:55 +00001299 // expression that points to a previous non-type template
Douglas Gregord684b002009-02-10 19:49:53 +00001300 // parameter.
1301 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001302 OldNonTypeParm->getDefaultArgument(),
1303 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001304 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1305 } else if (NewNonTypeParm->hasDefaultArgument()) {
1306 SawDefaultArgument = true;
1307 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1308 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001309 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001310 } else {
Douglas Gregord684b002009-02-10 19:49:53 +00001311 TemplateTemplateParmDecl *NewTemplateParm
1312 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001313
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001314 // Check for unexpanded parameter packs, recursively.
Douglas Gregor65019ac2011-10-25 03:44:56 +00001315 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001316 Invalid = true;
1317 continue;
1318 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001319
David Blaikie1368e582011-10-19 05:19:50 +00001320 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001321 if (NewTemplateParm->hasDefaultArgument() &&
1322 DiagnoseDefaultTemplateArgument(*this, TPC,
1323 NewTemplateParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001324 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001325 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001326
1327 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001328 TemplateTemplateParmDecl *OldTemplateParm
1329 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001330 if (NewTemplateParm->isParameterPack()) {
1331 assert(!NewTemplateParm->hasDefaultArgument() &&
1332 "Parameter packs can't have a default argument!");
1333 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001334 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001335 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001336 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1337 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001338 SawDefaultArgument = true;
1339 RedundantDefaultArg = true;
1340 PreviousDefaultArgLoc = NewDefaultLoc;
1341 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1342 // Merge the default argument from the old declaration to the
1343 // new declaration.
1344 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001345 // FIXME: We need to create a new kind of "default argument" expression
1346 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001347 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001348 OldTemplateParm->getDefaultArgument(),
1349 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001350 PreviousDefaultArgLoc
1351 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001352 } else if (NewTemplateParm->hasDefaultArgument()) {
1353 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001354 PreviousDefaultArgLoc
1355 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001356 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001357 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001358 }
1359
David Blaikie1368e582011-10-19 05:19:50 +00001360 // C++0x [temp.param]p11:
1361 // If a template parameter of a primary class template or alias template
1362 // is a template parameter pack, it shall be the last template parameter.
1363 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1364 (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1365 Diag((*NewParam)->getLocation(),
1366 diag::err_template_param_pack_must_be_last_template_parameter);
1367 Invalid = true;
1368 }
1369
Douglas Gregord684b002009-02-10 19:49:53 +00001370 if (RedundantDefaultArg) {
1371 // C++ [temp.param]p12:
1372 // A template-parameter shall not be given default arguments
1373 // by two different declarations in the same scope.
1374 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1375 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1376 Invalid = true;
Douglas Gregoree5d21f2011-02-04 03:57:22 +00001377 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregord684b002009-02-10 19:49:53 +00001378 // C++ [temp.param]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001379 // If a template-parameter of a class template has a default
1380 // template-argument, each subsequent template-parameter shall either
Douglas Gregorb49e4152011-01-05 16:21:17 +00001381 // have a default template-argument supplied or be a template parameter
1382 // pack.
Mike Stump1eb44332009-09-09 15:08:12 +00001383 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001384 diag::err_template_param_default_arg_missing);
1385 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1386 Invalid = true;
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001387 RemoveDefaultArguments = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001388 }
1389
1390 // If we have an old template parameter list that we're merging
1391 // in, move on to the next parameter.
1392 if (OldParams)
1393 ++OldParam;
1394 }
1395
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001396 // We were missing some default arguments at the end of the list, so remove
1397 // all of the default arguments.
1398 if (RemoveDefaultArguments) {
1399 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1400 NewParamEnd = NewParams->end();
1401 NewParam != NewParamEnd; ++NewParam) {
1402 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1403 TTP->removeDefaultArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001404 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001405 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1406 NTTP->removeDefaultArgument();
1407 else
1408 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1409 }
1410 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001411
Douglas Gregord684b002009-02-10 19:49:53 +00001412 return Invalid;
1413}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001414
John McCall4e2cbb22010-10-20 05:44:58 +00001415namespace {
1416
1417/// A class which looks for a use of a certain level of template
1418/// parameter.
1419struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1420 typedef RecursiveASTVisitor<DependencyChecker> super;
1421
1422 unsigned Depth;
1423 bool Match;
1424
1425 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1426 NamedDecl *ND = Params->getParam(0);
1427 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1428 Depth = PD->getDepth();
1429 } else if (NonTypeTemplateParmDecl *PD =
1430 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1431 Depth = PD->getDepth();
1432 } else {
1433 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1434 }
1435 }
1436
1437 bool Matches(unsigned ParmDepth) {
1438 if (ParmDepth >= Depth) {
1439 Match = true;
1440 return true;
1441 }
1442 return false;
1443 }
1444
1445 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1446 return !Matches(T->getDepth());
1447 }
1448
1449 bool TraverseTemplateName(TemplateName N) {
1450 if (TemplateTemplateParmDecl *PD =
1451 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1452 if (Matches(PD->getDepth())) return false;
1453 return super::TraverseTemplateName(N);
1454 }
1455
1456 bool VisitDeclRefExpr(DeclRefExpr *E) {
1457 if (NonTypeTemplateParmDecl *PD =
1458 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1459 if (PD->getDepth() == Depth) {
1460 Match = true;
1461 return false;
1462 }
1463 }
1464 return super::VisitDeclRefExpr(E);
1465 }
Douglas Gregor18c83392011-05-13 00:34:01 +00001466
1467 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1468 return TraverseType(T->getInjectedSpecializationType());
1469 }
John McCall4e2cbb22010-10-20 05:44:58 +00001470};
1471}
1472
Douglas Gregorc8406492011-05-10 18:27:06 +00001473/// Determines whether a given type depends on the given parameter
John McCall4e2cbb22010-10-20 05:44:58 +00001474/// list.
1475static bool
Douglas Gregorc8406492011-05-10 18:27:06 +00001476DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCall4e2cbb22010-10-20 05:44:58 +00001477 DependencyChecker Checker(Params);
Douglas Gregorc8406492011-05-10 18:27:06 +00001478 Checker.TraverseType(T);
John McCall4e2cbb22010-10-20 05:44:58 +00001479 return Checker.Match;
1480}
1481
Douglas Gregorc8406492011-05-10 18:27:06 +00001482// Find the source range corresponding to the named type in the given
1483// nested-name-specifier, if any.
1484static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1485 QualType T,
1486 const CXXScopeSpec &SS) {
1487 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1488 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1489 if (const Type *CurType = NNS->getAsType()) {
1490 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1491 return NNSLoc.getTypeLoc().getSourceRange();
1492 } else
1493 break;
1494
1495 NNSLoc = NNSLoc.getPrefix();
1496 }
1497
1498 return SourceRange();
1499}
1500
Mike Stump1eb44332009-09-09 15:08:12 +00001501/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001502/// specifier, returning the template parameter list that applies to the
1503/// name.
1504///
1505/// \param DeclStartLoc the start of the declaration that has a scope
1506/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001507///
Douglas Gregorc8406492011-05-10 18:27:06 +00001508/// \param DeclLoc The location of the declaration itself.
1509///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001510/// \param SS the scope specifier that will be matched to the given template
1511/// parameter lists. This scope specifier precedes a qualified name that is
1512/// being declared.
1513///
1514/// \param ParamLists the template parameter lists, from the outermost to the
1515/// innermost template parameter lists.
1516///
1517/// \param NumParamLists the number of template parameter lists in ParamLists.
1518///
John McCall77e8b112010-04-13 20:37:33 +00001519/// \param IsFriend Whether to apply the slightly different rules for
1520/// matching template parameters to scope specifiers in friend
1521/// declarations.
1522///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001523/// \param IsExplicitSpecialization will be set true if the entity being
1524/// declared is an explicit specialization, false otherwise.
1525///
Mike Stump1eb44332009-09-09 15:08:12 +00001526/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001527/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001528/// parameter list may have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001529/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001530/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001531/// itself a template).
1532TemplateParameterList *
1533Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
Douglas Gregorc8406492011-05-10 18:27:06 +00001534 SourceLocation DeclLoc,
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001535 const CXXScopeSpec &SS,
1536 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001537 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001538 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001539 bool &IsExplicitSpecialization,
1540 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001541 IsExplicitSpecialization = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001542 Invalid = false;
1543
1544 // The sequence of nested types to which we will match up the template
1545 // parameter lists. We first build this list by starting with the type named
1546 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001547 SmallVector<QualType, 4> NestedTypes;
Douglas Gregorc8406492011-05-10 18:27:06 +00001548 QualType T;
Douglas Gregor714c9922011-05-15 17:27:27 +00001549 if (SS.getScopeRep()) {
1550 if (CXXRecordDecl *Record
1551 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1552 T = Context.getTypeDeclType(Record);
1553 else
1554 T = QualType(SS.getScopeRep()->getAsType(), 0);
1555 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001556
1557 // If we found an explicit specialization that prevents us from needing
1558 // 'template<>' headers, this will be set to the location of that
1559 // explicit specialization.
1560 SourceLocation ExplicitSpecLoc;
1561
1562 while (!T.isNull()) {
1563 NestedTypes.push_back(T);
1564
1565 // Retrieve the parent of a record type.
1566 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1567 // If this type is an explicit specialization, we're done.
1568 if (ClassTemplateSpecializationDecl *Spec
1569 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1570 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1571 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1572 ExplicitSpecLoc = Spec->getLocation();
1573 break;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001574 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001575 } else if (Record->getTemplateSpecializationKind()
1576 == TSK_ExplicitSpecialization) {
1577 ExplicitSpecLoc = Record->getLocation();
John McCall77e8b112010-04-13 20:37:33 +00001578 break;
1579 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001580
1581 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1582 T = Context.getTypeDeclType(Parent);
1583 else
1584 T = QualType();
1585 continue;
1586 }
1587
1588 if (const TemplateSpecializationType *TST
1589 = T->getAs<TemplateSpecializationType>()) {
1590 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1591 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1592 T = Context.getTypeDeclType(Parent);
1593 else
1594 T = QualType();
1595 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001596 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001597 }
1598
1599 // Look one step prior in a dependent template specialization type.
1600 if (const DependentTemplateSpecializationType *DependentTST
1601 = T->getAs<DependentTemplateSpecializationType>()) {
1602 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1603 T = QualType(NNS->getAsType(), 0);
1604 else
1605 T = QualType();
1606 continue;
1607 }
1608
1609 // Look one step prior in a dependent name type.
1610 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1611 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1612 T = QualType(NNS->getAsType(), 0);
1613 else
1614 T = QualType();
1615 continue;
1616 }
1617
1618 // Retrieve the parent of an enumeration type.
1619 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1620 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1621 // check here.
1622 EnumDecl *Enum = EnumT->getDecl();
1623
1624 // Get to the parent type.
1625 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1626 T = Context.getTypeDeclType(Parent);
1627 else
1628 T = QualType();
1629 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001630 }
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Douglas Gregorc8406492011-05-10 18:27:06 +00001632 T = QualType();
1633 }
1634 // Reverse the nested types list, since we want to traverse from the outermost
1635 // to the innermost while checking template-parameter-lists.
1636 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregorb88e8882009-07-30 17:40:51 +00001637
Douglas Gregorc8406492011-05-10 18:27:06 +00001638 // C++0x [temp.expl.spec]p17:
1639 // A member or a member template may be nested within many
1640 // enclosing class templates. In an explicit specialization for
1641 // such a member, the member declaration shall be preceded by a
1642 // template<> for each enclosing class template that is
1643 // explicitly specialized.
Douglas Gregor89b9f102011-06-06 15:22:55 +00001644 bool SawNonEmptyTemplateParameterList = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001645 unsigned ParamIdx = 0;
1646 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1647 ++TypeIdx) {
1648 T = NestedTypes[TypeIdx];
1649
1650 // Whether we expect a 'template<>' header.
1651 bool NeedEmptyTemplateHeader = false;
1652
1653 // Whether we expect a template header with parameters.
1654 bool NeedNonemptyTemplateHeader = false;
1655
1656 // For a dependent type, the set of template parameters that we
1657 // expect to see.
1658 TemplateParameterList *ExpectedTemplateParams = 0;
1659
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001660 // C++0x [temp.expl.spec]p15:
1661 // A member or a member template may be nested within many enclosing
1662 // class templates. In an explicit specialization for such a member, the
1663 // member declaration shall be preceded by a template<> for each
1664 // enclosing class template that is explicitly specialized.
Douglas Gregorc8406492011-05-10 18:27:06 +00001665 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1666 if (ClassTemplatePartialSpecializationDecl *Partial
1667 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1668 ExpectedTemplateParams = Partial->getTemplateParameters();
1669 NeedNonemptyTemplateHeader = true;
1670 } else if (Record->isDependentType()) {
1671 if (Record->getDescribedClassTemplate()) {
John McCall31f17ec2010-04-27 00:57:59 +00001672 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregorc8406492011-05-10 18:27:06 +00001673 ->getTemplateParameters();
1674 NeedNonemptyTemplateHeader = true;
1675 }
1676 } else if (ClassTemplateSpecializationDecl *Spec
1677 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1678 // C++0x [temp.expl.spec]p4:
1679 // Members of an explicitly specialized class template are defined
1680 // in the same manner as members of normal classes, and not using
1681 // the template<> syntax.
1682 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1683 NeedEmptyTemplateHeader = true;
1684 else
Douglas Gregor95ea4502011-06-01 22:37:07 +00001685 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001686 } else if (Record->getTemplateSpecializationKind()) {
1687 if (Record->getTemplateSpecializationKind()
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001688 != TSK_ExplicitSpecialization &&
1689 TypeIdx == NumTypes - 1)
1690 IsExplicitSpecialization = true;
1691
1692 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001693 }
1694 } else if (const TemplateSpecializationType *TST
1695 = T->getAs<TemplateSpecializationType>()) {
1696 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1697 ExpectedTemplateParams = Template->getTemplateParameters();
1698 NeedNonemptyTemplateHeader = true;
1699 }
1700 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1701 // FIXME: We actually could/should check the template arguments here
1702 // against the corresponding template parameter list.
1703 NeedNonemptyTemplateHeader = false;
1704 }
1705
Douglas Gregor89b9f102011-06-06 15:22:55 +00001706 // C++ [temp.expl.spec]p16:
1707 // In an explicit specialization declaration for a member of a class
1708 // template or a member template that ap- pears in namespace scope, the
1709 // member template and some of its enclosing class templates may remain
1710 // unspecialized, except that the declaration shall not explicitly
1711 // specialize a class member template if its en- closing class templates
1712 // are not explicitly specialized as well.
1713 if (ParamIdx < NumParamLists) {
1714 if (ParamLists[ParamIdx]->size() == 0) {
1715 if (SawNonEmptyTemplateParameterList) {
1716 Diag(DeclLoc, diag::err_specialize_member_of_template)
1717 << ParamLists[ParamIdx]->getSourceRange();
1718 Invalid = true;
1719 IsExplicitSpecialization = false;
1720 return 0;
1721 }
1722 } else
1723 SawNonEmptyTemplateParameterList = true;
1724 }
1725
Douglas Gregorc8406492011-05-10 18:27:06 +00001726 if (NeedEmptyTemplateHeader) {
1727 // If we're on the last of the types, and we need a 'template<>' header
1728 // here, then it's an explicit specialization.
1729 if (TypeIdx == NumTypes - 1)
1730 IsExplicitSpecialization = true;
1731
1732 if (ParamIdx < NumParamLists) {
1733 if (ParamLists[ParamIdx]->size() > 0) {
1734 // The header has template parameters when it shouldn't. Complain.
1735 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1736 diag::err_template_param_list_matches_nontemplate)
1737 << T
1738 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1739 ParamLists[ParamIdx]->getRAngleLoc())
1740 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1741 Invalid = true;
1742 return 0;
1743 }
1744
1745 // Consume this template header.
1746 ++ParamIdx;
1747 continue;
1748 }
1749
1750 if (!IsFriend) {
1751 // We don't have a template header, but we should.
1752 SourceLocation ExpectedTemplateLoc;
1753 if (NumParamLists > 0)
1754 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1755 else
1756 ExpectedTemplateLoc = DeclStartLoc;
1757
1758 Diag(DeclLoc, diag::err_template_spec_needs_header)
1759 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1760 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1761 }
1762
1763 continue;
1764 }
1765
1766 if (NeedNonemptyTemplateHeader) {
1767 // In friend declarations we can have template-ids which don't
1768 // depend on the corresponding template parameter lists. But
1769 // assume that empty parameter lists are supposed to match this
1770 // template-id.
1771 if (IsFriend && T->isDependentType()) {
1772 if (ParamIdx < NumParamLists &&
1773 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1774 ExpectedTemplateParams = 0;
1775 else
1776 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001777 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001778
Douglas Gregorc8406492011-05-10 18:27:06 +00001779 if (ParamIdx < NumParamLists) {
1780 // Check the template parameter list, if we can.
1781 if (ExpectedTemplateParams &&
1782 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1783 ExpectedTemplateParams,
1784 true, TPL_TemplateMatch))
1785 Invalid = true;
1786
1787 if (!Invalid &&
1788 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1789 TPC_ClassTemplateMember))
1790 Invalid = true;
1791
1792 ++ParamIdx;
1793 continue;
1794 }
1795
1796 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1797 << T
1798 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1799 Invalid = true;
1800 continue;
1801 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001802 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001803
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001804 // If there were at least as many template-ids as there were template
1805 // parameter lists, then there are no template parameter lists remaining for
1806 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001807 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001808 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001810 // If there were too many template parameter lists, complain about that now.
Douglas Gregorc8406492011-05-10 18:27:06 +00001811 if (ParamIdx < NumParamLists - 1) {
1812 bool HasAnyExplicitSpecHeader = false;
1813 bool AllExplicitSpecHeaders = true;
1814 for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1815 if (ParamLists[I]->size() == 0)
1816 HasAnyExplicitSpecHeader = true;
1817 else
1818 AllExplicitSpecHeaders = false;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001819 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001820
1821 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1822 AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1823 : diag::err_template_spec_extra_headers)
1824 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1825 ParamLists[NumParamLists - 2]->getRAngleLoc());
1826
1827 // If there was a specialization somewhere, such that 'template<>' is
1828 // not required, and there were any 'template<>' headers, note where the
1829 // specialization occurred.
1830 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1831 Diag(ExplicitSpecLoc,
1832 diag::note_explicit_template_spec_does_not_need_header)
1833 << NestedTypes.back();
1834
1835 // We have a template parameter list with no corresponding scope, which
1836 // means that the resulting template declaration can't be instantiated
1837 // properly (we'll end up with dependent nodes when we shouldn't).
1838 if (!AllExplicitSpecHeaders)
1839 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregor89b9f102011-06-06 15:22:55 +00001842 // C++ [temp.expl.spec]p16:
1843 // In an explicit specialization declaration for a member of a class
1844 // template or a member template that ap- pears in namespace scope, the
1845 // member template and some of its enclosing class templates may remain
1846 // unspecialized, except that the declaration shall not explicitly
1847 // specialize a class member template if its en- closing class templates
1848 // are not explicitly specialized as well.
1849 if (ParamLists[NumParamLists - 1]->size() == 0 &&
1850 SawNonEmptyTemplateParameterList) {
1851 Diag(DeclLoc, diag::err_specialize_member_of_template)
1852 << ParamLists[ParamIdx]->getSourceRange();
1853 Invalid = true;
1854 IsExplicitSpecialization = false;
1855 return 0;
1856 }
1857
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001858 // Return the last template parameter list, which corresponds to the
1859 // entity being declared.
1860 return ParamLists[NumParamLists - 1];
1861}
1862
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001863void Sema::NoteAllFoundTemplates(TemplateName Name) {
1864 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1865 Diag(Template->getLocation(), diag::note_template_declared_here)
1866 << (isa<FunctionTemplateDecl>(Template)? 0
1867 : isa<ClassTemplateDecl>(Template)? 1
Richard Smith3e4c6c42011-05-05 21:57:07 +00001868 : isa<TypeAliasTemplateDecl>(Template)? 2
1869 : 3)
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001870 << Template->getDeclName();
1871 return;
1872 }
1873
1874 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1875 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1876 IEnd = OST->end();
1877 I != IEnd; ++I)
1878 Diag((*I)->getLocation(), diag::note_template_declared_here)
1879 << 0 << (*I)->getDeclName();
1880
1881 return;
1882 }
1883}
1884
1885
Douglas Gregor7532dc62009-03-30 22:58:21 +00001886QualType Sema::CheckTemplateIdType(TemplateName Name,
1887 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00001888 TemplateArgumentListInfo &TemplateArgs) {
John McCall14606042011-06-30 08:33:18 +00001889 DependentTemplateName *DTN
1890 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001891 if (DTN && DTN->isIdentifier())
1892 // When building a template-id where the template-name is dependent,
1893 // assume the template is a type template. Either our assumption is
1894 // correct, or the code is ill-formed and will be diagnosed when the
1895 // dependent name is substituted.
1896 return Context.getDependentTemplateSpecializationType(ETK_None,
1897 DTN->getQualifier(),
1898 DTN->getIdentifier(),
1899 TemplateArgs);
1900
Douglas Gregor7532dc62009-03-30 22:58:21 +00001901 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001902 if (!Template || isa<FunctionTemplateDecl>(Template)) {
1903 // We might have a substituted template template parameter pack. If so,
1904 // build a template specialization type for it.
1905 if (Name.getAsSubstTemplateTemplateParmPack())
1906 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3e4c6c42011-05-05 21:57:07 +00001907
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001908 Diag(TemplateLoc, diag::err_template_id_not_a_type)
1909 << Name;
1910 NoteAllFoundTemplates(Name);
1911 return QualType();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001912 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001913
Douglas Gregor40808ce2009-03-09 23:48:35 +00001914 // Check that the template argument list is well-formed for this
1915 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001916 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001917 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001918 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001919 return QualType();
1920
Douglas Gregor910f8002010-11-07 23:05:16 +00001921 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001922 "Converted template argument list is too short!");
1923
1924 QualType CanonType;
1925
Douglas Gregor561f8122011-07-01 01:22:09 +00001926 bool InstantiationDependent = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00001927 if (TypeAliasTemplateDecl *AliasTemplate
1928 = dyn_cast<TypeAliasTemplateDecl>(Template)) {
1929 // Find the canonical type for this type alias template specialization.
1930 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
1931 if (Pattern->isInvalidDecl())
1932 return QualType();
1933
1934 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1935 Converted.data(), Converted.size());
1936
1937 // Only substitute for the innermost template argument list.
1938 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith18041742011-05-14 15:04:18 +00001939 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smithaff37b42011-05-12 00:06:17 +00001940 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
1941 for (unsigned I = 0; I < Depth; ++I)
1942 TemplateArgLists.addOuterTemplateArguments(0, 0);
Richard Smith3e4c6c42011-05-05 21:57:07 +00001943
1944 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
1945 CanonType = SubstType(Pattern->getUnderlyingType(),
1946 TemplateArgLists, AliasTemplate->getLocation(),
1947 AliasTemplate->getDeclName());
1948 if (CanonType.isNull())
1949 return QualType();
1950 } else if (Name.isDependent() ||
1951 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor561f8122011-07-01 01:22:09 +00001952 TemplateArgs, InstantiationDependent)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001953 // This class template specialization is a dependent
1954 // type. Therefore, its canonical type is another class template
1955 // specialization type that contains all of the converted
1956 // arguments in canonical form. This ensures that, e.g., A<T> and
1957 // A<T, T> have identical types when A is declared as:
1958 //
1959 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001960 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001961 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001962 Converted.data(),
1963 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Douglas Gregor1275ae02009-07-28 23:00:59 +00001965 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001966 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001967 // In the future, we need to teach getTemplateSpecializationType to only
1968 // build the canonical type and return that to us.
1969 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001970
1971 // This might work out to be a current instantiation, in which
1972 // case the canonical type needs to be the InjectedClassNameType.
1973 //
1974 // TODO: in theory this could be a simple hashtable lookup; most
1975 // changes to CurContext don't change the set of current
1976 // instantiations.
1977 if (isa<ClassTemplateDecl>(Template)) {
1978 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1979 // If we get out to a namespace, we're done.
1980 if (Ctx->isFileContext()) break;
1981
1982 // If this isn't a record, keep looking.
1983 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1984 if (!Record) continue;
1985
1986 // Look for one of the two cases with InjectedClassNameTypes
1987 // and check whether it's the same template.
1988 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1989 !Record->getDescribedClassTemplate())
1990 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001991
John McCall31f17ec2010-04-27 00:57:59 +00001992 // Fetch the injected class name type and check whether its
1993 // injected type is equal to the type we just built.
1994 QualType ICNT = Context.getTypeDeclType(Record);
1995 QualType Injected = cast<InjectedClassNameType>(ICNT)
1996 ->getInjectedSpecializationType();
1997
1998 if (CanonType != Injected->getCanonicalTypeInternal())
1999 continue;
2000
2001 // If so, the canonical type of this TST is the injected
2002 // class name type of the record we just found.
2003 assert(ICNT.isCanonical());
2004 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00002005 break;
2006 }
2007 }
Mike Stump1eb44332009-09-09 15:08:12 +00002008 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002009 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002010 // Find the class template specialization declaration that
2011 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002012 void *InsertPos = 0;
2013 ClassTemplateSpecializationDecl *Decl
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002015 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002016 if (!Decl) {
2017 // This is the first time we have referenced this class template
2018 // specialization. Create the canonical declaration and add it to
2019 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002020 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002021 ClassTemplate->getTemplatedDecl()->getTagKind(),
2022 ClassTemplate->getDeclContext(),
Abramo Bagnara09d82122011-10-03 20:34:03 +00002023 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002024 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002025 ClassTemplate,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002026 Converted.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002027 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002028 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002029 Decl->setLexicalDeclContext(CurContext);
2030 }
2031
2032 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00002033 assert(isa<RecordType>(CanonType) &&
2034 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00002035 }
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Douglas Gregor40808ce2009-03-09 23:48:35 +00002037 // Build the fully-sugared type for this class template
2038 // specialization, which refers back to the class template
2039 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00002040 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002041}
2042
John McCallf312b1e2010-08-26 23:41:50 +00002043TypeResult
Douglas Gregor059101f2011-03-02 00:47:37 +00002044Sema::ActOnTemplateIdType(CXXScopeSpec &SS,
2045 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002046 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002047 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002048 SourceLocation RAngleLoc,
2049 bool IsCtorOrDtorName) {
Douglas Gregor059101f2011-03-02 00:47:37 +00002050 if (SS.isInvalid())
2051 return true;
2052
Douglas Gregor7532dc62009-03-30 22:58:21 +00002053 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00002054
Douglas Gregor40808ce2009-03-09 23:48:35 +00002055 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00002056 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00002057 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002058
Douglas Gregora88f09f2011-02-28 17:23:35 +00002059 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002060 QualType T
2061 = Context.getDependentTemplateSpecializationType(ETK_None,
2062 DTN->getQualifier(),
2063 DTN->getIdentifier(),
2064 TemplateArgs);
2065 // Build type-source information.
Douglas Gregora88f09f2011-02-28 17:23:35 +00002066 TypeLocBuilder TLB;
2067 DependentTemplateSpecializationTypeLoc SpecTL
2068 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Douglas Gregor059101f2011-03-02 00:47:37 +00002069 SpecTL.setKeywordLoc(SourceLocation());
Douglas Gregora88f09f2011-02-28 17:23:35 +00002070 SpecTL.setNameLoc(TemplateLoc);
2071 SpecTL.setLAngleLoc(LAngleLoc);
2072 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor94fdffa2011-03-01 20:11:18 +00002073 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Douglas Gregora88f09f2011-02-28 17:23:35 +00002074 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2075 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2076 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2077 }
2078
John McCalld5532b62009-11-23 01:53:49 +00002079 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002080 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00002081
2082 if (Result.isNull())
2083 return true;
2084
Douglas Gregor059101f2011-03-02 00:47:37 +00002085 // Build type-source information.
2086 TypeLocBuilder TLB;
2087 TemplateSpecializationTypeLoc SpecTL
2088 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2089 SpecTL.setTemplateNameLoc(TemplateLoc);
2090 SpecTL.setLAngleLoc(LAngleLoc);
2091 SpecTL.setRAngleLoc(RAngleLoc);
2092 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2093 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall833ca992009-10-29 08:12:44 +00002094
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002095 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2096 // constructor or destructor name (in such a case, the scope specifier
2097 // will be attached to the enclosing Decl or Expr node).
2098 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor059101f2011-03-02 00:47:37 +00002099 // Create an elaborated-type-specifier containing the nested-name-specifier.
2100 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2101 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2102 ElabTL.setKeywordLoc(SourceLocation());
2103 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2104 }
2105
2106 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall6b2becf2009-09-08 17:47:29 +00002107}
John McCallf1bbbb42009-09-04 01:14:41 +00002108
Douglas Gregor059101f2011-03-02 00:47:37 +00002109TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallf312b1e2010-08-26 23:41:50 +00002110 TypeSpecifierType TagSpec,
Douglas Gregor059101f2011-03-02 00:47:37 +00002111 SourceLocation TagLoc,
2112 CXXScopeSpec &SS,
2113 TemplateTy TemplateD,
2114 SourceLocation TemplateLoc,
2115 SourceLocation LAngleLoc,
2116 ASTTemplateArgsPtr TemplateArgsIn,
2117 SourceLocation RAngleLoc) {
2118 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2119
2120 // Translate the parser's template argument list in our AST format.
2121 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2122 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2123
2124 // Determine the tag kind
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002125 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregor059101f2011-03-02 00:47:37 +00002126 ElaboratedTypeKeyword Keyword
2127 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Douglas Gregor059101f2011-03-02 00:47:37 +00002129 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2130 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2131 DTN->getQualifier(),
2132 DTN->getIdentifier(),
2133 TemplateArgs);
2134
2135 // Build type-source information.
2136 TypeLocBuilder TLB;
2137 DependentTemplateSpecializationTypeLoc SpecTL
2138 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2139 SpecTL.setKeywordLoc(TagLoc);
2140 SpecTL.setNameLoc(TemplateLoc);
2141 SpecTL.setLAngleLoc(LAngleLoc);
2142 SpecTL.setRAngleLoc(RAngleLoc);
2143 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2144 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2145 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2146 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2147 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00002148
2149 if (TypeAliasTemplateDecl *TAT =
2150 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2151 // C++0x [dcl.type.elab]p2:
2152 // If the identifier resolves to a typedef-name or the simple-template-id
2153 // resolves to an alias template specialization, the
2154 // elaborated-type-specifier is ill-formed.
2155 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2156 Diag(TAT->getLocation(), diag::note_declared_at);
2157 }
Douglas Gregor059101f2011-03-02 00:47:37 +00002158
2159 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2160 if (Result.isNull())
Matt Beaumont-Gay3a51d412011-08-25 23:22:24 +00002161 return TypeResult(true);
Douglas Gregor059101f2011-03-02 00:47:37 +00002162
2163 // Check the tag kind
2164 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00002165 RecordDecl *D = RT->getDecl();
Douglas Gregor059101f2011-03-02 00:47:37 +00002166
John McCall6b2becf2009-09-08 17:47:29 +00002167 IdentifierInfo *Id = D->getIdentifier();
2168 assert(Id && "templated class must have an identifier");
Douglas Gregor059101f2011-03-02 00:47:37 +00002169
Richard Trieubbf34c02011-06-10 03:11:26 +00002170 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2171 TagLoc, *Id)) {
John McCall6b2becf2009-09-08 17:47:29 +00002172 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregor059101f2011-03-02 00:47:37 +00002173 << Result
Douglas Gregor849b2432010-03-31 17:46:05 +00002174 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00002175 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00002176 }
2177 }
Douglas Gregor059101f2011-03-02 00:47:37 +00002178
2179 // Provide source-location information for the template specialization.
2180 TypeLocBuilder TLB;
2181 TemplateSpecializationTypeLoc SpecTL
2182 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2183 SpecTL.setTemplateNameLoc(TemplateLoc);
2184 SpecTL.setLAngleLoc(LAngleLoc);
2185 SpecTL.setRAngleLoc(RAngleLoc);
2186 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2187 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCallf1bbbb42009-09-04 01:14:41 +00002188
Douglas Gregor059101f2011-03-02 00:47:37 +00002189 // Construct an elaborated type containing the nested-name-specifier (if any)
2190 // and keyword.
2191 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2192 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2193 ElabTL.setKeywordLoc(TagLoc);
2194 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2195 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor55f6b142009-02-09 18:46:07 +00002196}
2197
John McCall60d7b3a2010-08-24 06:29:42 +00002198ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Douglas Gregor4c9be892011-02-28 20:01:57 +00002199 LookupResult &R,
2200 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00002201 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002202 // FIXME: Can we do any checking at this point? I guess we could check the
2203 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00002204 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002205 // though.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002206 // foo<int> could identify a single function unambiguously
2207 // This approach does NOT work, since f<int>(1);
2208 // gets resolved prior to resorting to overload resolution
2209 // i.e., template<class T> void f(double);
2210 // vs template<class T, class U> void f(U);
John McCallf7a1a742009-11-24 19:00:30 +00002211
2212 // These should be filtered out by our callers.
2213 assert(!R.empty() && "empty lookup results when building templateid");
2214 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2215
John McCallc373d482010-01-27 01:50:18 +00002216 // We don't want lookup warnings at this point.
2217 R.suppressDiagnostics();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218
John McCallf7a1a742009-11-24 19:00:30 +00002219 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002220 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002221 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00002222 R.getLookupNameInfo(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002223 RequiresADL, TemplateArgs,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002224 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00002225
2226 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002227}
2228
John McCallf7a1a742009-11-24 19:00:30 +00002229// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00002230ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002231Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002232 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00002233 const TemplateArgumentListInfo &TemplateArgs) {
2234 DeclContext *DC;
2235 if (!(DC = computeDeclContext(SS, false)) ||
2236 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00002237 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00002238 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002240 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00002241 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002242 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2243 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00002244
John McCallf7a1a742009-11-24 19:00:30 +00002245 if (R.isAmbiguous())
2246 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002247
John McCallf7a1a742009-11-24 19:00:30 +00002248 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002249 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2250 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002251 return ExprError();
2252 }
2253
2254 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002255 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2256 << (NestedNameSpecifier*) SS.getScopeRep()
2257 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002258 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2259 return ExprError();
2260 }
2261
2262 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002263}
2264
Douglas Gregorc45c2322009-03-31 00:43:58 +00002265/// \brief Form a dependent template name.
2266///
2267/// This action forms a dependent template name given the template
2268/// name and its (presumably dependent) scope specifier. For
2269/// example, given "MetaFun::template apply", the scope specifier \p
2270/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2271/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002272TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002273 SourceLocation TemplateKWLoc,
2274 CXXScopeSpec &SS,
2275 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00002276 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002277 bool EnteringContext,
2278 TemplateTy &Result) {
Richard Smithebaf0e62011-10-18 20:49:44 +00002279 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2280 Diag(TemplateKWLoc,
2281 getLangOptions().CPlusPlus0x ?
2282 diag::warn_cxx98_compat_template_outside_of_template :
2283 diag::ext_template_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002284 << FixItHint::CreateRemoval(TemplateKWLoc);
2285
Douglas Gregor0707bc52010-01-19 16:01:07 +00002286 DeclContext *LookupCtx = 0;
2287 if (SS.isSet())
2288 LookupCtx = computeDeclContext(SS, EnteringContext);
2289 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00002290 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00002291 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00002292 // C++0x [temp.names]p5:
2293 // If a name prefixed by the keyword template is not the name of
2294 // a template, the program is ill-formed. [Note: the keyword
2295 // template may not be applied to non-template members of class
2296 // templates. -end note ] [ Note: as is the case with the
2297 // typename prefix, the template prefix is allowed in cases
2298 // where it is not strictly necessary; i.e., when the
2299 // nested-name-specifier or the expression on the left of the ->
2300 // or . is not dependent on a template-parameter, or the use
2301 // does not appear in the scope of a template. -end note]
2302 //
2303 // Note: C++03 was more strict here, because it banned the use of
2304 // the "template" keyword prior to a template-name that was not a
2305 // dependent name. C++ DR468 relaxed this requirement (the
2306 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00002307 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002308 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00002309 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
2310 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002311 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00002312 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2313 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregord078bd22011-03-11 23:27:41 +00002314 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2315 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00002316 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002317 } else if (TNK == TNK_Non_template) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002318 Diag(Name.getSourceRange().getBegin(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002319 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002320 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002321 << Name.getSourceRange()
2322 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002323 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002324 } else {
2325 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00002326 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002327 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00002328 }
2329
Mike Stump1eb44332009-09-09 15:08:12 +00002330 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002331 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002332
Douglas Gregor014e88d2009-11-03 23:16:33 +00002333 switch (Name.getKind()) {
2334 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002335 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002336 Name.Identifier));
2337 return TNK_Dependent_template_name;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002338
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002339 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00002340 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002341 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00002342 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00002343
2344 case UnqualifiedId::IK_LiteralOperatorId:
David Blaikieb219cfc2011-09-23 05:06:16 +00002345 llvm_unreachable(
2346 "We don't support these; Parse shouldn't have allowed propagation");
Sean Hunte6252d12009-11-28 08:58:14 +00002347
Douglas Gregor014e88d2009-11-03 23:16:33 +00002348 default:
2349 break;
2350 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002351
2352 Diag(Name.getSourceRange().getBegin(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002353 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002354 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002355 << Name.getSourceRange()
2356 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002357 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002358}
2359
Mike Stump1eb44332009-09-09 15:08:12 +00002360bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00002361 const TemplateArgumentLoc &AL,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002362 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00002363 const TemplateArgument &Arg = AL.getArgument();
2364
Anders Carlsson436b1562009-06-13 00:33:33 +00002365 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002366 switch(Arg.getKind()) {
2367 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00002368 // C++ [temp.arg.type]p1:
2369 // A template-argument for a template-parameter which is a
2370 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002371 break;
2372 case TemplateArgument::Template: {
2373 // We have a template type parameter but the template argument
2374 // is a template without any arguments.
2375 SourceRange SR = AL.getSourceRange();
2376 TemplateName Name = Arg.getAsTemplate();
2377 Diag(SR.getBegin(), diag::err_template_missing_args)
2378 << Name << SR;
2379 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2380 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00002381
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002382 return true;
2383 }
2384 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00002385 // We have a template type parameter but the template argument
2386 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00002387 SourceRange SR = AL.getSourceRange();
2388 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00002389 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Anders Carlsson436b1562009-06-13 00:33:33 +00002391 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002392 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002393 }
Anders Carlsson436b1562009-06-13 00:33:33 +00002394
John McCalla93c9342009-12-07 02:54:59 +00002395 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00002396 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Anders Carlsson436b1562009-06-13 00:33:33 +00002398 // Add the converted template type argument.
Douglas Gregore559ca12011-06-17 22:11:49 +00002399 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
2400
2401 // Objective-C ARC:
2402 // If an explicitly-specified template argument type is a lifetime type
2403 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
2404 if (getLangOptions().ObjCAutoRefCount &&
2405 ArgType->isObjCLifetimeType() &&
2406 !ArgType.getObjCLifetime()) {
2407 Qualifiers Qs;
2408 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
2409 ArgType = Context.getQualifiedType(ArgType, Qs);
2410 }
2411
2412 Converted.push_back(TemplateArgument(ArgType));
Anders Carlsson436b1562009-06-13 00:33:33 +00002413 return false;
2414}
2415
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002416/// \brief Substitute template arguments into the default template argument for
2417/// the given template type parameter.
2418///
2419/// \param SemaRef the semantic analysis object for which we are performing
2420/// the substitution.
2421///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002422/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002423/// for.
2424///
2425/// \param TemplateLoc the location of the template name that started the
2426/// template-id we are checking.
2427///
2428/// \param RAngleLoc the location of the right angle bracket ('>') that
2429/// terminates the template-id.
2430///
2431/// \param Param the template template parameter whose default we are
2432/// substituting into.
2433///
2434/// \param Converted the list of template arguments provided for template
2435/// parameters that precede \p Param in the template parameter list.
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002436/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00002437static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002438SubstDefaultTemplateArgument(Sema &SemaRef,
2439 TemplateDecl *Template,
2440 SourceLocation TemplateLoc,
2441 SourceLocation RAngleLoc,
2442 TemplateTypeParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002443 SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00002444 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002445
2446 // If the argument type is dependent, instantiate it now based
2447 // on the previously-computed template arguments.
2448 if (ArgType->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002449 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002450 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002451
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002452 MultiLevelTemplateArgumentList AllTemplateArgs
2453 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2454
2455 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002456 Template, Converted.data(),
2457 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002458 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002459
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002460 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2461 Param->getDefaultArgumentLoc(),
2462 Param->getDeclName());
2463 }
2464
2465 return ArgType;
2466}
2467
2468/// \brief Substitute template arguments into the default template argument for
2469/// the given non-type template parameter.
2470///
2471/// \param SemaRef the semantic analysis object for which we are performing
2472/// the substitution.
2473///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002475/// for.
2476///
2477/// \param TemplateLoc the location of the template name that started the
2478/// template-id we are checking.
2479///
2480/// \param RAngleLoc the location of the right angle bracket ('>') that
2481/// terminates the template-id.
2482///
Douglas Gregor788cd062009-11-11 01:00:40 +00002483/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002484/// substituting into.
2485///
2486/// \param Converted the list of template arguments provided for template
2487/// parameters that precede \p Param in the template parameter list.
2488///
2489/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002490static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002491SubstDefaultTemplateArgument(Sema &SemaRef,
2492 TemplateDecl *Template,
2493 SourceLocation TemplateLoc,
2494 SourceLocation RAngleLoc,
2495 NonTypeTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002496 SmallVectorImpl<TemplateArgument> &Converted) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002497 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002498 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002499
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002500 MultiLevelTemplateArgumentList AllTemplateArgs
2501 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002502
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002503 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002504 Template, Converted.data(),
2505 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002506 SourceRange(TemplateLoc, RAngleLoc));
2507
2508 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2509}
2510
Douglas Gregor788cd062009-11-11 01:00:40 +00002511/// \brief Substitute template arguments into the default template argument for
2512/// the given template template parameter.
2513///
2514/// \param SemaRef the semantic analysis object for which we are performing
2515/// the substitution.
2516///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002517/// \param Template the template that we are synthesizing template arguments
Douglas Gregor788cd062009-11-11 01:00:40 +00002518/// for.
2519///
2520/// \param TemplateLoc the location of the template name that started the
2521/// template-id we are checking.
2522///
2523/// \param RAngleLoc the location of the right angle bracket ('>') that
2524/// terminates the template-id.
2525///
2526/// \param Param the template template parameter whose default we are
2527/// substituting into.
2528///
2529/// \param Converted the list of template arguments provided for template
2530/// parameters that precede \p Param in the template parameter list.
2531///
Douglas Gregor1d752d72011-03-02 18:46:51 +00002532/// \param QualifierLoc Will be set to the nested-name-specifier (with
2533/// source-location information) that precedes the template name.
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002534///
Douglas Gregor788cd062009-11-11 01:00:40 +00002535/// \returns the substituted template argument, or NULL if an error occurred.
2536static TemplateName
2537SubstDefaultTemplateArgument(Sema &SemaRef,
2538 TemplateDecl *Template,
2539 SourceLocation TemplateLoc,
2540 SourceLocation RAngleLoc,
2541 TemplateTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002542 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002543 NestedNameSpecifierLoc &QualifierLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002544 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002545 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002546
Douglas Gregor788cd062009-11-11 01:00:40 +00002547 MultiLevelTemplateArgumentList AllTemplateArgs
2548 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002549
Douglas Gregor788cd062009-11-11 01:00:40 +00002550 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002551 Template, Converted.data(),
2552 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002553 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002554
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002555 // Substitute into the nested-name-specifier first,
Douglas Gregor1d752d72011-03-02 18:46:51 +00002556 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002557 if (QualifierLoc) {
2558 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2559 AllTemplateArgs);
2560 if (!QualifierLoc)
2561 return TemplateName();
2562 }
2563
Douglas Gregor1d752d72011-03-02 18:46:51 +00002564 return SemaRef.SubstTemplateName(QualifierLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +00002565 Param->getDefaultArgument().getArgument().getAsTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002566 Param->getDefaultArgument().getTemplateNameLoc(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002567 AllTemplateArgs);
2568}
2569
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002570/// \brief If the given template parameter has a default template
2571/// argument, substitute into that default template argument and
2572/// return the corresponding template argument.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002573TemplateArgumentLoc
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002574Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2575 SourceLocation TemplateLoc,
2576 SourceLocation RAngleLoc,
2577 Decl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002578 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002579 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002580 if (!TypeParm->hasDefaultArgument())
2581 return TemplateArgumentLoc();
2582
John McCalla93c9342009-12-07 02:54:59 +00002583 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002584 TemplateLoc,
2585 RAngleLoc,
2586 TypeParm,
2587 Converted);
2588 if (DI)
2589 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2590
2591 return TemplateArgumentLoc();
2592 }
2593
2594 if (NonTypeTemplateParmDecl *NonTypeParm
2595 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2596 if (!NonTypeParm->hasDefaultArgument())
2597 return TemplateArgumentLoc();
2598
John McCall60d7b3a2010-08-24 06:29:42 +00002599 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002600 TemplateLoc,
2601 RAngleLoc,
2602 NonTypeParm,
2603 Converted);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002604 if (Arg.isInvalid())
2605 return TemplateArgumentLoc();
2606
2607 Expr *ArgE = Arg.takeAs<Expr>();
2608 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2609 }
2610
2611 TemplateTemplateParmDecl *TempTempParm
2612 = cast<TemplateTemplateParmDecl>(Param);
2613 if (!TempTempParm->hasDefaultArgument())
2614 return TemplateArgumentLoc();
2615
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002616
Douglas Gregor1d752d72011-03-02 18:46:51 +00002617 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002618 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002619 TemplateLoc,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002620 RAngleLoc,
2621 TempTempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002622 Converted,
2623 QualifierLoc);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002624 if (TName.isNull())
2625 return TemplateArgumentLoc();
2626
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002627 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002628 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002629 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2630}
2631
Douglas Gregore7526412009-11-11 19:31:23 +00002632/// \brief Check that the given template argument corresponds to the given
2633/// template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002634///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002635/// \param Param The template parameter against which the argument will be
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002636/// checked.
2637///
2638/// \param Arg The template argument.
2639///
2640/// \param Template The template in which the template argument resides.
2641///
2642/// \param TemplateLoc The location of the template name for the template
2643/// whose argument list we're matching.
2644///
2645/// \param RAngleLoc The location of the right angle bracket ('>') that closes
2646/// the template argument list.
2647///
2648/// \param ArgumentPackIndex The index into the argument pack where this
2649/// argument will be placed. Only valid if the parameter is a parameter pack.
2650///
2651/// \param Converted The checked, converted argument will be added to the
2652/// end of this small vector.
2653///
2654/// \param CTAK Describes how we arrived at this particular template argument:
2655/// explicitly written, deduced, etc.
2656///
2657/// \returns true on error, false otherwise.
Douglas Gregore7526412009-11-11 19:31:23 +00002658bool Sema::CheckTemplateArgument(NamedDecl *Param,
2659 const TemplateArgumentLoc &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002660 NamedDecl *Template,
Douglas Gregore7526412009-11-11 19:31:23 +00002661 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002662 SourceLocation RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002663 unsigned ArgumentPackIndex,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002664 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002665 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002666 // Check template type parameters.
2667 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002668 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002669
Douglas Gregord9e15302009-11-11 19:41:09 +00002670 // Check non-type template parameters.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002671 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002672 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002673 // with the template arguments we've seen thus far. But if the
2674 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002675 QualType NTTPType = NTTP->getType();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002676 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2677 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002678
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002679 if (NTTPType->isDependentType() &&
2680 !isa<TemplateTemplateParmDecl>(Template) &&
2681 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002682 // Do substitution on the type of the non-type template parameter.
2683 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002684 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002685 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002686
2687 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002688 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002689 NTTPType = SubstType(NTTPType,
2690 MultiLevelTemplateArgumentList(TemplateArgs),
2691 NTTP->getLocation(),
2692 NTTP->getDeclName());
2693 // If that worked, check the non-type template parameter type
2694 // for validity.
2695 if (!NTTPType.isNull())
2696 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2697 NTTP->getLocation());
2698 if (NTTPType.isNull())
2699 return true;
2700 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002701
Douglas Gregore7526412009-11-11 19:31:23 +00002702 switch (Arg.getArgument().getKind()) {
2703 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002704 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002705
Douglas Gregore7526412009-11-11 19:31:23 +00002706 case TemplateArgument::Expression: {
Douglas Gregore7526412009-11-11 19:31:23 +00002707 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002708 ExprResult Res =
2709 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2710 Result, CTAK);
2711 if (Res.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002712 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713
Douglas Gregor910f8002010-11-07 23:05:16 +00002714 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002715 break;
2716 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002717
Douglas Gregore7526412009-11-11 19:31:23 +00002718 case TemplateArgument::Declaration:
2719 case TemplateArgument::Integral:
2720 // We've already checked this template argument, so just copy
2721 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002722 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002723 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002724
Douglas Gregore7526412009-11-11 19:31:23 +00002725 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002726 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002727 // We were given a template template argument. It may not be ill-formed;
2728 // see below.
2729 if (DependentTemplateName *DTN
Douglas Gregora7fc9012011-01-05 18:58:31 +00002730 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2731 .getAsDependentTemplateName()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002732 // We have a template argument such as \c T::template X, which we
2733 // parsed as a template template argument. However, since we now
2734 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002735 // template name into an expression.
2736
2737 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2738 Arg.getTemplateNameLoc());
2739
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002740 CXXScopeSpec SS;
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002741 SS.Adopt(Arg.getTemplateQualifierLoc());
John Wiegley429bb272011-04-08 18:41:53 +00002742 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002743 SS.getWithLocInContext(Context),
John Wiegley429bb272011-04-08 18:41:53 +00002744 NameInfo));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002745
Douglas Gregora7fc9012011-01-05 18:58:31 +00002746 // If we parsed the template argument as a pack expansion, create a
2747 // pack expansion expression.
2748 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
John Wiegley429bb272011-04-08 18:41:53 +00002749 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2750 if (E.isInvalid())
Douglas Gregora7fc9012011-01-05 18:58:31 +00002751 return true;
Douglas Gregora7fc9012011-01-05 18:58:31 +00002752 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002753
Douglas Gregore7526412009-11-11 19:31:23 +00002754 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002755 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2756 if (E.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002757 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002758
Douglas Gregor910f8002010-11-07 23:05:16 +00002759 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002760 break;
2761 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002762
Douglas Gregore7526412009-11-11 19:31:23 +00002763 // We have a template argument that actually does refer to a class
Richard Smith3e4c6c42011-05-05 21:57:07 +00002764 // template, alias template, or template template parameter, and
Douglas Gregore7526412009-11-11 19:31:23 +00002765 // therefore cannot be a non-type template argument.
2766 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2767 << Arg.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002768
Douglas Gregore7526412009-11-11 19:31:23 +00002769 Diag(Param->getLocation(), diag::note_template_param_here);
2770 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002771
Douglas Gregore7526412009-11-11 19:31:23 +00002772 case TemplateArgument::Type: {
2773 // We have a non-type template parameter but the template
2774 // argument is a type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002775
Douglas Gregore7526412009-11-11 19:31:23 +00002776 // C++ [temp.arg]p2:
2777 // In a template-argument, an ambiguity between a type-id and
2778 // an expression is resolved to a type-id, regardless of the
2779 // form of the corresponding template-parameter.
2780 //
2781 // We warn specifically about this case, since it can be rather
2782 // confusing for users.
2783 QualType T = Arg.getArgument().getAsType();
2784 SourceRange SR = Arg.getSourceRange();
2785 if (T->isFunctionType())
2786 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2787 else
2788 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2789 Diag(Param->getLocation(), diag::note_template_param_here);
2790 return true;
2791 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002792
Douglas Gregore7526412009-11-11 19:31:23 +00002793 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002794 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002795 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002796
Douglas Gregore7526412009-11-11 19:31:23 +00002797 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002798 }
2799
2800
Douglas Gregore7526412009-11-11 19:31:23 +00002801 // Check template template parameters.
2802 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002803
Douglas Gregore7526412009-11-11 19:31:23 +00002804 // Substitute into the template parameter list of the template
2805 // template parameter, since previously-supplied template arguments
2806 // may appear within the template template parameter.
2807 {
2808 // Set up a template instantiation context.
2809 LocalInstantiationScope Scope(*this);
2810 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002811 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002812 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002813
2814 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002815 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002816 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002817 SubstDecl(TempParm, CurContext,
Douglas Gregore7526412009-11-11 19:31:23 +00002818 MultiLevelTemplateArgumentList(TemplateArgs)));
2819 if (!TempParm)
2820 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002822
Douglas Gregore7526412009-11-11 19:31:23 +00002823 switch (Arg.getArgument().getKind()) {
2824 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002825 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002826
Douglas Gregore7526412009-11-11 19:31:23 +00002827 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002828 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002829 if (CheckTemplateArgument(TempParm, Arg))
2830 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002831
Douglas Gregor910f8002010-11-07 23:05:16 +00002832 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002833 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002834
Douglas Gregore7526412009-11-11 19:31:23 +00002835 case TemplateArgument::Expression:
2836 case TemplateArgument::Type:
2837 // We have a template template parameter but the template
2838 // argument does not refer to a template.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002839 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
2840 << getLangOptions().CPlusPlus0x;
Douglas Gregore7526412009-11-11 19:31:23 +00002841 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002842
Douglas Gregore7526412009-11-11 19:31:23 +00002843 case TemplateArgument::Declaration:
David Blaikie7530c032012-01-17 06:56:22 +00002844 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregore7526412009-11-11 19:31:23 +00002845 case TemplateArgument::Integral:
David Blaikie7530c032012-01-17 06:56:22 +00002846 llvm_unreachable("Integral argument with template template parameter");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847
Douglas Gregore7526412009-11-11 19:31:23 +00002848 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002849 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002850 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002851
Douglas Gregore7526412009-11-11 19:31:23 +00002852 return false;
2853}
2854
Douglas Gregorc15cb382009-02-09 23:23:08 +00002855/// \brief Check that the given template argument list is well-formed
2856/// for specializing the given template.
2857bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2858 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00002859 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002860 bool PartialTemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002861 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002862 TemplateParameterList *Params = Template->getTemplateParameters();
2863 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002864 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002865 bool Invalid = false;
2866
John McCalld5532b62009-11-23 01:53:49 +00002867 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2868
Mike Stump1eb44332009-09-09 15:08:12 +00002869 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002870 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002872 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002873 (NumArgs < Params->getMinRequiredArguments() &&
2874 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002875 // FIXME: point at either the first arg beyond what we can handle,
2876 // or the '>', depending on whether we have too many or too few
2877 // arguments.
2878 SourceRange Range;
2879 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002880 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002881 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2882 << (NumArgs > NumParams)
2883 << (isa<ClassTemplateDecl>(Template)? 0 :
2884 isa<FunctionTemplateDecl>(Template)? 1 :
2885 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2886 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002887 Diag(Template->getLocation(), diag::note_template_decl_here)
2888 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002889 Invalid = true;
2890 }
Mike Stump1eb44332009-09-09 15:08:12 +00002891
2892 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002893 // [...] The type and form of each template-argument specified in
2894 // a template-id shall match the type and form specified for the
2895 // corresponding parameter declared by the template in its
2896 // template-parameter-list.
Douglas Gregor67714232011-03-03 02:41:12 +00002897 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002898 SmallVector<TemplateArgument, 2> ArgumentPack;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002899 TemplateParameterList::iterator Param = Params->begin(),
2900 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002901 unsigned ArgIdx = 0;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00002902 LocalInstantiationScope InstScope(*this, true);
Douglas Gregor14be16b2010-12-20 16:57:52 +00002903 while (Param != ParamEnd) {
Douglas Gregorf35f8282009-11-11 21:54:23 +00002904 if (ArgIdx < NumArgs) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002905 // If we have an expanded parameter pack, make sure we don't have too
2906 // many arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002907 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002908 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002909 if (NTTP->isExpandedParameterPack() &&
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002910 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
2911 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2912 << true
2913 << (isa<ClassTemplateDecl>(Template)? 0 :
2914 isa<FunctionTemplateDecl>(Template)? 1 :
2915 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2916 << Template;
2917 Diag(Template->getLocation(), diag::note_template_decl_here)
2918 << Params->getSourceRange();
2919 return true;
2920 }
2921 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002922
Douglas Gregorf35f8282009-11-11 21:54:23 +00002923 // Check the template argument we were given.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002924 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2925 TemplateLoc, RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002926 ArgumentPack.size(), Converted))
Douglas Gregorf35f8282009-11-11 21:54:23 +00002927 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002928
Douglas Gregor14be16b2010-12-20 16:57:52 +00002929 if ((*Param)->isTemplateParameterPack()) {
2930 // The template parameter was a template parameter pack, so take the
2931 // deduced argument and place it on the argument pack. Note that we
2932 // stay on the same template parameter so that we can deduce more
2933 // arguments.
2934 ArgumentPack.push_back(Converted.back());
2935 Converted.pop_back();
2936 } else {
2937 // Move to the next template parameter.
2938 ++Param;
2939 }
2940 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002941 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002942 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002943
Douglas Gregor8735b292011-06-03 02:59:40 +00002944 // If we're checking a partial template argument list, we're done.
2945 if (PartialTemplateArgs) {
2946 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
2947 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
2948 ArgumentPack.data(),
2949 ArgumentPack.size()));
2950
2951 return Invalid;
2952 }
2953
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002954 // If we have a template parameter pack with no more corresponding
Douglas Gregor14be16b2010-12-20 16:57:52 +00002955 // arguments, just break out now and we'll fill in the argument pack below.
2956 if ((*Param)->isTemplateParameterPack())
2957 break;
Douglas Gregorf968d832011-05-27 01:19:52 +00002958
Douglas Gregorf35f8282009-11-11 21:54:23 +00002959 // We have a default template argument that we will use.
2960 TemplateArgumentLoc Arg;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002961
Douglas Gregorf35f8282009-11-11 21:54:23 +00002962 // Retrieve the default template argument from the template
2963 // parameter. For each kind of template parameter, we substitute the
2964 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002965 // (when the template parameter was part of a nested template) into
Douglas Gregorf35f8282009-11-11 21:54:23 +00002966 // the default argument.
2967 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2968 if (!TTP->hasDefaultArgument()) {
Douglas Gregor8735b292011-06-03 02:59:40 +00002969 assert(Invalid && "Missing default argument");
Douglas Gregorf35f8282009-11-11 21:54:23 +00002970 break;
2971 }
2972
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002973 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002974 Template,
2975 TemplateLoc,
2976 RAngleLoc,
2977 TTP,
2978 Converted);
2979 if (!ArgType)
2980 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002981
Douglas Gregorf35f8282009-11-11 21:54:23 +00002982 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2983 ArgType);
2984 } else if (NonTypeTemplateParmDecl *NTTP
2985 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2986 if (!NTTP->hasDefaultArgument()) {
Douglas Gregor8735b292011-06-03 02:59:40 +00002987 assert(Invalid && "Missing default argument");
Douglas Gregorf35f8282009-11-11 21:54:23 +00002988 break;
2989 }
2990
John McCall60d7b3a2010-08-24 06:29:42 +00002991 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002992 TemplateLoc,
2993 RAngleLoc,
2994 NTTP,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002995 Converted);
2996 if (E.isInvalid())
2997 return true;
2998
2999 Expr *Ex = E.takeAs<Expr>();
3000 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3001 } else {
3002 TemplateTemplateParmDecl *TempParm
3003 = cast<TemplateTemplateParmDecl>(*Param);
3004
3005 if (!TempParm->hasDefaultArgument()) {
Douglas Gregor8735b292011-06-03 02:59:40 +00003006 assert(Invalid && "Missing default argument");
Douglas Gregorf35f8282009-11-11 21:54:23 +00003007 break;
3008 }
3009
Douglas Gregor1d752d72011-03-02 18:46:51 +00003010 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregorf35f8282009-11-11 21:54:23 +00003011 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003012 TemplateLoc,
3013 RAngleLoc,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003014 TempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003015 Converted,
3016 QualifierLoc);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003017 if (Name.isNull())
3018 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003020 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3021 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregorf35f8282009-11-11 21:54:23 +00003022 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003023
Douglas Gregorf35f8282009-11-11 21:54:23 +00003024 // Introduce an instantiation record that describes where we are using
3025 // the default template argument.
3026 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00003027 Converted.data(), Converted.size(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003028 SourceRange(TemplateLoc, RAngleLoc));
3029
Douglas Gregorf35f8282009-11-11 21:54:23 +00003030 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00003031 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00003032 RAngleLoc, 0, Converted))
Douglas Gregore7526412009-11-11 19:31:23 +00003033 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003034
Douglas Gregor67714232011-03-03 02:41:12 +00003035 // Core issue 150 (assumed resolution): if this is a template template
3036 // parameter, keep track of the default template arguments from the
3037 // template definition.
3038 if (isTemplateTemplateParameter)
3039 TemplateArgs.addArgument(Arg);
3040
Douglas Gregor14be16b2010-12-20 16:57:52 +00003041 // Move to the next template parameter and argument.
3042 ++Param;
3043 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003044 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003045
Douglas Gregor14be16b2010-12-20 16:57:52 +00003046 // Form argument packs for each of the parameter packs remaining.
3047 while (Param != ParamEnd) {
Douglas Gregord3731192011-01-10 07:32:04 +00003048 // If we're checking a partial list of template arguments, don't fill
3049 // in arguments for non-template parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003050
3051 if ((*Param)->isTemplateParameterPack()) {
David Blaikie1368e582011-10-19 05:19:50 +00003052 if (!HasParameterPack)
3053 return true;
Douglas Gregor8735b292011-06-03 02:59:40 +00003054 if (ArgumentPack.empty())
Douglas Gregor14be16b2010-12-20 16:57:52 +00003055 Converted.push_back(TemplateArgument(0, 0));
Douglas Gregor203e6a32011-01-11 23:09:57 +00003056 else {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003057 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3058 ArgumentPack.data(),
Douglas Gregor203e6a32011-01-11 23:09:57 +00003059 ArgumentPack.size()));
Douglas Gregor14be16b2010-12-20 16:57:52 +00003060 ArgumentPack.clear();
3061 }
3062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063
Douglas Gregor14be16b2010-12-20 16:57:52 +00003064 ++Param;
3065 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003066
Douglas Gregorc15cb382009-02-09 23:23:08 +00003067 return Invalid;
3068}
3069
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003070namespace {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003071 class UnnamedLocalNoLinkageFinder
3072 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003073 {
3074 Sema &S;
3075 SourceRange SR;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003076
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003077 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003078
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003079 public:
3080 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3081
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003082 bool Visit(QualType T) {
3083 return inherited::Visit(T.getTypePtr());
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003084 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003085
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003086#define TYPE(Class, Parent) \
3087 bool Visit##Class##Type(const Class##Type *);
3088#define ABSTRACT_TYPE(Class, Parent) \
3089 bool Visit##Class##Type(const Class##Type *) { return false; }
3090#define NON_CANONICAL_TYPE(Class, Parent) \
3091 bool Visit##Class##Type(const Class##Type *) { return false; }
3092#include "clang/AST/TypeNodes.def"
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003093
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003094 bool VisitTagDecl(const TagDecl *Tag);
3095 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3096 };
3097}
3098
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003099bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003100 return false;
3101}
3102
3103bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3104 return Visit(T->getElementType());
3105}
3106
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003107bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003108 return Visit(T->getPointeeType());
3109}
3110
3111bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112 const BlockPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003113 return Visit(T->getPointeeType());
3114}
3115
3116bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117 const LValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003118 return Visit(T->getPointeeType());
3119}
3120
3121bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122 const RValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003123 return Visit(T->getPointeeType());
3124}
3125
3126bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127 const MemberPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003128 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3129}
3130
3131bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003132 const ConstantArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003133 return Visit(T->getElementType());
3134}
3135
3136bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137 const IncompleteArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003138 return Visit(T->getElementType());
3139}
3140
3141bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142 const VariableArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003143 return Visit(T->getElementType());
3144}
3145
3146bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147 const DependentSizedArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003148 return Visit(T->getElementType());
3149}
3150
3151bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003152 const DependentSizedExtVectorType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003153 return Visit(T->getElementType());
3154}
3155
3156bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3157 return Visit(T->getElementType());
3158}
3159
3160bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3161 return Visit(T->getElementType());
3162}
3163
3164bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3165 const FunctionProtoType* T) {
3166 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003167 AEnd = T->arg_type_end();
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003168 A != AEnd; ++A) {
3169 if (Visit(*A))
3170 return true;
3171 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003172
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003173 return Visit(T->getResultType());
3174}
3175
3176bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3177 const FunctionNoProtoType* T) {
3178 return Visit(T->getResultType());
3179}
3180
3181bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3182 const UnresolvedUsingType*) {
3183 return false;
3184}
3185
3186bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3187 return false;
3188}
3189
3190bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3191 return Visit(T->getUnderlyingType());
3192}
3193
3194bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3195 return false;
3196}
3197
Sean Huntca63c202011-05-24 22:41:36 +00003198bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3199 const UnaryTransformType*) {
3200 return false;
3201}
3202
Richard Smith34b41d92011-02-20 03:19:35 +00003203bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3204 return Visit(T->getDeducedType());
3205}
3206
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003207bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3208 return VisitTagDecl(T->getDecl());
3209}
3210
3211bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3212 return VisitTagDecl(T->getDecl());
3213}
3214
3215bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3216 const TemplateTypeParmType*) {
3217 return false;
3218}
3219
Douglas Gregorc3069d62011-01-14 02:55:32 +00003220bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3221 const SubstTemplateTypeParmPackType *) {
3222 return false;
3223}
3224
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003225bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3226 const TemplateSpecializationType*) {
3227 return false;
3228}
3229
3230bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3231 const InjectedClassNameType* T) {
3232 return VisitTagDecl(T->getDecl());
3233}
3234
3235bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3236 const DependentNameType* T) {
3237 return VisitNestedNameSpecifier(T->getQualifier());
3238}
3239
3240bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3241 const DependentTemplateSpecializationType* T) {
3242 return VisitNestedNameSpecifier(T->getQualifier());
3243}
3244
Douglas Gregor7536dd52010-12-20 02:24:11 +00003245bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3246 const PackExpansionType* T) {
3247 return Visit(T->getPattern());
3248}
3249
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003250bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3251 return false;
3252}
3253
3254bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3255 const ObjCInterfaceType *) {
3256 return false;
3257}
3258
3259bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3260 const ObjCObjectPointerType *) {
3261 return false;
3262}
3263
Eli Friedmanb001de72011-10-06 23:00:33 +00003264bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3265 return Visit(T->getValueType());
3266}
3267
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003268bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3269 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003270 S.Diag(SR.getBegin(),
3271 S.getLangOptions().CPlusPlus0x ?
3272 diag::warn_cxx98_compat_template_arg_local_type :
3273 diag::ext_template_arg_local_type)
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003274 << S.Context.getTypeDeclType(Tag) << SR;
3275 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276 }
3277
Richard Smith162e1c12011-04-15 14:24:37 +00003278 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003279 S.Diag(SR.getBegin(),
3280 S.getLangOptions().CPlusPlus0x ?
3281 diag::warn_cxx98_compat_template_arg_unnamed_type :
3282 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003283 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3284 return true;
3285 }
3286
3287 return false;
3288}
3289
3290bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3291 NestedNameSpecifier *NNS) {
3292 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3293 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003295 switch (NNS->getKind()) {
3296 case NestedNameSpecifier::Identifier:
3297 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00003298 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003299 case NestedNameSpecifier::Global:
3300 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003301
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003302 case NestedNameSpecifier::TypeSpec:
3303 case NestedNameSpecifier::TypeSpecWithTemplate:
3304 return Visit(QualType(NNS->getAsType(), 0));
3305 }
David Blaikie7530c032012-01-17 06:56:22 +00003306 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003307}
3308
3309
Douglas Gregorc15cb382009-02-09 23:23:08 +00003310/// \brief Check a template argument against its corresponding
3311/// template type parameter.
3312///
3313/// This routine implements the semantics of C++ [temp.arg.type]. It
3314/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003315bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00003316 TypeSourceInfo *ArgInfo) {
3317 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00003318 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00003319 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00003320
3321 if (Arg->isVariablyModifiedType()) {
3322 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00003323 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00003324 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003325 }
3326
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003327 // C++03 [temp.arg.type]p2:
3328 // A local type, a type with no linkage, an unnamed type or a type
3329 // compounded from any of these types shall not be used as a
3330 // template-argument for a template type-parameter.
3331 //
Richard Smithebaf0e62011-10-18 20:49:44 +00003332 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003333 // a warning.
Richard Smithebaf0e62011-10-18 20:49:44 +00003334 if (LangOpts.CPlusPlus0x ?
3335 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
3336 SR.getBegin()) != DiagnosticsEngine::Ignored ||
3337 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
3338 SR.getBegin()) != DiagnosticsEngine::Ignored :
3339 Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003340 UnnamedLocalNoLinkageFinder Finder(*this, SR);
3341 (void)Finder.Visit(Context.getCanonicalType(Arg));
3342 }
3343
Douglas Gregorc15cb382009-02-09 23:23:08 +00003344 return false;
3345}
3346
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003347/// \brief Checks whether the given template argument is the address
3348/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349static bool
Douglas Gregorb7a09262010-04-01 18:32:35 +00003350CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3351 NonTypeTemplateParmDecl *Param,
3352 QualType ParamType,
3353 Expr *ArgIn,
3354 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003355 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003356 Expr *Arg = ArgIn;
3357 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003358
3359 // See through any implicit casts we added to fix the type.
John McCall91a57552011-07-15 05:09:51 +00003360 Arg = Arg->IgnoreImpCasts();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003361
3362 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003363 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003364 // A template-argument for a non-type, non-template
3365 // template-parameter shall be one of: [...]
3366 //
3367 // -- the address of an object or function with external
3368 // linkage, including function templates and function
3369 // template-ids but excluding non-static class members,
3370 // expressed as & id-expression where the & is optional if
3371 // the name refers to a function or array, or if the
3372 // corresponding template-parameter is a reference; or
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003374 // In C++98/03 mode, give an extension warning on any extra parentheses.
3375 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3376 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003377 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003378 if (!Invalid && !ExtraParens) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003379 S.Diag(Arg->getSourceRange().getBegin(),
Richard Smithebaf0e62011-10-18 20:49:44 +00003380 S.getLangOptions().CPlusPlus0x ?
3381 diag::warn_cxx98_compat_template_arg_extra_parens :
3382 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003383 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003384 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003385 }
3386
3387 Arg = Parens->getSubExpr();
3388 }
3389
John McCall91a57552011-07-15 05:09:51 +00003390 while (SubstNonTypeTemplateParmExpr *subst =
3391 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3392 Arg = subst->getReplacement()->IgnoreImpCasts();
3393
Douglas Gregorb7a09262010-04-01 18:32:35 +00003394 bool AddressTaken = false;
3395 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003396 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003397 if (UnOp->getOpcode() == UO_AddrOf) {
John McCall91a57552011-07-15 05:09:51 +00003398 Arg = UnOp->getSubExpr();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003399 AddressTaken = true;
3400 AddrOpLoc = UnOp->getOperatorLoc();
3401 }
Francois Picheta343a412011-04-29 09:08:14 +00003402 }
John McCall91a57552011-07-15 05:09:51 +00003403
Francois Pichet62ec1f22011-09-17 17:15:52 +00003404 if (S.getLangOptions().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
John McCall91a57552011-07-15 05:09:51 +00003405 Converted = TemplateArgument(ArgIn);
3406 return false;
3407 }
3408
3409 while (SubstNonTypeTemplateParmExpr *subst =
3410 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3411 Arg = subst->getReplacement()->IgnoreImpCasts();
3412
3413 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003414 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003415 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3416 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003417 S.Diag(Param->getLocation(), diag::note_template_param_here);
3418 return true;
3419 }
Chandler Carruth038cc392010-01-31 10:01:20 +00003420
3421 // Stop checking the precise nature of the argument if it is value dependent,
3422 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00003423 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00003424 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00003425 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003426 }
Chandler Carruth038cc392010-01-31 10:01:20 +00003427
Douglas Gregorb7a09262010-04-01 18:32:35 +00003428 if (!isa<ValueDecl>(DRE->getDecl())) {
3429 S.Diag(Arg->getSourceRange().getBegin(),
3430 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003431 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003432 S.Diag(Param->getLocation(), diag::note_template_param_here);
3433 return true;
3434 }
3435
3436 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003437
3438 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00003439 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
3440 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003441 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003442 S.Diag(Param->getLocation(), diag::note_template_param_here);
3443 return true;
3444 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003445
3446 // Cannot refer to non-static member functions
3447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00003448 if (!Method->isStatic()) {
3449 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003450 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003451 S.Diag(Param->getLocation(), diag::note_template_param_here);
3452 return true;
3453 }
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003455 // Functions must have external linkage.
3456 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00003457 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003458 S.Diag(Arg->getSourceRange().getBegin(),
3459 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003460 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003461 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003462 << true;
3463 return true;
3464 }
3465
3466 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003467 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003468
Douglas Gregorb7a09262010-04-01 18:32:35 +00003469 // If the template parameter has pointer type, the function decays.
3470 if (ParamType->isPointerType() && !AddressTaken)
3471 ArgType = S.Context.getPointerType(Func->getType());
3472 else if (AddressTaken && ParamType->isReferenceType()) {
3473 // If we originally had an address-of operator, but the
3474 // parameter has reference type, complain and (if things look
3475 // like they will work) drop the address-of operator.
3476 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3477 ParamType.getNonReferenceType())) {
3478 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3479 << ParamType;
3480 S.Diag(Param->getLocation(), diag::note_template_param_here);
3481 return true;
3482 }
3483
3484 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3485 << ParamType
3486 << FixItHint::CreateRemoval(AddrOpLoc);
3487 S.Diag(Param->getLocation(), diag::note_template_param_here);
3488
3489 ArgType = Func->getType();
3490 }
3491 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00003492 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003493 S.Diag(Arg->getSourceRange().getBegin(),
3494 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003495 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003496 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003497 << true;
3498 return true;
3499 }
3500
Douglas Gregorb7a09262010-04-01 18:32:35 +00003501 // A value of reference type is not an object.
3502 if (Var->getType()->isReferenceType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003503 S.Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003504 diag::err_template_arg_reference_var)
3505 << Var->getType() << Arg->getSourceRange();
3506 S.Diag(Param->getLocation(), diag::note_template_param_here);
3507 return true;
3508 }
3509
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003510 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003511 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003512
3513 // If the template parameter has pointer type, we must have taken
3514 // the address of this object.
3515 if (ParamType->isReferenceType()) {
3516 if (AddressTaken) {
3517 // If we originally had an address-of operator, but the
3518 // parameter has reference type, complain and (if things look
3519 // like they will work) drop the address-of operator.
3520 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3521 ParamType.getNonReferenceType())) {
3522 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3523 << ParamType;
3524 S.Diag(Param->getLocation(), diag::note_template_param_here);
3525 return true;
3526 }
3527
3528 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3529 << ParamType
3530 << FixItHint::CreateRemoval(AddrOpLoc);
3531 S.Diag(Param->getLocation(), diag::note_template_param_here);
3532
3533 ArgType = Var->getType();
3534 }
3535 } else if (!AddressTaken && ParamType->isPointerType()) {
3536 if (Var->getType()->isArrayType()) {
3537 // Array-to-pointer decay.
3538 ArgType = S.Context.getArrayDecayedType(Var->getType());
3539 } else {
3540 // If the template parameter has pointer type but the address of
3541 // this object was not taken, complain and (possibly) recover by
3542 // taking the address of the entity.
3543 ArgType = S.Context.getPointerType(Var->getType());
3544 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3545 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3546 << ParamType;
3547 S.Diag(Param->getLocation(), diag::note_template_param_here);
3548 return true;
3549 }
3550
3551 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3552 << ParamType
3553 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3554
3555 S.Diag(Param->getLocation(), diag::note_template_param_here);
3556 }
3557 }
3558 } else {
3559 // We found something else, but we don't know specifically what it is.
3560 S.Diag(Arg->getSourceRange().getBegin(),
3561 diag::err_template_arg_not_object_or_func)
3562 << Arg->getSourceRange();
3563 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3564 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003565 }
Mike Stump1eb44332009-09-09 15:08:12 +00003566
John McCallf85e1932011-06-15 23:02:42 +00003567 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003568 if (ParamType->isPointerType() &&
Douglas Gregorb7a09262010-04-01 18:32:35 +00003569 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
John McCallf85e1932011-06-15 23:02:42 +00003570 S.IsQualificationConversion(ArgType, ParamType, false,
3571 ObjCLifetimeConversion)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003572 // For pointer-to-object types, qualification conversions are
3573 // permitted.
3574 } else {
3575 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3576 if (!ParamRef->getPointeeType()->isFunctionType()) {
3577 // C++ [temp.arg.nontype]p5b3:
3578 // For a non-type template-parameter of type reference to
3579 // object, no conversions apply. The type referred to by the
3580 // reference may be more cv-qualified than the (otherwise
3581 // identical) type of the template- argument. The
3582 // template-parameter is bound directly to the
3583 // template-argument, which shall be an lvalue.
3584
3585 // FIXME: Other qualifiers?
3586 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3587 unsigned ArgQuals = ArgType.getCVRQualifiers();
3588
3589 if ((ParamQuals | ArgQuals) != ParamQuals) {
3590 S.Diag(Arg->getSourceRange().getBegin(),
3591 diag::err_template_arg_ref_bind_ignores_quals)
3592 << ParamType << Arg->getType()
3593 << Arg->getSourceRange();
3594 S.Diag(Param->getLocation(), diag::note_template_param_here);
3595 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003597 }
3598 }
3599
3600 // At this point, the template argument refers to an object or
3601 // function with external linkage. We now need to check whether the
3602 // argument and parameter types are compatible.
3603 if (!S.Context.hasSameUnqualifiedType(ArgType,
3604 ParamType.getNonReferenceType())) {
3605 // We can't perform this conversion or binding.
3606 if (ParamType->isReferenceType())
3607 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
John McCall91a57552011-07-15 05:09:51 +00003608 << ParamType << ArgIn->getType() << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003609 else
3610 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
John McCall91a57552011-07-15 05:09:51 +00003611 << ArgIn->getType() << ParamType << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003612 S.Diag(Param->getLocation(), diag::note_template_param_here);
3613 return true;
3614 }
3615 }
3616
3617 // Create the template argument.
3618 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003619 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003620 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003621}
3622
3623/// \brief Checks whether the given template argument is a pointer to
3624/// member constant according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003625bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
Douglas Gregorcaddba02009-11-12 18:38:13 +00003626 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003627 bool Invalid = false;
3628
3629 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003630 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003631 Arg = Cast->getSubExpr();
3632
3633 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003634 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003635 // A template-argument for a non-type, non-template
3636 // template-parameter shall be one of: [...]
3637 //
3638 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003639 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003640
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003641 // In C++98/03 mode, give an extension warning on any extra parentheses.
3642 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3643 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003644 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003645 if (!Invalid && !ExtraParens) {
Mike Stump1eb44332009-09-09 15:08:12 +00003646 Diag(Arg->getSourceRange().getBegin(),
Richard Smithebaf0e62011-10-18 20:49:44 +00003647 getLangOptions().CPlusPlus0x ?
3648 diag::warn_cxx98_compat_template_arg_extra_parens :
3649 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003650 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003651 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003652 }
3653
3654 Arg = Parens->getSubExpr();
3655 }
3656
John McCall91a57552011-07-15 05:09:51 +00003657 while (SubstNonTypeTemplateParmExpr *subst =
3658 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3659 Arg = subst->getReplacement()->IgnoreImpCasts();
3660
Douglas Gregorcaddba02009-11-12 18:38:13 +00003661 // A pointer-to-member constant written &Class::member.
3662 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003663 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003664 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3665 if (DRE && !DRE->getQualifier())
3666 DRE = 0;
3667 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003668 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003669 // A constant of pointer-to-member type.
3670 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3671 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3672 if (VD->getType()->isMemberPointerType()) {
3673 if (isa<NonTypeTemplateParmDecl>(VD) ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003674 (isa<VarDecl>(VD) &&
Douglas Gregorcaddba02009-11-12 18:38:13 +00003675 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3676 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003677 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003678 else
3679 Converted = TemplateArgument(VD->getCanonicalDecl());
3680 return Invalid;
3681 }
3682 }
3683 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684
Douglas Gregorcaddba02009-11-12 18:38:13 +00003685 DRE = 0;
3686 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003687
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003688 if (!DRE)
3689 return Diag(Arg->getSourceRange().getBegin(),
3690 diag::err_template_arg_not_pointer_to_member_form)
3691 << Arg->getSourceRange();
3692
3693 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3694 assert((isa<FieldDecl>(DRE->getDecl()) ||
3695 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3696 "Only non-static member pointers can make it here");
3697
3698 // Okay: this is the address of a non-static member, and therefore
3699 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003700 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003701 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003702 else
3703 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003704 return Invalid;
3705 }
3706
3707 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003708 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003709 diag::err_template_arg_not_pointer_to_member_form)
3710 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003711 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003712 diag::note_template_arg_refers_here);
3713 return true;
3714}
3715
Douglas Gregorc15cb382009-02-09 23:23:08 +00003716/// \brief Check a template argument against its corresponding
3717/// non-type template parameter.
3718///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003719/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley429bb272011-04-08 18:41:53 +00003720/// If an error occurred, it returns ExprError(); otherwise, it
3721/// returns the converted template argument. \p
Douglas Gregor2943aed2009-03-03 04:44:36 +00003722/// InstantiatedParamType is the type of the non-type template
3723/// parameter after it has been instantiated.
John Wiegley429bb272011-04-08 18:41:53 +00003724ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3725 QualType InstantiatedParamType, Expr *Arg,
3726 TemplateArgument &Converted,
3727 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003728 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3729
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003730 // If either the parameter has a dependent type or the argument is
3731 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003732 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3733 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003734 Converted = TemplateArgument(Arg);
John Wiegley429bb272011-04-08 18:41:53 +00003735 return Owned(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003736 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003737
3738 // C++ [temp.arg.nontype]p5:
3739 // The following conversions are performed on each expression used
3740 // as a non-type template-argument. If a non-type
3741 // template-argument cannot be converted to the type of the
3742 // corresponding template-parameter then the program is
3743 // ill-formed.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003744 QualType ParamType = InstantiatedParamType;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003745 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00003746 // C++11:
3747 // -- for a non-type template-parameter of integral or
3748 // enumeration type, conversions permitted in a converted
3749 // constant expression are applied.
3750 //
3751 // C++98:
3752 // -- for a non-type template-parameter of integral or
3753 // enumeration type, integral promotions (4.5) and integral
3754 // conversions (4.7) are applied.
3755
3756 if (CTAK == CTAK_Deduced &&
3757 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
3758 // C++ [temp.deduct.type]p17:
3759 // If, in the declaration of a function template with a non-type
3760 // template-parameter, the non-type template-parameter is used
3761 // in an expression in the function parameter-list and, if the
3762 // corresponding template-argument is deduced, the
3763 // template-argument type shall match the type of the
3764 // template-parameter exactly, except that a template-argument
3765 // deduced from an array bound may be of any integral type.
3766 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3767 << Arg->getType().getUnqualifiedType()
3768 << ParamType.getUnqualifiedType();
3769 Diag(Param->getLocation(), diag::note_template_param_here);
3770 return ExprError();
3771 }
3772
3773 if (getLangOptions().CPlusPlus0x) {
3774 // We can't check arbitrary value-dependent arguments.
3775 // FIXME: If there's no viable conversion to the template parameter type,
3776 // we should be able to diagnose that prior to instantiation.
3777 if (Arg->isValueDependent()) {
3778 Converted = TemplateArgument(Arg);
3779 return Owned(Arg);
3780 }
3781
3782 // C++ [temp.arg.nontype]p1:
3783 // A template-argument for a non-type, non-template template-parameter
3784 // shall be one of:
3785 //
3786 // -- for a non-type template-parameter of integral or enumeration
3787 // type, a converted constant expression of the type of the
3788 // template-parameter; or
3789 llvm::APSInt Value;
3790 ExprResult ArgResult =
3791 CheckConvertedConstantExpression(Arg, ParamType, Value,
3792 CCEK_TemplateArg);
3793 if (ArgResult.isInvalid())
3794 return ExprError();
3795
3796 // Widen the argument value to sizeof(parameter type). This is almost
3797 // always a no-op, except when the parameter type is bool. In
3798 // that case, this may extend the argument from 1 bit to 8 bits.
3799 QualType IntegerType = ParamType;
3800 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
3801 IntegerType = Enum->getDecl()->getIntegerType();
3802 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
3803
3804 Converted = TemplateArgument(Value, Context.getCanonicalType(ParamType));
3805 return ArgResult;
3806 }
3807
Richard Smith4f870622011-10-27 22:11:44 +00003808 ExprResult ArgResult = DefaultLvalueConversion(Arg);
3809 if (ArgResult.isInvalid())
3810 return ExprError();
3811 Arg = ArgResult.take();
3812
3813 QualType ArgType = Arg->getType();
3814
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003815 // C++ [temp.arg.nontype]p1:
3816 // A template-argument for a non-type, non-template
3817 // template-parameter shall be one of:
3818 //
3819 // -- an integral constant-expression of integral or enumeration
3820 // type; or
3821 // -- the name of a non-type template-parameter; or
3822 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003823 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003824 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003825 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003826 diag::err_template_arg_not_integral_or_enumeral)
3827 << ArgType << Arg->getSourceRange();
3828 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003829 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003830 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003831 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003832 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3833 << ArgType << Arg->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003834 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003835 }
3836
Douglas Gregor02024a92010-03-28 02:42:43 +00003837 // From here on out, all we care about are the unqualified forms
3838 // of the parameter and argument types.
3839 ParamType = ParamType.getUnqualifiedType();
3840 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003841
3842 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003843 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003844 // Okay: no conversion necessary
John McCalldaa8e4e2010-11-15 09:13:47 +00003845 } else if (ParamType->isBooleanType()) {
3846 // This is an integral-to-boolean conversion.
John Wiegley429bb272011-04-08 18:41:53 +00003847 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003848 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3849 !ParamType->isEnumeralType()) {
3850 // This is an integral promotion or conversion.
John Wiegley429bb272011-04-08 18:41:53 +00003851 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003852 } else {
3853 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003854 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003855 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003856 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003857 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003858 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003859 }
3860
Douglas Gregorc7469372011-05-04 21:55:00 +00003861 // Add the value of this argument to the list of converted
3862 // arguments. We use the bitwidth and signedness of the template
3863 // parameter.
3864 if (Arg->isValueDependent()) {
3865 // The argument is value-dependent. Create a new
3866 // TemplateArgument with the converted expression.
3867 Converted = TemplateArgument(Arg);
3868 return Owned(Arg);
3869 }
3870
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003871 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003872 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003873 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003874
Douglas Gregorc7469372011-05-04 21:55:00 +00003875 if (ParamType->isBooleanType()) {
3876 // Value must be zero or one.
3877 Value = Value != 0;
3878 unsigned AllowedBits = Context.getTypeSize(IntegerType);
3879 if (Value.getBitWidth() != AllowedBits)
3880 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00003881 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00003882 } else {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003883 llvm::APSInt OldValue = Value;
Douglas Gregorc7469372011-05-04 21:55:00 +00003884
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885 // Coerce the template argument's value to the value it will have
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003886 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003887 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003888 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003889 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00003890 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00003891
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003892 // Complain if an unsigned parameter received a negative value.
Douglas Gregor575a1c92011-05-20 16:38:50 +00003893 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorc7469372011-05-04 21:55:00 +00003894 && (OldValue.isSigned() && OldValue.isNegative())) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003895 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3896 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3897 << Arg->getSourceRange();
3898 Diag(Param->getLocation(), diag::note_template_param_here);
3899 }
Douglas Gregorc7469372011-05-04 21:55:00 +00003900
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003901 // Complain if we overflowed the template parameter's type.
3902 unsigned RequiredBits;
Douglas Gregor575a1c92011-05-20 16:38:50 +00003903 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003904 RequiredBits = OldValue.getActiveBits();
3905 else if (OldValue.isUnsigned())
3906 RequiredBits = OldValue.getActiveBits() + 1;
3907 else
3908 RequiredBits = OldValue.getMinSignedBits();
3909 if (RequiredBits > AllowedBits) {
3910 Diag(Arg->getSourceRange().getBegin(),
3911 diag::warn_template_arg_too_large)
3912 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3913 << Arg->getSourceRange();
3914 Diag(Param->getLocation(), diag::note_template_param_here);
3915 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003916 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003917
John McCall833ca992009-10-29 08:12:44 +00003918 Converted = TemplateArgument(Value,
Douglas Gregor6b63f552011-08-09 01:55:14 +00003919 ParamType->isEnumeralType()
3920 ? Context.getCanonicalType(ParamType)
3921 : IntegerType);
John Wiegley429bb272011-04-08 18:41:53 +00003922 return Owned(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003923 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003924
Richard Smith4f870622011-10-27 22:11:44 +00003925 QualType ArgType = Arg->getType();
John McCall6bb80172010-03-30 21:47:33 +00003926 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3927
Douglas Gregorb7a09262010-04-01 18:32:35 +00003928 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3929 // from a template argument of type std::nullptr_t to a non-type
3930 // template parameter of type pointer to object, pointer to
3931 // function, or pointer-to-member, respectively.
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00003932 if (ArgType->isNullPtrType()) {
3933 if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
3934 Converted = TemplateArgument((NamedDecl *)0);
3935 return Owned(Arg);
3936 }
3937
3938 if (ParamType->isNullPtrType()) {
3939 llvm::APSInt Zero(Context.getTypeSize(Context.NullPtrTy), true);
3940 Converted = TemplateArgument(Zero, Context.NullPtrTy);
3941 return Owned(Arg);
3942 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003943 }
3944
Douglas Gregorb86b0572009-02-11 01:18:59 +00003945 // Handle pointer-to-function, reference-to-function, and
3946 // pointer-to-member-function all in (roughly) the same way.
3947 if (// -- For a non-type template-parameter of type pointer to
3948 // function, only the function-to-pointer conversion (4.3) is
3949 // applied. If the template-argument represents a set of
3950 // overloaded functions (or a pointer to such), the matching
3951 // function is selected from the set (13.4).
3952 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003953 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003954 // -- For a non-type template-parameter of type reference to
3955 // function, no conversions apply. If the template-argument
3956 // represents a set of overloaded functions, the matching
3957 // function is selected from the set (13.4).
3958 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003959 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003960 // -- For a non-type template-parameter of type pointer to
3961 // member function, no conversions apply. If the
3962 // template-argument represents a set of overloaded member
3963 // functions, the matching member function is selected from
3964 // the set (13.4).
3965 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003966 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003967 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003968
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003969 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003970 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003971 true,
3972 FoundResult)) {
3973 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00003974 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003975
3976 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3977 ArgType = Arg->getType();
3978 } else
John Wiegley429bb272011-04-08 18:41:53 +00003979 return ExprError();
Douglas Gregora35284b2009-02-11 00:19:33 +00003980 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003981
John Wiegley429bb272011-04-08 18:41:53 +00003982 if (!ParamType->isMemberPointerType()) {
3983 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3984 ParamType,
3985 Arg, Converted))
3986 return ExprError();
3987 return Owned(Arg);
3988 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003989
John McCallf85e1932011-06-15 23:02:42 +00003990 bool ObjCLifetimeConversion;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003991 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(),
John McCallf85e1932011-06-15 23:02:42 +00003992 false, ObjCLifetimeConversion)) {
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003993 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp,
3994 Arg->getValueKind()).take();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003995 } else if (!Context.hasSameUnqualifiedType(ArgType,
3996 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003997 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003998 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003999 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00004000 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00004001 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00004002 return ExprError();
Douglas Gregora35284b2009-02-11 00:19:33 +00004003 }
Mike Stump1eb44332009-09-09 15:08:12 +00004004
John Wiegley429bb272011-04-08 18:41:53 +00004005 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
4006 return ExprError();
4007 return Owned(Arg);
Douglas Gregora35284b2009-02-11 00:19:33 +00004008 }
4009
Chris Lattnerfe90de72009-02-20 21:37:53 +00004010 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00004011 // -- for a non-type template-parameter of type pointer to
4012 // object, qualification conversions (4.4) and the
4013 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004014 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00004015 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00004016 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004017
John Wiegley429bb272011-04-08 18:41:53 +00004018 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4019 ParamType,
4020 Arg, Converted))
4021 return ExprError();
4022 return Owned(Arg);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004023 }
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Ted Kremenek6217b802009-07-29 21:53:49 +00004025 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00004026 // -- For a non-type template-parameter of type reference to
4027 // object, no conversions apply. The type referred to by the
4028 // reference may be more cv-qualified than the (otherwise
4029 // identical) type of the template-argument. The
4030 // template-parameter is bound directly to the
4031 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00004032 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00004033 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004034
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004035 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004036 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
4037 ParamRefType->getPointeeType(),
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004038 true,
4039 FoundResult)) {
4040 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00004041 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004042
4043 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4044 ArgType = Arg->getType();
4045 } else
John Wiegley429bb272011-04-08 18:41:53 +00004046 return ExprError();
Douglas Gregorb86b0572009-02-11 01:18:59 +00004047 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048
John Wiegley429bb272011-04-08 18:41:53 +00004049 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4050 ParamType,
4051 Arg, Converted))
4052 return ExprError();
4053 return Owned(Arg);
Douglas Gregorb86b0572009-02-11 01:18:59 +00004054 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00004055
4056 // -- For a non-type template-parameter of type pointer to data
4057 // member, qualification conversions (4.4) are applied.
4058 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4059
John McCallf85e1932011-06-15 23:02:42 +00004060 bool ObjCLifetimeConversion;
Douglas Gregor8e6563b2009-02-11 18:22:40 +00004061 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00004062 // Types match exactly: nothing more to do here.
John McCallf85e1932011-06-15 23:02:42 +00004063 } else if (IsQualificationConversion(ArgType, ParamType, false,
4064 ObjCLifetimeConversion)) {
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00004065 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp,
4066 Arg->getValueKind()).take();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004067 } else {
4068 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00004069 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00004070 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00004071 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004072 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00004073 return ExprError();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004074 }
4075
John Wiegley429bb272011-04-08 18:41:53 +00004076 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
4077 return ExprError();
4078 return Owned(Arg);
Douglas Gregorc15cb382009-02-09 23:23:08 +00004079}
4080
4081/// \brief Check a template argument against its corresponding
4082/// template template parameter.
4083///
4084/// This routine implements the semantics of C++ [temp.arg.template].
4085/// It returns true if an error occurred, and false otherwise.
4086bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00004087 const TemplateArgumentLoc &Arg) {
4088 TemplateName Name = Arg.getArgument().getAsTemplate();
4089 TemplateDecl *Template = Name.getAsTemplateDecl();
4090 if (!Template) {
4091 // Any dependent template name is fine.
4092 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
4093 return false;
4094 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00004095
Richard Smith3e4c6c42011-05-05 21:57:07 +00004096 // C++0x [temp.arg.template]p1:
Douglas Gregordd0574e2009-02-10 00:24:35 +00004097 // A template-argument for a template template-parameter shall be
Richard Smith3e4c6c42011-05-05 21:57:07 +00004098 // the name of a class template or an alias template, expressed as an
4099 // id-expression. When the template-argument names a class template, only
Douglas Gregordd0574e2009-02-10 00:24:35 +00004100 // primary class templates are considered when matching the
4101 // template template argument with the corresponding parameter;
4102 // partial specializations are not considered even if their
4103 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004104 //
4105 // Note that we also allow template template parameters here, which
4106 // will happen when we are dealing with, e.g., class template
4107 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00004108 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00004109 !isa<TemplateTemplateParmDecl>(Template) &&
4110 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004111 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00004112 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00004113 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00004114 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00004115 << Template;
4116 }
4117
4118 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
4119 Param->getTemplateParameters(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004120 true,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004121 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00004122 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00004123}
4124
Douglas Gregor02024a92010-03-28 02:42:43 +00004125/// \brief Given a non-type template argument that refers to a
4126/// declaration and the type of its corresponding non-type template
4127/// parameter, produce an expression that properly refers to that
4128/// declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004129ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004130Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4131 QualType ParamType,
4132 SourceLocation Loc) {
4133 assert(Arg.getKind() == TemplateArgument::Declaration &&
4134 "Only declaration template arguments permitted here");
4135 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4136
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004137 if (VD->getDeclContext()->isRecord() &&
Douglas Gregor02024a92010-03-28 02:42:43 +00004138 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4139 // If the value is a class member, we might have a pointer-to-member.
4140 // Determine whether the non-type template template parameter is of
4141 // pointer-to-member type. If so, we need to build an appropriate
4142 // expression for a pointer-to-member, since a "normal" DeclRefExpr
4143 // would refer to the member itself.
4144 if (ParamType->isMemberPointerType()) {
4145 QualType ClassType
4146 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4147 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00004148 = NestedNameSpecifier::Create(Context, 0, false,
4149 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00004150 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00004151 SS.MakeTrivial(Context, Qualifier, Loc);
John McCalldfa1edb2010-11-23 20:48:44 +00004152
4153 // The actual value-ness of this is unimportant, but for
4154 // internal consistency's sake, references to instance methods
4155 // are r-values.
4156 ExprValueKind VK = VK_LValue;
4157 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4158 VK = VK_RValue;
4159
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004160 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00004161 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00004162 VK,
John McCallf89e55a2010-11-18 06:31:45 +00004163 Loc,
4164 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00004165 if (RefExpr.isInvalid())
4166 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004167
John McCall2de56d12010-08-25 11:45:40 +00004168 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004169
Douglas Gregorc0c83002010-04-30 21:46:38 +00004170 // We might need to perform a trailing qualification conversion, since
4171 // the element type on the parameter could be more qualified than the
4172 // element type in the expression we constructed.
John McCallf85e1932011-06-15 23:02:42 +00004173 bool ObjCLifetimeConversion;
Douglas Gregorc0c83002010-04-30 21:46:38 +00004174 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCallf85e1932011-06-15 23:02:42 +00004175 ParamType.getUnqualifiedType(), false,
4176 ObjCLifetimeConversion))
John Wiegley429bb272011-04-08 18:41:53 +00004177 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178
Douglas Gregor02024a92010-03-28 02:42:43 +00004179 assert(!RefExpr.isInvalid() &&
4180 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00004181 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00004182 return move(RefExpr);
4183 }
4184 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185
Douglas Gregor02024a92010-03-28 02:42:43 +00004186 QualType T = VD->getType().getNonReferenceType();
4187 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00004188 // When the non-type template parameter is a pointer, take the
4189 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00004190 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004191 if (RefExpr.isInvalid())
4192 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004193
4194 if (T->isFunctionType() || T->isArrayType()) {
4195 // Decay functions and arrays.
John Wiegley429bb272011-04-08 18:41:53 +00004196 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4197 if (RefExpr.isInvalid())
4198 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004199
4200 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00004201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004202
Douglas Gregorb7a09262010-04-01 18:32:35 +00004203 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00004204 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00004205 }
4206
John McCallf89e55a2010-11-18 06:31:45 +00004207 ExprValueKind VK = VK_RValue;
4208
Douglas Gregor02024a92010-03-28 02:42:43 +00004209 // If the non-type template parameter has reference type, qualify the
4210 // resulting declaration reference with the extra qualifiers on the
4211 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00004212 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4213 VK = VK_LValue;
4214 T = Context.getQualifiedType(T,
4215 TargetRef->getPointeeType().getQualifiers());
4216 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004217
John McCallf89e55a2010-11-18 06:31:45 +00004218 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004219}
4220
4221/// \brief Construct a new expression that refers to the given
4222/// integral template argument with the given source-location
4223/// information.
4224///
4225/// This routine takes care of the mapping from an integral template
4226/// argument (which may have any integral type) to the appropriate
4227/// literal value.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004228ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004229Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4230 SourceLocation Loc) {
4231 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregord3731192011-01-10 07:32:04 +00004232 "Operation is only valid for integral template arguments");
Douglas Gregor02024a92010-03-28 02:42:43 +00004233 QualType T = Arg.getIntegralType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00004234 if (T->isAnyCharacterType()) {
4235 CharacterLiteral::CharacterKind Kind;
4236 if (T->isWideCharType())
4237 Kind = CharacterLiteral::Wide;
4238 else if (T->isChar16Type())
4239 Kind = CharacterLiteral::UTF16;
4240 else if (T->isChar32Type())
4241 Kind = CharacterLiteral::UTF32;
4242 else
4243 Kind = CharacterLiteral::Ascii;
4244
Douglas Gregor02024a92010-03-28 02:42:43 +00004245 return Owned(new (Context) CharacterLiteral(
Douglas Gregor5cee1192011-07-27 05:40:30 +00004246 Arg.getAsIntegral()->getZExtValue(),
4247 Kind, T, Loc));
4248 }
4249
Douglas Gregor02024a92010-03-28 02:42:43 +00004250 if (T->isBooleanType())
4251 return Owned(new (Context) CXXBoolLiteralExpr(
4252 Arg.getAsIntegral()->getBoolValue(),
Chris Lattner223de242011-04-25 20:37:58 +00004253 T, Loc));
Douglas Gregor02024a92010-03-28 02:42:43 +00004254
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004255 if (T->isNullPtrType())
4256 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
4257
Chris Lattner223de242011-04-25 20:37:58 +00004258 // If this is an enum type that we're instantiating, we need to use an integer
4259 // type the same size as the enumerator. We don't want to build an
4260 // IntegerLiteral with enum type.
Peter Collingbournefb7b3632010-12-15 15:06:14 +00004261 QualType BT;
4262 if (const EnumType *ET = T->getAs<EnumType>())
Chris Lattner223de242011-04-25 20:37:58 +00004263 BT = ET->getDecl()->getIntegerType();
Peter Collingbournefb7b3632010-12-15 15:06:14 +00004264 else
4265 BT = T;
4266
John McCall4e9272d2011-07-15 07:47:58 +00004267 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
4268 if (T->isEnumeralType()) {
4269 // FIXME: This is a hack. We need a better way to handle substituted
4270 // non-type template parameters.
4271 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0,
4272 Context.getTrivialTypeSourceInfo(T, Loc),
4273 Loc, Loc);
4274 }
4275
4276 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00004277}
4278
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004279/// \brief Match two template parameters within template parameter lists.
4280static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4281 bool Complain,
4282 Sema::TemplateParameterListEqualKind Kind,
4283 SourceLocation TemplateArgLoc) {
4284 // Check the actual kind (type, non-type, template).
4285 if (Old->getKind() != New->getKind()) {
4286 if (Complain) {
4287 unsigned NextDiag = diag::err_template_param_different_kind;
4288 if (TemplateArgLoc.isValid()) {
4289 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4290 NextDiag = diag::note_template_param_different_kind;
4291 }
4292 S.Diag(New->getLocation(), NextDiag)
4293 << (Kind != Sema::TPL_TemplateMatch);
4294 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4295 << (Kind != Sema::TPL_TemplateMatch);
4296 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004297
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004298 return false;
4299 }
4300
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301 // Check that both are parameter packs are neither are parameter packs.
4302 // However, if we are matching a template template argument to a
Douglas Gregora0347822011-01-13 00:08:50 +00004303 // template template parameter, the template template parameter can have
4304 // a parameter pack where the template template argument does not.
4305 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4306 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4307 Old->isTemplateParameterPack())) {
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004308 if (Complain) {
4309 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4310 if (TemplateArgLoc.isValid()) {
4311 S.Diag(TemplateArgLoc,
4312 diag::err_template_arg_template_params_mismatch);
4313 NextDiag = diag::note_template_parameter_pack_non_pack;
4314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004316 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4317 : isa<NonTypeTemplateParmDecl>(New)? 1
4318 : 2;
4319 S.Diag(New->getLocation(), NextDiag)
4320 << ParamKind << New->isParameterPack();
4321 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4322 << ParamKind << Old->isParameterPack();
4323 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004324
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004325 return false;
4326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004328 // For non-type template parameters, check the type of the parameter.
4329 if (NonTypeTemplateParmDecl *OldNTTP
4330 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4331 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004333 // If we are matching a template template argument to a template
4334 // template parameter and one of the non-type template parameter types
4335 // is dependent, then we must wait until template instantiation time
4336 // to actually compare the arguments.
4337 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4338 (OldNTTP->getType()->isDependentType() ||
4339 NewNTTP->getType()->isDependentType()))
4340 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004341
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004342 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4343 if (Complain) {
4344 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4345 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004346 S.Diag(TemplateArgLoc,
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004347 diag::err_template_arg_template_params_mismatch);
4348 NextDiag = diag::note_template_nontype_parm_different_type;
4349 }
4350 S.Diag(NewNTTP->getLocation(), NextDiag)
4351 << NewNTTP->getType()
4352 << (Kind != Sema::TPL_TemplateMatch);
4353 S.Diag(OldNTTP->getLocation(),
4354 diag::note_template_nontype_parm_prev_declaration)
4355 << OldNTTP->getType();
4356 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004357
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004358 return false;
4359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004360
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004361 return true;
4362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004363
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004364 // For template template parameters, check the template parameter types.
4365 // The template parameter lists of template template
4366 // parameters must agree.
4367 if (TemplateTemplateParmDecl *OldTTP
4368 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004369 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004370 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4371 OldTTP->getTemplateParameters(),
4372 Complain,
4373 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004375 : Kind),
4376 TemplateArgLoc);
4377 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004378
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004379 return true;
4380}
Douglas Gregor02024a92010-03-28 02:42:43 +00004381
Douglas Gregora0347822011-01-13 00:08:50 +00004382/// \brief Diagnose a known arity mismatch when comparing template argument
4383/// lists.
4384static
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004385void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregora0347822011-01-13 00:08:50 +00004386 TemplateParameterList *New,
4387 TemplateParameterList *Old,
4388 Sema::TemplateParameterListEqualKind Kind,
4389 SourceLocation TemplateArgLoc) {
4390 unsigned NextDiag = diag::err_template_param_list_different_arity;
4391 if (TemplateArgLoc.isValid()) {
4392 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4393 NextDiag = diag::note_template_param_list_different_arity;
4394 }
4395 S.Diag(New->getTemplateLoc(), NextDiag)
4396 << (New->size() > Old->size())
4397 << (Kind != Sema::TPL_TemplateMatch)
4398 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4399 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4400 << (Kind != Sema::TPL_TemplateMatch)
4401 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4402}
4403
Douglas Gregorddc29e12009-02-06 22:42:48 +00004404/// \brief Determine whether the given template parameter lists are
4405/// equivalent.
4406///
Mike Stump1eb44332009-09-09 15:08:12 +00004407/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00004408/// source code as part of a new template declaration.
4409///
4410/// \param Old The old template parameter list, typically found via
4411/// name lookup of the template declared with this template parameter
4412/// list.
4413///
4414/// \param Complain If true, this routine will produce a diagnostic if
4415/// the template parameter lists are not equivalent.
4416///
Douglas Gregorfb898e12009-11-12 16:20:59 +00004417/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00004418///
4419/// \param TemplateArgLoc If this source location is valid, then we
4420/// are actually checking the template parameter list of a template
4421/// argument (New) against the template parameter list of its
4422/// corresponding template template parameter (Old). We produce
4423/// slightly different diagnostics in this scenario.
4424///
Douglas Gregorddc29e12009-02-06 22:42:48 +00004425/// \returns True if the template parameter lists are equal, false
4426/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00004427bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00004428Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4429 TemplateParameterList *Old,
4430 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004431 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00004432 SourceLocation TemplateArgLoc) {
Douglas Gregora0347822011-01-13 00:08:50 +00004433 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4434 if (Complain)
4435 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4436 TemplateArgLoc);
Douglas Gregorddc29e12009-02-06 22:42:48 +00004437
4438 return false;
4439 }
4440
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004441 // C++0x [temp.arg.template]p3:
4442 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004443 // when each of the template parameters in the template-parameter-list of
Richard Smith3e4c6c42011-05-05 21:57:07 +00004444 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004445 // (call it A) matches the corresponding template parameter in the
Douglas Gregora0347822011-01-13 00:08:50 +00004446 // template-parameter-list of P. [...]
4447 TemplateParameterList::iterator NewParm = New->begin();
4448 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004449 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregora0347822011-01-13 00:08:50 +00004450 OldParmEnd = Old->end();
4451 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregorc421f542011-01-13 18:47:47 +00004452 if (Kind != TPL_TemplateTemplateArgumentMatch ||
4453 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregora0347822011-01-13 00:08:50 +00004454 if (NewParm == NewParmEnd) {
4455 if (Complain)
4456 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4457 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004458
Douglas Gregora0347822011-01-13 00:08:50 +00004459 return false;
4460 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004461
Douglas Gregora0347822011-01-13 00:08:50 +00004462 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4463 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004464 return false;
4465
Douglas Gregora0347822011-01-13 00:08:50 +00004466 ++NewParm;
4467 continue;
4468 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004469
Douglas Gregora0347822011-01-13 00:08:50 +00004470 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004471 // [...] When P's template- parameter-list contains a template parameter
4472 // pack (14.5.3), the template parameter pack will match zero or more
4473 // template parameters or template parameter packs in the
Douglas Gregora0347822011-01-13 00:08:50 +00004474 // template-parameter-list of A with the same type and form as the
4475 // template parameter pack in P (ignoring whether those template
4476 // parameters are template parameter packs).
4477 for (; NewParm != NewParmEnd; ++NewParm) {
4478 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4479 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004480 return false;
Douglas Gregora0347822011-01-13 00:08:50 +00004481 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00004482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004483
Douglas Gregora0347822011-01-13 00:08:50 +00004484 // Make sure we exhausted all of the arguments.
4485 if (NewParm != NewParmEnd) {
4486 if (Complain)
4487 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4488 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004489
Douglas Gregora0347822011-01-13 00:08:50 +00004490 return false;
4491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Douglas Gregorddc29e12009-02-06 22:42:48 +00004493 return true;
4494}
4495
4496/// \brief Check whether a template can be declared within this scope.
4497///
4498/// If the template declaration is valid in this scope, returns
4499/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00004500bool
Douglas Gregor05396e22009-08-25 17:23:04 +00004501Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorfb35e8f2011-11-03 16:37:14 +00004502 if (!S)
4503 return false;
4504
Douglas Gregorddc29e12009-02-06 22:42:48 +00004505 // Find the nearest enclosing declaration scope.
4506 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4507 (S->getFlags() & Scope::TemplateParamScope) != 0)
4508 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Douglas Gregorddc29e12009-02-06 22:42:48 +00004510 // C++ [temp]p2:
4511 // A template-declaration can appear only as a namespace scope or
4512 // class scope declaration.
4513 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00004514 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4515 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00004516 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00004517 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004518
Eli Friedman1503f772009-07-31 01:43:05 +00004519 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00004520 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004521
4522 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4523 return false;
4524
Mike Stump1eb44332009-09-09 15:08:12 +00004525 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004526 diag::err_template_outside_namespace_or_class_scope)
4527 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004528}
Douglas Gregorcc636682009-02-17 23:15:12 +00004529
Douglas Gregord5cb8762009-10-07 00:13:32 +00004530/// \brief Determine what kind of template specialization the given declaration
4531/// is.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00004532static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004533 if (!D)
4534 return TSK_Undeclared;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004535
Douglas Gregorf6b11852009-10-08 15:14:33 +00004536 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4537 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00004538 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4539 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004540 if (VarDecl *Var = dyn_cast<VarDecl>(D))
4541 return Var->getTemplateSpecializationKind();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004542
Douglas Gregord5cb8762009-10-07 00:13:32 +00004543 return TSK_Undeclared;
4544}
4545
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004546/// \brief Check whether a specialization is well-formed in the current
Douglas Gregor9302da62009-10-14 23:50:59 +00004547/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00004548///
Douglas Gregor9302da62009-10-14 23:50:59 +00004549/// This routine determines whether a template specialization can be declared
4550/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004551///
4552/// \param S the semantic analysis object for which this check is being
4553/// performed.
4554///
4555/// \param Specialized the entity being specialized or instantiated, which
4556/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004557/// a member of a class template (member function, static data member,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004558/// member class).
4559///
4560/// \param PrevDecl the previous declaration of this entity, if any.
4561///
4562/// \param Loc the location of the explicit specialization or instantiation of
4563/// this entity.
4564///
4565/// \param IsPartialSpecialization whether this is a partial specialization of
4566/// a class template.
4567///
Douglas Gregord5cb8762009-10-07 00:13:32 +00004568/// \returns true if there was an error that we cannot recover from, false
4569/// otherwise.
4570static bool CheckTemplateSpecializationScope(Sema &S,
4571 NamedDecl *Specialized,
4572 NamedDecl *PrevDecl,
4573 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00004574 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004575 // Keep these "kind" numbers in sync with the %select statements in the
4576 // various diagnostics emitted by this routine.
4577 int EntityKind = 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004578 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004579 EntityKind = IsPartialSpecialization? 1 : 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004580 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004581 EntityKind = 2;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004582 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004583 EntityKind = 3;
4584 else if (isa<VarDecl>(Specialized))
4585 EntityKind = 4;
4586 else if (isa<RecordDecl>(Specialized))
4587 EntityKind = 5;
4588 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00004589 S.Diag(Loc, diag::err_template_spec_unknown_kind);
4590 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00004591 return true;
4592 }
4593
Douglas Gregor88b70942009-02-25 22:02:03 +00004594 // C++ [temp.expl.spec]p2:
4595 // An explicit specialization shall be declared in the namespace
4596 // of which the template is a member, or, for member templates, in
4597 // the namespace of which the enclosing class or enclosing class
4598 // template is a member. An explicit specialization of a member
4599 // function, member class or static data member of a class
4600 // template shall be declared in the namespace of which the class
4601 // template is a member. Such a declaration may also be a
4602 // definition. If the declaration is not a definition, the
4603 // specialization may be defined later in the name- space in which
4604 // the explicit specialization was declared, or in a namespace
4605 // that encloses the one in which the explicit specialization was
4606 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004607 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004608 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00004609 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00004610 return true;
4611 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004612
Douglas Gregor0a407472009-10-07 17:30:37 +00004613 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
Francois Pichet62ec1f22011-09-17 17:15:52 +00004614 if (S.getLangOptions().MicrosoftExt) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004615 // Do not warn for class scope explicit specialization during
4616 // instantiation, warning was already emitted during pattern
4617 // semantic analysis.
4618 if (!S.ActiveTemplateInstantiations.size())
4619 S.Diag(Loc, diag::ext_function_specialization_in_class)
4620 << Specialized;
4621 } else {
4622 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4623 << Specialized;
4624 return true;
4625 }
Douglas Gregor0a407472009-10-07 17:30:37 +00004626 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004627
Douglas Gregor8e0c1182011-10-20 16:41:18 +00004628 if (S.CurContext->isRecord() &&
4629 !S.CurContext->Equals(Specialized->getDeclContext())) {
4630 // Make sure that we're specializing in the right record context.
4631 // Otherwise, things can go horribly wrong.
4632 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4633 << Specialized;
4634 return true;
4635 }
4636
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004637 // C++ [temp.class.spec]p6:
4638 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004639 // in any namespace scope in which its definition may be defined (14.5.1
4640 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004641 bool ComplainedAboutScope = false;
Douglas Gregor8e0c1182011-10-20 16:41:18 +00004642 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00004643 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004644 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004645 if ((!PrevDecl ||
Douglas Gregor9302da62009-10-14 23:50:59 +00004646 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4647 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004648 // C++ [temp.exp.spec]p2:
4649 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004650 // the template is a member, or, for member templates, in the namespace
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004651 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004652 // An explicit specialization of a member function, member class or
4653 // static data member of a class template shall be declared in the
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004654 // namespace of which the class template is a member.
4655 //
4656 // C++0x [temp.expl.spec]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004657 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004658 // the specialized template.
Richard Smithebaf0e62011-10-18 20:49:44 +00004659 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
4660 bool IsCPlusPlus0xExtension = DC->Encloses(SpecializedContext);
4661 if (isa<TranslationUnitDecl>(SpecializedContext)) {
4662 assert(!IsCPlusPlus0xExtension &&
4663 "DC encloses TU but isn't in enclosing namespace set");
4664 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregora4d5de52010-09-12 05:24:55 +00004665 << EntityKind << Specialized;
Richard Smithebaf0e62011-10-18 20:49:44 +00004666 } else if (isa<NamespaceDecl>(SpecializedContext)) {
4667 int Diag;
4668 if (!IsCPlusPlus0xExtension)
4669 Diag = diag::err_template_spec_decl_out_of_scope;
4670 else if (!S.getLangOptions().CPlusPlus0x)
4671 Diag = diag::ext_template_spec_decl_out_of_scope;
4672 else
4673 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
4674 S.Diag(Loc, Diag)
4675 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
4676 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677
Douglas Gregor9302da62009-10-14 23:50:59 +00004678 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Richard Smithebaf0e62011-10-18 20:49:44 +00004679 ComplainedAboutScope =
4680 !(IsCPlusPlus0xExtension && S.getLangOptions().CPlusPlus0x);
Douglas Gregor88b70942009-02-25 22:02:03 +00004681 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004682 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004683
4684 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00004685 // namespace.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004686 // Note that HandleDeclarator() performs this check for explicit
Douglas Gregord5cb8762009-10-07 00:13:32 +00004687 // specializations of function templates, static data members, and member
4688 // functions, so we skip the check here for those kinds of entities.
4689 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004690 // Should we refactor that check, so that it occurs later?
4691 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00004692 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4693 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004694 if (isa<TranslationUnitDecl>(SpecializedContext))
4695 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4696 << EntityKind << Specialized;
4697 else if (isa<NamespaceDecl>(SpecializedContext))
4698 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4699 << EntityKind << Specialized
4700 << cast<NamedDecl>(SpecializedContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004701
Douglas Gregor9302da62009-10-14 23:50:59 +00004702 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00004703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004704
Douglas Gregord5cb8762009-10-07 00:13:32 +00004705 // FIXME: check for specialization-after-instantiation errors and such.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004706
Douglas Gregor88b70942009-02-25 22:02:03 +00004707 return false;
4708}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004709
Douglas Gregorbacb9492011-01-03 21:13:47 +00004710/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4711/// that checks non-type template partial specialization arguments.
4712static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4713 NonTypeTemplateParmDecl *Param,
4714 const TemplateArgument *Args,
4715 unsigned NumArgs) {
4716 for (unsigned I = 0; I != NumArgs; ++I) {
4717 if (Args[I].getKind() == TemplateArgument::Pack) {
4718 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004719 Args[I].pack_begin(),
Douglas Gregorbacb9492011-01-03 21:13:47 +00004720 Args[I].pack_size()))
4721 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722
Douglas Gregore94866f2009-06-12 21:21:02 +00004723 continue;
Douglas Gregorbacb9492011-01-03 21:13:47 +00004724 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004725
Douglas Gregorbacb9492011-01-03 21:13:47 +00004726 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004727 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004728 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004729 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004730
Douglas Gregor7a21fd42011-01-03 21:37:45 +00004731 // We can have a pack expansion of any of the bullets below.
Douglas Gregorbacb9492011-01-03 21:13:47 +00004732 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4733 ArgExpr = Expansion->getPattern();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004734
4735 // Strip off any implicit casts we added as part of type checking.
4736 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4737 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004738
Douglas Gregore94866f2009-06-12 21:21:02 +00004739 // C++ [temp.class.spec]p8:
4740 // A non-type argument is non-specialized if it is the name of a
4741 // non-type parameter. All other non-type arguments are
4742 // specialized.
4743 //
4744 // Below, we check the two conditions that only apply to
4745 // specialized non-type arguments, so skip any non-specialized
4746 // arguments.
4747 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004748 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00004749 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750
Douglas Gregore94866f2009-06-12 21:21:02 +00004751 // C++ [temp.class.spec]p9:
4752 // Within the argument list of a class template partial
4753 // specialization, the following restrictions apply:
4754 // -- A partially specialized non-type argument expression
4755 // shall not involve a template parameter of the partial
4756 // specialization except when the argument expression is a
4757 // simple identifier.
4758 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004759 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004760 diag::err_dependent_non_type_arg_in_partial_spec)
4761 << ArgExpr->getSourceRange();
4762 return true;
4763 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004764
Douglas Gregore94866f2009-06-12 21:21:02 +00004765 // -- The type of a template parameter corresponding to a
4766 // specialized non-type argument shall not be dependent on a
4767 // parameter of the specialization.
4768 if (Param->getType()->isDependentType()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004769 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004770 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4771 << Param->getType()
4772 << ArgExpr->getSourceRange();
Douglas Gregorbacb9492011-01-03 21:13:47 +00004773 S.Diag(Param->getLocation(), diag::note_template_param_here);
Douglas Gregore94866f2009-06-12 21:21:02 +00004774 return true;
4775 }
4776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004777
Douglas Gregorbacb9492011-01-03 21:13:47 +00004778 return false;
4779}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004780
Douglas Gregorbacb9492011-01-03 21:13:47 +00004781/// \brief Check the non-type template arguments of a class template
4782/// partial specialization according to C++ [temp.class.spec]p9.
4783///
4784/// \param TemplateParams the template parameters of the primary class
4785/// template.
4786///
4787/// \param TemplateArg the template arguments of the class template
4788/// partial specialization.
4789///
4790/// \returns true if there was an error, false otherwise.
4791static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4792 TemplateParameterList *TemplateParams,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004793 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004794 const TemplateArgument *ArgList = TemplateArgs.data();
4795
4796 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4797 NonTypeTemplateParmDecl *Param
4798 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4799 if (!Param)
4800 continue;
4801
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004802 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
Douglas Gregorbacb9492011-01-03 21:13:47 +00004803 &ArgList[I], 1))
4804 return true;
4805 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004806
4807 return false;
4808}
4809
John McCalld226f652010-08-21 09:40:31 +00004810DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004811Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4812 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004813 SourceLocation KWLoc,
Douglas Gregord023aec2011-09-09 20:53:38 +00004814 SourceLocation ModulePrivateLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004815 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004816 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004817 SourceLocation TemplateNameLoc,
4818 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004819 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004820 SourceLocation RAngleLoc,
4821 AttributeList *Attr,
4822 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004823 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004824
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004825 // NOTE: KWLoc is the location of the tag keyword. This will instead
4826 // store the location of the outermost template keyword in the declaration.
4827 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
4828 ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation();
4829
Douglas Gregorcc636682009-02-17 23:15:12 +00004830 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004831 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004832 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004833 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4834
4835 if (!ClassTemplate) {
4836 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004837 << (Name.getAsTemplateDecl() &&
Douglas Gregor8b13c082009-11-12 00:46:20 +00004838 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4839 return true;
4840 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004841
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004842 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004843 bool isPartialSpecialization = false;
4844
Douglas Gregor88b70942009-02-25 22:02:03 +00004845 // Check the validity of the template headers that introduce this
4846 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004847 // FIXME: We probably shouldn't complain about these headers for
4848 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004849 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004850 TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00004851 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
4852 TemplateNameLoc,
4853 SS,
Mike Stump1eb44332009-09-09 15:08:12 +00004854 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004855 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004856 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004857 isExplicitSpecialization,
4858 Invalid);
4859 if (Invalid)
4860 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004861
Douglas Gregor05396e22009-08-25 17:23:04 +00004862 if (TemplateParams && TemplateParams->size() > 0) {
4863 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004864
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004865 if (TUK == TUK_Friend) {
4866 Diag(KWLoc, diag::err_partial_specialization_friend)
4867 << SourceRange(LAngleLoc, RAngleLoc);
4868 return true;
4869 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004870
Douglas Gregor05396e22009-08-25 17:23:04 +00004871 // C++ [temp.class.spec]p10:
4872 // The template parameter list of a specialization shall not
4873 // contain default template argument values.
4874 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4875 Decl *Param = TemplateParams->getParam(I);
4876 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4877 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004878 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004879 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004880 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004881 }
4882 } else if (NonTypeTemplateParmDecl *NTTP
4883 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4884 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004885 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004886 diag::err_default_arg_in_partial_spec)
4887 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004888 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004889 }
4890 } else {
4891 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004892 if (TTP->hasDefaultArgument()) {
4893 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004894 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004895 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004896 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004897 }
4898 }
4899 }
Douglas Gregora735b202009-10-13 14:39:41 +00004900 } else if (TemplateParams) {
4901 if (TUK == TUK_Friend)
4902 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004903 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004904 SourceRange(TemplateParams->getTemplateLoc(),
4905 TemplateParams->getRAngleLoc()))
4906 << SourceRange(LAngleLoc, RAngleLoc);
4907 else
4908 isExplicitSpecialization = true;
4909 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004910 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004911 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004912 isExplicitSpecialization = true;
4913 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004914
Douglas Gregorcc636682009-02-17 23:15:12 +00004915 // Check that the specialization uses the same tag kind as the
4916 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004917 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4918 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004919 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00004920 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004921 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004922 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004923 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004924 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004925 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004926 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004927 diag::note_previous_use);
4928 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4929 }
4930
Douglas Gregor40808ce2009-03-09 23:48:35 +00004931 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004932 TemplateArgumentListInfo TemplateArgs;
4933 TemplateArgs.setLAngleLoc(LAngleLoc);
4934 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004935 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004936
Douglas Gregor925910d2011-01-03 20:35:03 +00004937 // Check for unexpanded parameter packs in any of the template arguments.
4938 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004939 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor925910d2011-01-03 20:35:03 +00004940 UPPC_PartialSpecialization))
4941 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004942
Douglas Gregorcc636682009-02-17 23:15:12 +00004943 // Check that the template argument list is well-formed for this
4944 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004945 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004946 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4947 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004948 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004949
Douglas Gregor910f8002010-11-07 23:05:16 +00004950 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004951 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004952
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004953 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004954 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004955 if (isPartialSpecialization) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004956 if (CheckClassTemplatePartialSpecializationArgs(*this,
Douglas Gregore94866f2009-06-12 21:21:02 +00004957 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004958 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004959 return true;
4960
Douglas Gregor561f8122011-07-01 01:22:09 +00004961 bool InstantiationDependent;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004962 if (!Name.isDependent() &&
Douglas Gregorde090962010-02-09 00:37:32 +00004963 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004964 TemplateArgs.getArgumentArray(),
Douglas Gregor561f8122011-07-01 01:22:09 +00004965 TemplateArgs.size(),
4966 InstantiationDependent)) {
Douglas Gregorde090962010-02-09 00:37:32 +00004967 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4968 << ClassTemplate->getDeclName();
4969 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004970 }
4971 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004972
Douglas Gregorcc636682009-02-17 23:15:12 +00004973 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004974 ClassTemplateSpecializationDecl *PrevDecl = 0;
4975
4976 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004977 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004978 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004979 = ClassTemplate->findPartialSpecialization(Converted.data(),
4980 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004981 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004982 else
4983 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004984 = ClassTemplate->findSpecialization(Converted.data(),
4985 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004986
4987 ClassTemplateSpecializationDecl *Specialization = 0;
4988
Douglas Gregor88b70942009-02-25 22:02:03 +00004989 // Check whether we can declare a class template specialization in
4990 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004991 if (TUK != TUK_Friend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004992 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
4993 TemplateNameLoc,
Douglas Gregor9302da62009-10-14 23:50:59 +00004994 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004995 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004996
Douglas Gregorb88e8882009-07-30 17:40:51 +00004997 // The canonical type
4998 QualType CanonType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004999 if (PrevDecl &&
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005000 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00005001 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00005002 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005003 // arguments was referenced but not declared, or we're only
5004 // referencing this specialization as a friend, reuse that
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005005 // declaration node as our own, updating its source location and
5006 // the list of outer template parameters to reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00005007 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00005008 Specialization->setLocation(TemplateNameLoc);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005009 if (TemplateParameterLists.size() > 0) {
5010 Specialization->setTemplateParameterListsInfo(Context,
5011 TemplateParameterLists.size(),
5012 (TemplateParameterList**) TemplateParameterLists.release());
5013 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005014 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00005015 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005016 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00005017 // Build the canonical type that describes the converted template
5018 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00005019 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5020 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00005021 Converted.data(),
5022 Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005023
5024 if (Context.hasSameType(CanonType,
Douglas Gregorb9c66312010-12-23 17:13:55 +00005025 ClassTemplate->getInjectedClassNameSpecialization())) {
5026 // C++ [temp.class.spec]p9b3:
5027 //
5028 // -- The argument list of the specialization shall not be identical
5029 // to the implicit argument list of the primary template.
5030 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Douglas Gregor8d267c52011-09-09 02:06:17 +00005031 << (TUK == TUK_Definition)
5032 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregorb9c66312010-12-23 17:13:55 +00005033 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
5034 ClassTemplate->getIdentifier(),
5035 TemplateNameLoc,
5036 Attr,
5037 TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +00005038 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005039 TemplateParameterLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00005040 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregorb9c66312010-12-23 17:13:55 +00005041 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00005042
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005043 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005044 ClassTemplatePartialSpecializationDecl *PrevPartial
5045 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005046 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005047 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00005048 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00005049 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005050 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005051 KWLoc, TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00005052 TemplateParams,
5053 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005054 Converted.data(),
5055 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00005056 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00005057 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005058 PrevPartial,
5059 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00005060 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005061 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005062 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005063 TemplateParameterLists.size() - 1,
Abramo Bagnara9b934882010-06-12 08:15:14 +00005064 (TemplateParameterList**) TemplateParameterLists.release());
5065 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005066
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005067 if (!PrevPartial)
5068 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005069 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00005070
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005071 // If we are providing an explicit specialization of a member class
Douglas Gregored9c0f92009-10-29 00:04:11 +00005072 // template specialization, make a note of that.
5073 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5074 PrevPartial->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005075
Douglas Gregor031a5882009-06-13 00:26:55 +00005076 // Check that all of the template parameters of the class template
5077 // partial specialization are deducible from the template
5078 // arguments. If not, this class template partial specialization
5079 // will never be used.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005080 SmallVector<bool, 8> DeducibleParams;
Douglas Gregor031a5882009-06-13 00:26:55 +00005081 DeducibleParams.resize(TemplateParams->size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00005083 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00005084 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00005085 unsigned NumNonDeducible = 0;
5086 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
5087 if (!DeducibleParams[I])
5088 ++NumNonDeducible;
5089
5090 if (NumNonDeducible) {
5091 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
5092 << (NumNonDeducible > 1)
5093 << SourceRange(TemplateNameLoc, RAngleLoc);
5094 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5095 if (!DeducibleParams[I]) {
5096 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
5097 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00005098 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005099 diag::note_partial_spec_unused_parameter)
5100 << Param->getDeclName();
5101 else
Mike Stump1eb44332009-09-09 15:08:12 +00005102 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005103 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00005104 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00005105 }
5106 }
5107 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005108 } else {
5109 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005110 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00005111 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005112 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00005113 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005114 KWLoc, TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005115 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005116 Converted.data(),
5117 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00005118 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005119 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005120 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005121 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005122 TemplateParameterLists.size(),
Abramo Bagnara9b934882010-06-12 08:15:14 +00005123 (TemplateParameterList**) TemplateParameterLists.release());
5124 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005125
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005126 if (!PrevDecl)
5127 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00005128
5129 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005130 }
5131
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005132 // C++ [temp.expl.spec]p6:
5133 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005134 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005135 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005136 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005137 // use occurs; no diagnostic is required.
5138 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005139 bool Okay = false;
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005140 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005141 // Is there any previous explicit specialization declaration?
5142 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5143 Okay = true;
5144 break;
5145 }
5146 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005147
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005148 if (!Okay) {
5149 SourceRange Range(TemplateNameLoc, RAngleLoc);
5150 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5151 << Context.getTypeDeclType(Specialization) << Range;
5152
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005153 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005154 diag::note_instantiation_required_here)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005155 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005156 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005157 return true;
5158 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005160
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005161 // If this is not a friend, note that this is an explicit specialization.
5162 if (TUK != TUK_Friend)
5163 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005164
5165 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005166 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00005167 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00005168 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005169 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005170 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00005171 Diag(Def->getLocation(), diag::note_previous_definition);
5172 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00005173 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00005174 }
5175 }
5176
John McCall7f1b9872010-12-18 03:30:47 +00005177 if (Attr)
5178 ProcessDeclAttributeList(S, Specialization, Attr);
5179
Douglas Gregord023aec2011-09-09 20:53:38 +00005180 if (ModulePrivateLoc.isValid())
5181 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
5182 << (isPartialSpecialization? 1 : 0)
5183 << FixItHint::CreateRemoval(ModulePrivateLoc);
5184
Douglas Gregorfc705b82009-02-26 22:19:44 +00005185 // Build the fully-sugared type for this class template
5186 // specialization as the user wrote in the specialization
5187 // itself. This means that we'll pretty-print the type retrieved
5188 // from the specialization's declaration the way that the user
5189 // actually wrote the specialization, rather than formatting the
5190 // name based on the "canonical" representation used to store the
5191 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005192 TypeSourceInfo *WrittenTy
5193 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5194 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005195 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005196 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005197 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005198 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00005199 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00005200
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00005201 // C++ [temp.expl.spec]p9:
5202 // A template explicit specialization is in the scope of the
5203 // namespace in which the template was defined.
5204 //
5205 // We actually implement this paragraph where we set the semantic
5206 // context (in the creation of the ClassTemplateSpecializationDecl),
5207 // but we also maintain the lexical context where the actual
5208 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00005209 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005210
Douglas Gregorcc636682009-02-17 23:15:12 +00005211 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005212 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00005213 Specialization->startDefinition();
5214
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005215 if (TUK == TUK_Friend) {
5216 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5217 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00005218 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005219 /*FIXME:*/KWLoc);
5220 Friend->setAccess(AS_public);
5221 CurContext->addDecl(Friend);
5222 } else {
5223 // Add the specialization into its lexical context, so that it can
5224 // be seen when iterating through the list of declarations in that
5225 // context. However, specializations are not found by name lookup.
5226 CurContext->addDecl(Specialization);
5227 }
John McCalld226f652010-08-21 09:40:31 +00005228 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00005229}
Douglas Gregord57959a2009-03-27 23:10:48 +00005230
John McCalld226f652010-08-21 09:40:31 +00005231Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00005232 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005233 Declarator &D) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005234 return HandleDeclarator(S, D, move(TemplateParameterLists));
Douglas Gregore542c862009-06-23 23:11:28 +00005235}
5236
John McCalld226f652010-08-21 09:40:31 +00005237Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00005238 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005239 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00005240 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005241 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Douglas Gregor52591bf2009-06-24 00:54:41 +00005243 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00005244 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00005245 }
Mike Stump1eb44332009-09-09 15:08:12 +00005246
Douglas Gregor52591bf2009-06-24 00:54:41 +00005247 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00005248
Douglas Gregor45fa5602011-11-07 20:56:01 +00005249 D.setFunctionDefinitionKind(FDK_Definition);
John McCalld226f652010-08-21 09:40:31 +00005250 Decl *DP = HandleDeclarator(ParentScope, D,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005251 move(TemplateParameterLists));
Mike Stump1eb44332009-09-09 15:08:12 +00005252 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00005253 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00005254 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00005255 FunctionTemplate->getTemplatedDecl());
5256 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
5257 return ActOnStartOfFunctionDef(FnBodyScope, Function);
5258 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00005259}
5260
John McCall75042392010-02-11 01:33:53 +00005261/// \brief Strips various properties off an implicit instantiation
5262/// that has just been explicitly specialized.
5263static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00005264 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00005265
5266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5267 FD->setInlineSpecified(false);
5268 }
5269}
5270
Nico Weberd1d512a2012-01-09 19:52:25 +00005271/// \brief Compute the diagnostic location for an explicit instantiation
5272// declaration or definition.
5273static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005274 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Weberd1d512a2012-01-09 19:52:25 +00005275 // Explicit instantiations following a specialization have no effect and
5276 // hence no PointOfInstantiation. In that case, walk decl backwards
5277 // until a valid name loc is found.
5278 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005279 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
5280 Prev = Prev->getPreviousDecl()) {
Nico Weberd1d512a2012-01-09 19:52:25 +00005281 PrevDiagLoc = Prev->getLocation();
5282 }
5283 assert(PrevDiagLoc.isValid() &&
5284 "Explicit instantiation without point of instantiation?");
5285 return PrevDiagLoc;
5286}
5287
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005288/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregor454885e2009-10-15 15:54:05 +00005289/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005290/// for those cases where they are required and determining whether the
Douglas Gregor454885e2009-10-15 15:54:05 +00005291/// new specialization/instantiation will have any effect.
5292///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005293/// \param NewLoc the location of the new explicit specialization or
Douglas Gregor454885e2009-10-15 15:54:05 +00005294/// instantiation.
5295///
5296/// \param NewTSK the kind of the new explicit specialization or instantiation.
5297///
5298/// \param PrevDecl the previous declaration of the entity.
5299///
5300/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5301///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005302/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregor454885e2009-10-15 15:54:05 +00005303/// declaration was instantiated (either implicitly or explicitly).
5304///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005305/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00005306/// specialization or instantiation has no effect and should be ignored.
5307///
5308/// \returns true if there was an error that should prevent the introduction of
5309/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00005310bool
5311Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5312 TemplateSpecializationKind NewTSK,
5313 NamedDecl *PrevDecl,
5314 TemplateSpecializationKind PrevTSK,
5315 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005316 bool &HasNoEffect) {
5317 HasNoEffect = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005318
Douglas Gregor454885e2009-10-15 15:54:05 +00005319 switch (NewTSK) {
5320 case TSK_Undeclared:
5321 case TSK_ImplicitInstantiation:
David Blaikieb219cfc2011-09-23 05:06:16 +00005322 llvm_unreachable("Don't check implicit instantiations here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005323
Douglas Gregor454885e2009-10-15 15:54:05 +00005324 case TSK_ExplicitSpecialization:
5325 switch (PrevTSK) {
5326 case TSK_Undeclared:
5327 case TSK_ExplicitSpecialization:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005328 // Okay, we're just specializing something that is either already
Douglas Gregor454885e2009-10-15 15:54:05 +00005329 // explicitly specialized or has merely been mentioned without any
5330 // instantiation.
5331 return false;
5332
5333 case TSK_ImplicitInstantiation:
5334 if (PrevPointOfInstantiation.isInvalid()) {
5335 // The declaration itself has not actually been instantiated, so it is
5336 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00005337 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00005338 return false;
5339 }
5340 // Fall through
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005341
Douglas Gregor454885e2009-10-15 15:54:05 +00005342 case TSK_ExplicitInstantiationDeclaration:
5343 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005344 assert((PrevTSK == TSK_ImplicitInstantiation ||
5345 PrevPointOfInstantiation.isValid()) &&
Douglas Gregor454885e2009-10-15 15:54:05 +00005346 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005347
Douglas Gregor454885e2009-10-15 15:54:05 +00005348 // C++ [temp.expl.spec]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005349 // If a template, a member template or the member of a class template
Douglas Gregor454885e2009-10-15 15:54:05 +00005350 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005351 // before the first use of that specialization that would cause an
Douglas Gregor454885e2009-10-15 15:54:05 +00005352 // implicit instantiation to take place, in every translation unit in
5353 // which such a use occurs; no diagnostic is required.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005354 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005355 // Is there any previous explicit specialization declaration?
5356 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5357 return false;
5358 }
5359
Douglas Gregor0d035142009-10-27 18:42:08 +00005360 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00005361 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00005362 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00005363 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005364
Douglas Gregor454885e2009-10-15 15:54:05 +00005365 return true;
5366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005367
Douglas Gregor454885e2009-10-15 15:54:05 +00005368 case TSK_ExplicitInstantiationDeclaration:
5369 switch (PrevTSK) {
5370 case TSK_ExplicitInstantiationDeclaration:
5371 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005372 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005373 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005374
Douglas Gregor454885e2009-10-15 15:54:05 +00005375 case TSK_Undeclared:
5376 case TSK_ImplicitInstantiation:
5377 // We're explicitly instantiating something that may have already been
5378 // implicitly instantiated; that's fine.
5379 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005380
Douglas Gregor454885e2009-10-15 15:54:05 +00005381 case TSK_ExplicitSpecialization:
5382 // C++0x [temp.explicit]p4:
5383 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005384 // of a template appears after a declaration of an explicit
Douglas Gregor454885e2009-10-15 15:54:05 +00005385 // specialization for that template, the explicit instantiation has no
5386 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005387 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005388 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005389
Douglas Gregor454885e2009-10-15 15:54:05 +00005390 case TSK_ExplicitInstantiationDefinition:
5391 // C++0x [temp.explicit]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005392 // If an entity is the subject of both an explicit instantiation
5393 // declaration and an explicit instantiation definition in the same
Douglas Gregor454885e2009-10-15 15:54:05 +00005394 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005395 Diag(NewLoc,
Douglas Gregor0d035142009-10-27 18:42:08 +00005396 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberff91d242011-12-23 20:58:04 +00005397
5398 // Explicit instantiations following a specialization have no effect and
5399 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
5400 // until a valid name loc is found.
Nico Weberd1d512a2012-01-09 19:52:25 +00005401 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5402 diag::note_explicit_instantiation_definition_here);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005403 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005404 return false;
5405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005406
Douglas Gregor454885e2009-10-15 15:54:05 +00005407 case TSK_ExplicitInstantiationDefinition:
5408 switch (PrevTSK) {
5409 case TSK_Undeclared:
5410 case TSK_ImplicitInstantiation:
5411 // We're explicitly instantiating something that may have already been
5412 // implicitly instantiated; that's fine.
5413 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005414
Douglas Gregor454885e2009-10-15 15:54:05 +00005415 case TSK_ExplicitSpecialization:
5416 // C++ DR 259, C++0x [temp.explicit]p4:
5417 // For a given set of template parameters, if an explicit
5418 // instantiation of a template appears after a declaration of
5419 // an explicit specialization for that template, the explicit
5420 // instantiation has no effect.
5421 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005422 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00005423 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00005424 // has been explicitly specialized.
Richard Smithebaf0e62011-10-18 20:49:44 +00005425 Diag(NewLoc, getLangOptions().CPlusPlus0x ?
5426 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
5427 diag::ext_explicit_instantiation_after_specialization)
5428 << PrevDecl;
5429 Diag(PrevDecl->getLocation(),
5430 diag::note_previous_template_specialization);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005431 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005432 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005433
Douglas Gregor454885e2009-10-15 15:54:05 +00005434 case TSK_ExplicitInstantiationDeclaration:
5435 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005436 // were previously asked to suppress instantiations. That's fine.
Nico Weberff91d242011-12-23 20:58:04 +00005437
5438 // C++0x [temp.explicit]p4:
5439 // For a given set of template parameters, if an explicit instantiation
5440 // of a template appears after a declaration of an explicit
5441 // specialization for that template, the explicit instantiation has no
5442 // effect.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005443 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberff91d242011-12-23 20:58:04 +00005444 // Is there any previous explicit specialization declaration?
5445 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5446 HasNoEffect = true;
5447 break;
5448 }
5449 }
5450
Douglas Gregor454885e2009-10-15 15:54:05 +00005451 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005452
Douglas Gregor454885e2009-10-15 15:54:05 +00005453 case TSK_ExplicitInstantiationDefinition:
5454 // C++0x [temp.spec]p5:
5455 // For a given template and a given set of template-arguments,
5456 // - an explicit instantiation definition shall appear at most once
5457 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00005458 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00005459 << PrevDecl;
Nico Weberd1d512a2012-01-09 19:52:25 +00005460 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor0d035142009-10-27 18:42:08 +00005461 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005462 HasNoEffect = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005463 return false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005464 }
Douglas Gregor454885e2009-10-15 15:54:05 +00005465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005466
David Blaikieb219cfc2011-09-23 05:06:16 +00005467 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregor454885e2009-10-15 15:54:05 +00005468}
5469
John McCallaf2094e2010-04-08 09:05:18 +00005470/// \brief Perform semantic analysis for the given dependent function
5471/// template specialization. The only possible way to get a dependent
5472/// function template specialization is with a friend declaration,
5473/// like so:
5474///
5475/// template <class T> void foo(T);
5476/// template <class T> class A {
5477/// friend void foo<>(T);
5478/// };
5479///
5480/// There really isn't any useful analysis we can do here, so we
5481/// just store the information.
5482bool
5483Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5484 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5485 LookupResult &Previous) {
5486 // Remove anything from Previous that isn't a function template in
5487 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005488 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00005489 LookupResult::Filter F = Previous.makeFilter();
5490 while (F.hasNext()) {
5491 NamedDecl *D = F.next()->getUnderlyingDecl();
5492 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00005493 !FDLookupContext->InEnclosingNamespaceSetOf(
5494 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00005495 F.erase();
5496 }
5497 F.done();
5498
5499 // Should this be diagnosed here?
5500 if (Previous.empty()) return true;
5501
5502 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5503 ExplicitTemplateArgs);
5504 return false;
5505}
5506
Abramo Bagnarae03db982010-05-20 15:32:11 +00005507/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005508/// specialization.
5509///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005510/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005511/// explicit function template specialization. On successful completion,
5512/// the function declaration \p FD will become a function template
5513/// specialization.
5514///
5515/// \param FD the function declaration, which will be updated to become a
5516/// function template specialization.
5517///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005518/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5519/// if any. Note that this may be valid info even when 0 arguments are
5520/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5521/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005522///
Francois Pichet59e7c562011-07-08 06:21:47 +00005523/// \param Previous the set of declarations that may be specialized by
Abramo Bagnarae03db982010-05-20 15:32:11 +00005524/// this function specialization.
5525bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005526Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
Douglas Gregor67714232011-03-03 02:41:12 +00005527 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00005528 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005529 // The set of function template specializations that could match this
5530 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005531 UnresolvedSet<8> Candidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005532
Sebastian Redl7a126a42010-08-31 00:36:30 +00005533 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00005534 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5535 I != E; ++I) {
5536 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5537 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005538 // Only consider templates found within the same semantic lookup scope as
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005539 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005540 if (!FDLookupContext->InEnclosingNamespaceSetOf(
5541 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005542 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005543
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005544 // C++ [temp.expl.spec]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005545 // A trailing template-argument can be left unspecified in the
5546 // template-id naming an explicit function template specialization
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005547 // provided it can be deduced from the function argument type.
5548 // Perform template argument deduction to determine whether we may be
5549 // specializing this template.
5550 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00005551 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005552 FunctionDecl *Specialization = 0;
5553 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00005554 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005555 FD->getType(),
5556 Specialization,
5557 Info)) {
5558 // FIXME: Template argument deduction failed; record why it failed, so
5559 // that we can provide nifty diagnostics.
5560 (void)TDK;
5561 continue;
5562 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005563
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005564 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00005565 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005566 }
5567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005568
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005569 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00005570 UnresolvedSetIterator Result
5571 = getMostSpecialized(Candidates.begin(), Candidates.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00005572 TPOC_Other, 0, FD->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005573 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005574 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005575 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00005576 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005577 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00005578 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005579 return true;
John McCallc373d482010-01-27 01:50:18 +00005580
5581 // Ignore access information; it doesn't figure into redeclaration checking.
5582 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnaraabfb4052011-03-04 17:20:30 +00005583
5584 FunctionTemplateSpecializationInfo *SpecInfo
5585 = Specialization->getTemplateSpecializationInfo();
5586 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet59e7c562011-07-08 06:21:47 +00005587
5588 // Note: do not overwrite location info if previous template
5589 // specialization kind was explicit.
5590 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
5591 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation)
5592 Specialization->setLocation(FD->getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005593
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005594 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005595 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00005596
5597 // If this is a friend declaration, then we're not really declaring
5598 // an explicit specialization.
5599 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005600
Douglas Gregord5cb8762009-10-07 00:13:32 +00005601 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00005602 if (!isFriend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005603 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00005604 Specialization->getPrimaryTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005605 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005606 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00005607 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005608
5609 // C++ [temp.expl.spec]p6:
5610 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005611 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005612 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005613 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005614 // use occurs; no diagnostic is required.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005615 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00005616 if (!isFriend &&
5617 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00005618 TSK_ExplicitSpecialization,
5619 Specialization,
5620 SpecInfo->getTemplateSpecializationKind(),
5621 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005622 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005623 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00005624
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005625 // Mark the prior declaration as an explicit specialization, so that later
5626 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005627 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00005628 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005629 MarkUnusedFileScopedDecl(Specialization);
5630 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005631
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005632 // Turn the given function declaration into a function template
5633 // specialization, with the template arguments from the previous
5634 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00005635 // Take copies of (semantic and syntactic) template argument lists.
5636 const TemplateArgumentList* TemplArgs = new (Context)
5637 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregor838db382010-02-11 01:19:42 +00005638 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00005639 TemplArgs, /*InsertPos=*/0,
5640 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00005641 ExplicitTemplateArgs);
Douglas Gregore885e182011-05-21 18:53:30 +00005642 FD->setStorageClass(Specialization->getStorageClass());
5643
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005644 // The "previous declaration" for this function template specialization is
5645 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00005646 Previous.clear();
5647 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005648 return false;
5649}
5650
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005651/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005652/// specialization.
5653///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005654/// This routine performs all of the semantic analysis required for an
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005655/// explicit member function specialization. On successful completion,
5656/// the function declaration \p FD will become a member function
5657/// specialization.
5658///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005659/// \param Member the member declaration, which will be updated to become a
5660/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005661///
John McCall68263142009-11-18 22:49:29 +00005662/// \param Previous the set of declarations, one of which may be specialized
5663/// by this function specialization; the set will be modified to contain the
5664/// redeclared member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005665bool
John McCall68263142009-11-18 22:49:29 +00005666Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005667 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00005668
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005669 // Try to find the member we are instantiating.
5670 NamedDecl *Instantiation = 0;
5671 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005672 MemberSpecializationInfo *MSInfo = 0;
5673
John McCall68263142009-11-18 22:49:29 +00005674 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005675 // Nowhere to look anyway.
5676 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005677 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5678 I != E; ++I) {
5679 NamedDecl *D = (*I)->getUnderlyingDecl();
5680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005681 if (Context.hasSameType(Function->getType(), Method->getType())) {
5682 Instantiation = Method;
5683 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005684 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005685 break;
5686 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005687 }
5688 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005689 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005690 VarDecl *PrevVar;
5691 if (Previous.isSingleResult() &&
5692 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005693 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00005694 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005695 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005696 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005697 }
5698 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005699 CXXRecordDecl *PrevRecord;
5700 if (Previous.isSingleResult() &&
5701 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5702 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005703 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005704 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005705 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005706 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005707
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005708 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005709 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005710 // specializations are always out-of-line, the caller will complain about
5711 // this mismatch later.
5712 return false;
5713 }
John McCall77e8b112010-04-13 20:37:33 +00005714
5715 // If this is a friend, just bail out here before we start turning
5716 // things into explicit specializations.
5717 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5718 // Preserve instantiation information.
5719 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5720 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5721 cast<CXXMethodDecl>(InstantiatedFrom),
5722 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5723 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5724 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5725 cast<CXXRecordDecl>(InstantiatedFrom),
5726 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5727 }
5728
5729 Previous.clear();
5730 Previous.addDecl(Instantiation);
5731 return false;
5732 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005733
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005734 // Make sure that this is a specialization of a member.
5735 if (!InstantiatedFrom) {
5736 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5737 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005738 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5739 return true;
5740 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005741
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005742 // C++ [temp.expl.spec]p6:
5743 // If a template, a member template or the member of a class template is
Nico Weberff91d242011-12-23 20:58:04 +00005744 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005745 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005746 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005747 // use occurs; no diagnostic is required.
5748 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00005749
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005750 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00005751 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5752 TSK_ExplicitSpecialization,
5753 Instantiation,
5754 MSInfo->getTemplateSpecializationKind(),
5755 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005756 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005757 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005758
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005759 // Check the scope of this explicit specialization.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005760 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005761 InstantiatedFrom,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005762 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005763 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005764 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00005765
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005766 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00005767 // the original declaration to note that it is an explicit specialization
5768 // (if it was previously an implicit instantiation). This latter step
5769 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005770 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005771 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5772 if (InstantiationFunction->getTemplateSpecializationKind() ==
5773 TSK_ImplicitInstantiation) {
5774 InstantiationFunction->setTemplateSpecializationKind(
5775 TSK_ExplicitSpecialization);
5776 InstantiationFunction->setLocation(Member->getLocation());
5777 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005778
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005779 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5780 cast<CXXMethodDecl>(InstantiatedFrom),
5781 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005782 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005783 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005784 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5785 if (InstantiationVar->getTemplateSpecializationKind() ==
5786 TSK_ImplicitInstantiation) {
5787 InstantiationVar->setTemplateSpecializationKind(
5788 TSK_ExplicitSpecialization);
5789 InstantiationVar->setLocation(Member->getLocation());
5790 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005791
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005792 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5793 cast<VarDecl>(InstantiatedFrom),
5794 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005795 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005796 } else {
5797 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00005798 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5799 if (InstantiationClass->getTemplateSpecializationKind() ==
5800 TSK_ImplicitInstantiation) {
5801 InstantiationClass->setTemplateSpecializationKind(
5802 TSK_ExplicitSpecialization);
5803 InstantiationClass->setLocation(Member->getLocation());
5804 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005805
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005806 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00005807 cast<CXXRecordDecl>(InstantiatedFrom),
5808 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005810
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005811 // Save the caller the trouble of having to figure out which declaration
5812 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00005813 Previous.clear();
5814 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005815 return false;
5816}
5817
Douglas Gregor558c0322009-10-14 23:41:34 +00005818/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00005819///
5820/// \returns true if a serious error occurs, false otherwise.
5821static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00005822 SourceLocation InstLoc,
5823 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005824 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5825 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005826
Douglas Gregor669eed82010-07-13 00:10:04 +00005827 if (CurContext->isRecord()) {
5828 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5829 << D;
5830 return true;
5831 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005832
Richard Smith3e2e91e2011-10-18 02:28:33 +00005833 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005834 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith3e2e91e2011-10-18 02:28:33 +00005835 // template. If the name declared in the explicit instantiation is an
5836 // unqualified name, the explicit instantiation shall appear in the
5837 // namespace where its template is declared or, if that namespace is inline
5838 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregor558c0322009-10-14 23:41:34 +00005839 //
5840 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith3e2e91e2011-10-18 02:28:33 +00005841 if (WasQualifiedName) {
5842 if (CurContext->Encloses(OrigContext))
5843 return false;
5844 } else {
5845 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
5846 return false;
5847 }
5848
5849 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
5850 if (WasQualifiedName)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005851 S.Diag(InstLoc,
5852 S.getLangOptions().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00005853 diag::err_explicit_instantiation_out_of_scope :
5854 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005855 << D << NS;
5856 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005857 S.Diag(InstLoc,
Douglas Gregor2166beb2010-05-11 17:39:34 +00005858 S.getLangOptions().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00005859 diag::err_explicit_instantiation_unqualified_wrong_namespace :
5860 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
5861 << D << NS;
5862 } else
5863 S.Diag(InstLoc,
5864 S.getLangOptions().CPlusPlus0x?
5865 diag::err_explicit_instantiation_must_be_global :
5866 diag::warn_explicit_instantiation_must_be_global_0x)
5867 << D;
Douglas Gregor558c0322009-10-14 23:41:34 +00005868 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005869 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005870}
5871
5872/// \brief Determine whether the given scope specifier has a template-id in it.
5873static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5874 if (!SS.isSet())
5875 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005876
Richard Smith3e2e91e2011-10-18 02:28:33 +00005877 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005878 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00005879 // or a static data member of a class template specialization, the name of
5880 // the class template specialization in the qualified-id for the member
5881 // name shall be a simple-template-id.
5882 //
5883 // C++98 has the same restriction, just worded differently.
5884 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5885 NNS; NNS = NNS->getPrefix())
John McCallf4c73712011-01-19 06:33:43 +00005886 if (const Type *T = NNS->getAsType())
Douglas Gregor558c0322009-10-14 23:41:34 +00005887 if (isa<TemplateSpecializationType>(T))
5888 return true;
5889
5890 return false;
5891}
5892
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005893// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005894DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005895Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005896 SourceLocation ExternLoc,
5897 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005898 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005899 SourceLocation KWLoc,
5900 const CXXScopeSpec &SS,
5901 TemplateTy TemplateD,
5902 SourceLocation TemplateNameLoc,
5903 SourceLocation LAngleLoc,
5904 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005905 SourceLocation RAngleLoc,
5906 AttributeList *Attr) {
5907 // Find the class template we're specializing
5908 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005909 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005910 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5911
5912 // Check that the specialization uses the same tag kind as the
5913 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005914 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5915 assert(Kind != TTK_Enum &&
5916 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005917 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00005918 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005919 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005920 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005921 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005922 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005923 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005924 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005925 diag::note_previous_use);
5926 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5927 }
5928
Douglas Gregor558c0322009-10-14 23:41:34 +00005929 // C++0x [temp.explicit]p2:
5930 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005931 // definition and an explicit instantiation declaration. An explicit
5932 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005933 TemplateSpecializationKind TSK
5934 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5935 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005936
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005937 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005938 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005939 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005940
5941 // Check that the template argument list is well-formed for this
5942 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005943 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005944 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5945 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005946 return true;
5947
Douglas Gregor910f8002010-11-07 23:05:16 +00005948 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005949 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005950
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005951 // Find the class template specialization declaration that
5952 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005953 void *InsertPos = 0;
5954 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005955 = ClassTemplate->findSpecialization(Converted.data(),
5956 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005957
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005958 TemplateSpecializationKind PrevDecl_TSK
5959 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5960
Douglas Gregord5cb8762009-10-07 00:13:32 +00005961 // C++0x [temp.explicit]p2:
5962 // [...] An explicit instantiation shall appear in an enclosing
5963 // namespace of its template. [...]
5964 //
5965 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005966 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5967 SS.isSet()))
5968 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005969
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005970 ClassTemplateSpecializationDecl *Specialization = 0;
5971
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005972 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005973 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005974 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005975 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005976 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005977 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005978 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005979
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005980 // Even though HasNoEffect == true means that this explicit instantiation
5981 // has no effect on semantics, we go on to put its syntax in the AST.
5982
5983 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5984 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005985 // Since the only prior class template specialization with these
5986 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005987 // declaration node as our own, updating the source location
5988 // for the template name to reflect our new declaration.
5989 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005990 Specialization = PrevDecl;
5991 Specialization->setLocation(TemplateNameLoc);
5992 PrevDecl = 0;
5993 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005994 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005995
Douglas Gregor52604ab2009-09-11 21:19:12 +00005996 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005997 // Create a new class template specialization declaration node for
5998 // this explicit specialization.
5999 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00006000 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006001 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00006002 KWLoc, TemplateNameLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006003 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00006004 Converted.data(),
6005 Converted.size(),
6006 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00006007 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006008
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00006009 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006010 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00006011 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006012 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006013 }
6014
6015 // Build the fully-sugared type for this explicit instantiation as
6016 // the user wrote in the explicit instantiation itself. This means
6017 // that we'll pretty-print the type retrieved from the
6018 // specialization's declaration the way that the user actually wrote
6019 // the explicit instantiation, rather than formatting the name based
6020 // on the "canonical" representation used to store the template
6021 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00006022 TypeSourceInfo *WrittenTy
6023 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6024 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006025 Context.getTypeDeclType(Specialization));
6026 Specialization->setTypeAsWritten(WrittenTy);
6027 TemplateArgsIn.release();
6028
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006029 // Set source locations for keywords.
6030 Specialization->setExternLoc(ExternLoc);
6031 Specialization->setTemplateKeywordLoc(TemplateLoc);
6032
Rafael Espindola0257b7f2012-01-03 06:04:21 +00006033 if (Attr)
6034 ProcessDeclAttributeList(S, Specialization, Attr);
6035
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006036 // Add the explicit instantiation into its lexical context. However,
6037 // since explicit instantiations are never found by name lookup, we
6038 // just put it into the declaration context directly.
6039 Specialization->setLexicalDeclContext(CurContext);
6040 CurContext->addDecl(Specialization);
6041
6042 // Syntax is now OK, so return if it has no other effect on semantics.
6043 if (HasNoEffect) {
6044 // Set the template specialization kind.
6045 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00006046 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00006047 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006048
6049 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006050 // A definition of a class template or class member template
6051 // shall be in scope at the point of the explicit instantiation of
6052 // the class template or class member template.
6053 //
6054 // This check comes when we actually try to perform the
6055 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006056 ClassTemplateSpecializationDecl *Def
6057 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00006058 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006059 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00006060 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006061 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006062 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006063 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
6064 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006065
Douglas Gregor0d035142009-10-27 18:42:08 +00006066 // Instantiate the members of this class template specialization.
6067 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00006068 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006069 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00006070 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
6071
6072 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
6073 // TSK_ExplicitInstantiationDefinition
6074 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
6075 TSK == TSK_ExplicitInstantiationDefinition)
6076 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006077
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006078 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006079 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006080
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006081 // Set the template specialization kind.
6082 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00006083 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006084}
6085
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006086// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00006087DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00006088Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00006089 SourceLocation ExternLoc,
6090 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006091 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006092 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006093 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006094 IdentifierInfo *Name,
6095 SourceLocation NameLoc,
6096 AttributeList *Attr) {
6097
Douglas Gregor402abb52009-05-28 23:31:59 +00006098 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00006099 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00006100 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00006101 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregore7612302011-09-09 19:05:14 +00006102 /*ModulePrivateLoc=*/SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +00006103 MultiTemplateParamsArg(*this, 0, 0),
Richard Smithbdad7a22012-01-10 01:33:14 +00006104 Owned, IsDependent, SourceLocation(), false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006105 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00006106 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
6107
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006108 if (!TagD)
6109 return true;
6110
John McCalld226f652010-08-21 09:40:31 +00006111 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006112 if (Tag->isEnum()) {
6113 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
6114 << Context.getTypeDeclType(Tag);
6115 return true;
6116 }
6117
Douglas Gregord0c87372009-05-27 17:30:49 +00006118 if (Tag->isInvalidDecl())
6119 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006120
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006121 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
6122 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
6123 if (!Pattern) {
6124 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
6125 << Context.getTypeDeclType(Record);
6126 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
6127 return true;
6128 }
6129
Douglas Gregor558c0322009-10-14 23:41:34 +00006130 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006131 // If the explicit instantiation is for a class or member class, the
6132 // elaborated-type-specifier in the declaration shall include a
Douglas Gregor558c0322009-10-14 23:41:34 +00006133 // simple-template-id.
6134 //
6135 // C++98 has the same restriction, just worded differently.
6136 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00006137 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006138 << Record << SS.getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006139
Douglas Gregor558c0322009-10-14 23:41:34 +00006140 // C++0x [temp.explicit]p2:
6141 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006142 // definition and an explicit instantiation declaration. An explicit
Douglas Gregor558c0322009-10-14 23:41:34 +00006143 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00006144 TemplateSpecializationKind TSK
6145 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6146 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006147
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006148 // C++0x [temp.explicit]p2:
6149 // [...] An explicit instantiation shall appear in an enclosing
6150 // namespace of its template. [...]
6151 //
6152 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00006153 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006154
Douglas Gregor454885e2009-10-15 15:54:05 +00006155 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006156 CXXRecordDecl *PrevDecl
Douglas Gregoref96ee02012-01-14 16:38:05 +00006157 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor952b0172010-02-11 01:04:33 +00006158 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00006159 PrevDecl = Record;
6160 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00006161 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006162 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00006163 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006164 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00006165 PrevDecl,
6166 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006167 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006168 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006169 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006170 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00006171 return TagD;
6172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006173
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006174 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00006175 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006176 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006177 // C++ [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006178 // A definition of a member class of a class template shall be in scope
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006179 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006180 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00006181 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006182 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00006183 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6184 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006185 Diag(Pattern->getLocation(), diag::note_forward_declaration)
6186 << Pattern;
6187 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00006188 } else {
6189 if (InstantiateClass(NameLoc, Record, Def,
6190 getTemplateInstantiationArgs(Record),
6191 TSK))
6192 return true;
6193
Douglas Gregor952b0172010-02-11 01:04:33 +00006194 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00006195 if (!RecordDef)
6196 return true;
6197 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006198 }
6199
Douglas Gregor0d035142009-10-27 18:42:08 +00006200 // Instantiate all of the members of the class.
6201 InstantiateClassMembers(NameLoc, RecordDef,
6202 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006203
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006204 if (TSK == TSK_ExplicitInstantiationDefinition)
6205 MarkVTableUsed(NameLoc, RecordDef, true);
6206
Mike Stump390b4cc2009-05-16 07:39:55 +00006207 // FIXME: We don't have any representation for explicit instantiations of
6208 // member classes. Such a representation is not needed for compilation, but it
6209 // should be available for clients that want to see all of the declarations in
6210 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006211 return TagD;
6212}
6213
John McCallf312b1e2010-08-26 23:41:50 +00006214DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6215 SourceLocation ExternLoc,
6216 SourceLocation TemplateLoc,
6217 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006218 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00006219 // TODO: check if/when DNInfo should replace Name.
6220 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6221 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006222 if (!Name) {
6223 if (!D.isInvalidType())
6224 Diag(D.getDeclSpec().getSourceRange().getBegin(),
6225 diag::err_explicit_instantiation_requires_name)
6226 << D.getDeclSpec().getSourceRange()
6227 << D.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006228
Douglas Gregord5a423b2009-09-25 18:43:00 +00006229 return true;
6230 }
6231
6232 // The scope passed in may not be a decl scope. Zip up the scope tree until
6233 // we find one that is.
6234 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6235 (S->getFlags() & Scope::TemplateParamScope) != 0)
6236 S = S->getParent();
6237
6238 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00006239 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6240 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006241 if (R.isNull())
6242 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006243
Douglas Gregore885e182011-05-21 18:53:30 +00006244 // C++ [dcl.stc]p1:
6245 // A storage-class-specifier shall not be specified in [...] an explicit
6246 // instantiation (14.7.2) directive.
Douglas Gregord5a423b2009-09-25 18:43:00 +00006247 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006248 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6249 << Name;
6250 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00006251 } else if (D.getDeclSpec().getStorageClassSpec()
6252 != DeclSpec::SCS_unspecified) {
6253 // Complain about then remove the storage class specifier.
6254 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6255 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6256
6257 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006258 }
6259
Douglas Gregor663b5a02009-10-14 20:14:33 +00006260 // C++0x [temp.explicit]p1:
6261 // [...] An explicit instantiation of a function template shall not use the
6262 // inline or constexpr specifiers.
6263 // Presumably, this also applies to member functions of class templates as
6264 // well.
Richard Smith2dc7ece2011-10-18 03:44:03 +00006265 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006266 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2dc7ece2011-10-18 03:44:03 +00006267 getLangOptions().CPlusPlus0x ?
6268 diag::err_explicit_instantiation_inline :
6269 diag::warn_explicit_instantiation_inline_0x)
Richard Smithfe6f6482011-10-14 19:58:02 +00006270 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6271 if (D.getDeclSpec().isConstexprSpecified())
6272 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
6273 // not already specified.
6274 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6275 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006276
Douglas Gregor558c0322009-10-14 23:41:34 +00006277 // C++0x [temp.explicit]p2:
6278 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006279 // definition and an explicit instantiation declaration. An explicit
6280 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00006281 TemplateSpecializationKind TSK
6282 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6283 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006284
Abramo Bagnara25777432010-08-11 22:01:17 +00006285 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00006286 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006287
6288 if (!R->isFunctionType()) {
6289 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006290 // A [...] static data member of a class template can be explicitly
6291 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006292 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00006293 if (Previous.isAmbiguous())
6294 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006295
John McCall1bcee0a2009-12-02 08:25:40 +00006296 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006297 if (!Prev || !Prev->isStaticDataMember()) {
6298 // We expect to see a data data member here.
6299 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6300 << Name;
6301 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6302 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00006303 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00006304 return true;
6305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006306
Douglas Gregord5a423b2009-09-25 18:43:00 +00006307 if (!Prev->getInstantiatedFromStaticDataMember()) {
6308 // FIXME: Check for explicit specialization?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006309 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006310 diag::err_explicit_instantiation_data_member_not_instantiated)
6311 << Prev;
6312 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6313 // FIXME: Can we provide a note showing where this was declared?
6314 return true;
6315 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006316
Douglas Gregor558c0322009-10-14 23:41:34 +00006317 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006318 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006319 // or a static data member of a class template specialization, the name of
6320 // the class template specialization in the qualified-id for the member
6321 // name shall be a simple-template-id.
6322 //
6323 // C++98 has the same restriction, just worded differently.
6324 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006325 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006326 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006327 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006328
Douglas Gregor558c0322009-10-14 23:41:34 +00006329 // Check the scope of this explicit instantiation.
6330 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006331
Douglas Gregor454885e2009-10-15 15:54:05 +00006332 // Verify that it is okay to explicitly instantiate here.
6333 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6334 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006335 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006336 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00006337 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006338 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006339 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006340 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006341 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006342 return (Decl*) 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006343
Douglas Gregord5a423b2009-09-25 18:43:00 +00006344 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006345 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006346 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006347 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006348
Douglas Gregord5a423b2009-09-25 18:43:00 +00006349 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00006350 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006351 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006352
6353 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00006354 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00006355 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00006356 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006357 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6358 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00006359 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6360 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00006361 ASTTemplateArgsPtr TemplateArgsPtr(*this,
6362 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00006363 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00006364 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00006365 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00006366 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00006367 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006368
Douglas Gregord5a423b2009-09-25 18:43:00 +00006369 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006370 // A [...] function [...] can be explicitly instantiated from its template.
6371 // A member function [...] of a class template can be explicitly
6372 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006373 // template.
John McCallc373d482010-01-27 01:50:18 +00006374 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006375 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6376 P != PEnd; ++P) {
6377 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00006378 if (!HasExplicitTemplateArgs) {
6379 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6380 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6381 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00006382
John McCallc373d482010-01-27 01:50:18 +00006383 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00006384 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6385 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00006386 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00006387 }
6388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006389
Douglas Gregord5a423b2009-09-25 18:43:00 +00006390 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6391 if (!FunTmpl)
6392 continue;
6393
John McCall5769d612010-02-08 23:07:23 +00006394 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006395 FunctionDecl *Specialization = 0;
6396 if (TemplateDeductionResult TDK
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006397 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00006398 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006399 R, Specialization, Info)) {
6400 // FIXME: Keep track of almost-matches?
6401 (void)TDK;
6402 continue;
6403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006404
John McCallc373d482010-01-27 01:50:18 +00006405 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006407
Douglas Gregord5a423b2009-09-25 18:43:00 +00006408 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00006409 UnresolvedSetIterator Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006410 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006411 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006412 PDiag(diag::err_explicit_instantiation_not_known) << Name,
6413 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6414 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00006415
John McCallc373d482010-01-27 01:50:18 +00006416 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00006417 return true;
John McCallc373d482010-01-27 01:50:18 +00006418
6419 // Ignore access control bits, we don't need them for redeclaration checking.
6420 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006421
Douglas Gregor0a897e32009-10-15 17:21:20 +00006422 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006423 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006424 diag::err_explicit_instantiation_member_function_not_instantiated)
6425 << Specialization
6426 << (Specialization->getTemplateSpecializationKind() ==
6427 TSK_ExplicitSpecialization);
6428 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6429 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006430 }
6431
Douglas Gregoref96ee02012-01-14 16:38:05 +00006432 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor583f33b2009-10-15 18:07:02 +00006433 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6434 PrevDecl = Specialization;
6435
Douglas Gregor0a897e32009-10-15 17:21:20 +00006436 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006437 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006438 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006439 PrevDecl,
6440 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor0a897e32009-10-15 17:21:20 +00006441 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006442 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00006443 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006444
Douglas Gregor0a897e32009-10-15 17:21:20 +00006445 // FIXME: We may still want to build some representation of this
6446 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006447 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006448 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00006449 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00006450
6451 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola256fc4d2012-01-04 05:40:59 +00006452 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
6453 if (Attr)
6454 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006455
Douglas Gregor0a897e32009-10-15 17:21:20 +00006456 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006457 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006458
Douglas Gregor558c0322009-10-14 23:41:34 +00006459 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006460 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006461 // or a static data member of a class template specialization, the name of
6462 // the class template specialization in the qualified-id for the member
6463 // name shall be a simple-template-id.
6464 //
6465 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006466 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006467 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006468 D.getCXXScopeSpec().isSet() &&
Douglas Gregor558c0322009-10-14 23:41:34 +00006469 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006470 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006471 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006472 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006473
Douglas Gregor558c0322009-10-14 23:41:34 +00006474 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006475 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregor558c0322009-10-14 23:41:34 +00006476 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006477 D.getIdentifierLoc(),
Douglas Gregor558c0322009-10-14 23:41:34 +00006478 D.getCXXScopeSpec().isSet());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006479
Douglas Gregord5a423b2009-09-25 18:43:00 +00006480 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00006481 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006482}
6483
John McCallf312b1e2010-08-26 23:41:50 +00006484TypeResult
John McCallc4e70192009-09-11 04:59:25 +00006485Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6486 const CXXScopeSpec &SS, IdentifierInfo *Name,
6487 SourceLocation TagLoc, SourceLocation NameLoc) {
6488 // This has to hold, because SS is expected to be defined.
6489 assert(Name && "Expected a name in a dependent tag");
6490
6491 NestedNameSpecifier *NNS
6492 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6493 if (!NNS)
6494 return true;
6495
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006496 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00006497
Douglas Gregor48c89f42010-04-24 16:38:41 +00006498 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6499 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006500 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00006501 return true;
6502 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006503
Douglas Gregor059101f2011-03-02 00:47:37 +00006504 // Create the resulting type.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006505 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor059101f2011-03-02 00:47:37 +00006506 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6507
6508 // Create type-source location information for this type.
6509 TypeLocBuilder TLB;
6510 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
6511 TL.setKeywordLoc(TagLoc);
6512 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6513 TL.setNameLoc(NameLoc);
6514 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCallc4e70192009-09-11 04:59:25 +00006515}
6516
John McCallf312b1e2010-08-26 23:41:50 +00006517TypeResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006518Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6519 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregor1a15dae2010-06-16 22:31:08 +00006520 SourceLocation IdLoc) {
Douglas Gregore29425b2011-02-28 22:42:13 +00006521 if (SS.isInvalid())
Douglas Gregord57959a2009-03-27 23:10:48 +00006522 return true;
Douglas Gregore29425b2011-02-28 22:42:13 +00006523
Richard Smithebaf0e62011-10-18 20:49:44 +00006524 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6525 Diag(TypenameLoc,
6526 getLangOptions().CPlusPlus0x ?
6527 diag::warn_cxx98_compat_typename_outside_of_template :
6528 diag::ext_typename_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006529 << FixItHint::CreateRemoval(TypenameLoc);
6530
Douglas Gregor2494dd02011-03-01 01:34:45 +00006531 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor9e876872011-03-01 18:12:44 +00006532 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6533 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00006534 if (T.isNull())
6535 return true;
John McCall63b43852010-04-29 23:50:39 +00006536
6537 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6538 if (isa<DependentNameType>(T)) {
6539 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00006540 TL.setKeywordLoc(TypenameLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00006541 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006542 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006543 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006544 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00006545 TL.setKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00006546 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006547 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006549
John McCallb3d87482010-08-24 05:47:05 +00006550 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00006551}
6552
John McCallf312b1e2010-08-26 23:41:50 +00006553TypeResult
Douglas Gregora02411e2011-02-27 22:46:49 +00006554Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6555 const CXXScopeSpec &SS,
6556 SourceLocation TemplateLoc,
6557 TemplateTy TemplateIn,
6558 SourceLocation TemplateNameLoc,
6559 SourceLocation LAngleLoc,
6560 ASTTemplateArgsPtr TemplateArgsIn,
6561 SourceLocation RAngleLoc) {
Richard Smithebaf0e62011-10-18 20:49:44 +00006562 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6563 Diag(TypenameLoc,
6564 getLangOptions().CPlusPlus0x ?
6565 diag::warn_cxx98_compat_typename_outside_of_template :
6566 diag::ext_typename_outside_of_template)
6567 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006568
6569 // Translate the parser's template argument list in our AST format.
6570 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6571 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6572
6573 TemplateName Template = TemplateIn.get();
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006574 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6575 // Construct a dependent template specialization type.
6576 assert(DTN && "dependent template has non-dependent name?");
6577 assert(DTN->getQualifier()
6578 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
6579 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
6580 DTN->getQualifier(),
6581 DTN->getIdentifier(),
6582 TemplateArgs);
Douglas Gregora02411e2011-02-27 22:46:49 +00006583
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006584 // Create source-location information for this type.
John McCall4e449832010-05-28 23:32:21 +00006585 TypeLocBuilder Builder;
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006586 DependentTemplateSpecializationTypeLoc SpecTL
6587 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Douglas Gregora02411e2011-02-27 22:46:49 +00006588 SpecTL.setLAngleLoc(LAngleLoc);
6589 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006590 SpecTL.setKeywordLoc(TypenameLoc);
Douglas Gregor94fdffa2011-03-01 20:11:18 +00006591 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006592 SpecTL.setNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006593 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6594 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006595 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor6946baf2009-09-02 13:05:45 +00006596 }
Douglas Gregora02411e2011-02-27 22:46:49 +00006597
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006598 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
6599 if (T.isNull())
6600 return true;
Douglas Gregora02411e2011-02-27 22:46:49 +00006601
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006602 // Provide source-location information for the template specialization
6603 // type.
Douglas Gregora02411e2011-02-27 22:46:49 +00006604 TypeLocBuilder Builder;
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006605 TemplateSpecializationTypeLoc SpecTL
6606 = Builder.push<TemplateSpecializationTypeLoc>(T);
6607
6608 // FIXME: No place to set the location of the 'template' keyword!
Douglas Gregora02411e2011-02-27 22:46:49 +00006609 SpecTL.setLAngleLoc(LAngleLoc);
6610 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006611 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006612 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6613 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
6614
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006615 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
6616 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
6617 TL.setKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00006618 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6619
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006620 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
6621 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00006622}
6623
Douglas Gregora02411e2011-02-27 22:46:49 +00006624
Douglas Gregord57959a2009-03-27 23:10:48 +00006625/// \brief Build the type that describes a C++ typename specifier,
6626/// e.g., "typename T::type".
6627QualType
Douglas Gregore29425b2011-02-28 22:42:13 +00006628Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
6629 SourceLocation KeywordLoc,
6630 NestedNameSpecifierLoc QualifierLoc,
6631 const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006632 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00006633 CXXScopeSpec SS;
Douglas Gregore29425b2011-02-28 22:42:13 +00006634 SS.Adopt(QualifierLoc);
Douglas Gregord57959a2009-03-27 23:10:48 +00006635
John McCall77bb1aa2010-05-01 00:40:08 +00006636 DeclContext *Ctx = computeDeclContext(SS);
6637 if (!Ctx) {
6638 // If the nested-name-specifier is dependent and couldn't be
6639 // resolved to a type, build a typename type.
Douglas Gregore29425b2011-02-28 22:42:13 +00006640 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
6641 return Context.getDependentNameType(Keyword,
6642 QualifierLoc.getNestedNameSpecifier(),
6643 &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00006644 }
Douglas Gregord57959a2009-03-27 23:10:48 +00006645
John McCall77bb1aa2010-05-01 00:40:08 +00006646 // If the nested-name-specifier refers to the current instantiation,
6647 // the "typename" keyword itself is superfluous. In C++03, the
6648 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
6649 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00006650 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00006651
John McCall77bb1aa2010-05-01 00:40:08 +00006652 if (RequireCompleteDeclContext(SS, Ctx))
6653 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00006654
6655 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006656 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00006657 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00006658 unsigned DiagID = 0;
6659 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006660 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00006661 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00006662 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00006663 break;
Douglas Gregord9545042010-12-09 00:06:27 +00006664
6665 case LookupResult::FoundUnresolvedValue: {
6666 // We found a using declaration that is a value. Most likely, the using
6667 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregore29425b2011-02-28 22:42:13 +00006668 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregord9545042010-12-09 00:06:27 +00006669 IILoc);
6670 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
6671 << Name << Ctx << FullRange;
6672 if (UnresolvedUsingValueDecl *Using
6673 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregordc355712011-02-25 00:36:19 +00006674 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregord9545042010-12-09 00:06:27 +00006675 Diag(Loc, diag::note_using_value_decl_missing_typename)
6676 << FixItHint::CreateInsertion(Loc, "typename ");
6677 }
6678 }
6679 // Fall through to create a dependent typename type, from which we can recover
6680 // better.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006681
Douglas Gregor7d3f5762010-01-15 01:44:47 +00006682 case LookupResult::NotFoundInCurrentInstantiation:
6683 // Okay, it's a member of an unknown instantiation.
Douglas Gregore29425b2011-02-28 22:42:13 +00006684 return Context.getDependentNameType(Keyword,
6685 QualifierLoc.getNestedNameSpecifier(),
6686 &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00006687
6688 case LookupResult::Found:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006689 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006690 // We found a type. Build an ElaboratedType, since the
6691 // typename-specifier was just sugar.
Douglas Gregore29425b2011-02-28 22:42:13 +00006692 return Context.getElaboratedType(ETK_Typename,
6693 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006694 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00006695 }
6696
6697 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00006698 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00006699 break;
6700
6701 case LookupResult::FoundOverloaded:
6702 DiagID = diag::err_typename_nested_not_type;
6703 Referenced = *Result.begin();
6704 break;
6705
John McCall6e247262009-10-10 05:48:19 +00006706 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00006707 return QualType();
6708 }
6709
6710 // If we get here, it's because name lookup did not find a
6711 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore29425b2011-02-28 22:42:13 +00006712 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006713 IILoc);
6714 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00006715 if (Referenced)
6716 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6717 << Name;
6718 return QualType();
6719}
Douglas Gregor4a959d82009-08-06 16:20:37 +00006720
6721namespace {
6722 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00006723 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00006724 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00006725 SourceLocation Loc;
6726 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00006727
Douglas Gregor4a959d82009-08-06 16:20:37 +00006728 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00006729 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006730
Mike Stump1eb44332009-09-09 15:08:12 +00006731 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006732 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00006733 DeclarationName Entity)
6734 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00006735 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00006736
6737 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00006738 /// transformed.
6739 ///
6740 /// For the purposes of type reconstruction, a type has already been
6741 /// transformed if it is NULL or if it is not dependent.
6742 bool AlreadyTransformed(QualType T) {
6743 return T.isNull() || !T->isDependentType();
6744 }
Mike Stump1eb44332009-09-09 15:08:12 +00006745
6746 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00006747 /// rebuilt.
6748 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00006749
Douglas Gregor4a959d82009-08-06 16:20:37 +00006750 /// \brief Returns the name of the entity whose type is being rebuilt.
6751 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00006752
Douglas Gregor972e6ce2009-10-27 06:26:26 +00006753 /// \brief Sets the "base" location and entity when that
6754 /// information is known based on another transformation.
6755 void setBase(SourceLocation Loc, DeclarationName Entity) {
6756 this->Loc = Loc;
6757 this->Entity = Entity;
6758 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00006759 };
6760}
6761
Douglas Gregor4a959d82009-08-06 16:20:37 +00006762/// \brief Rebuilds a type within the context of the current instantiation.
6763///
Mike Stump1eb44332009-09-09 15:08:12 +00006764/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00006765/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00006766/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00006767/// partial specialization thereof). This routine will rebuild that type now
6768/// that we have entered the declarator's scope, which may produce different
6769/// canonical types, e.g.,
6770///
6771/// \code
6772/// template<typename T>
6773/// struct X {
6774/// typedef T* pointer;
6775/// pointer data();
6776/// };
6777///
6778/// template<typename T>
6779/// typename X<T>::pointer X<T>::data() { ... }
6780/// \endcode
6781///
Douglas Gregor4714c122010-03-31 17:34:00 +00006782/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006783/// since we do not know that we can look into X<T> when we parsed the type.
6784/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006785/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00006786/// as the canonical type of T*, allowing the return types of the out-of-line
6787/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00006788TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6789 SourceLocation Loc,
6790 DeclarationName Name) {
6791 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00006792 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00006793
Douglas Gregor4a959d82009-08-06 16:20:37 +00006794 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6795 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00006796}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006797
John McCall60d7b3a2010-08-24 06:29:42 +00006798ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00006799 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6800 DeclarationName());
6801 return Rebuilder.TransformExpr(E);
6802}
6803
John McCall63b43852010-04-29 23:50:39 +00006804bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor7e384942011-02-25 16:07:42 +00006805 if (SS.isInvalid())
6806 return true;
John McCall31f17ec2010-04-27 00:57:59 +00006807
Douglas Gregor7e384942011-02-25 16:07:42 +00006808 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall31f17ec2010-04-27 00:57:59 +00006809 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6810 DeclarationName());
Douglas Gregor7e384942011-02-25 16:07:42 +00006811 NestedNameSpecifierLoc Rebuilt
6812 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
6813 if (!Rebuilt)
6814 return true;
John McCall63b43852010-04-29 23:50:39 +00006815
Douglas Gregor7e384942011-02-25 16:07:42 +00006816 SS.Adopt(Rebuilt);
John McCall63b43852010-04-29 23:50:39 +00006817 return false;
John McCall31f17ec2010-04-27 00:57:59 +00006818}
6819
Douglas Gregor20606502011-10-14 15:31:12 +00006820/// \brief Rebuild the template parameters now that we know we're in a current
6821/// instantiation.
6822bool Sema::RebuildTemplateParamsInCurrentInstantiation(
6823 TemplateParameterList *Params) {
6824 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
6825 Decl *Param = Params->getParam(I);
6826
6827 // There is nothing to rebuild in a type parameter.
6828 if (isa<TemplateTypeParmDecl>(Param))
6829 continue;
6830
6831 // Rebuild the template parameter list of a template template parameter.
6832 if (TemplateTemplateParmDecl *TTP
6833 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
6834 if (RebuildTemplateParamsInCurrentInstantiation(
6835 TTP->getTemplateParameters()))
6836 return true;
6837
6838 continue;
6839 }
6840
6841 // Rebuild the type of a non-type template parameter.
6842 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
6843 TypeSourceInfo *NewTSI
6844 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
6845 NTTP->getLocation(),
6846 NTTP->getDeclName());
6847 if (!NewTSI)
6848 return true;
6849
6850 if (NewTSI != NTTP->getTypeSourceInfo()) {
6851 NTTP->setTypeSourceInfo(NewTSI);
6852 NTTP->setType(NewTSI->getType());
6853 }
6854 }
6855
6856 return false;
6857}
6858
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006859/// \brief Produces a formatted string that describes the binding of
6860/// template parameters to template arguments.
6861std::string
6862Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6863 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00006864 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006865}
6866
6867std::string
6868Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6869 const TemplateArgument *Args,
6870 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006871 llvm::SmallString<128> Str;
6872 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006873
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006874 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006875 return std::string();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006876
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006877 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006878 if (I >= NumArgs)
6879 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006880
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006881 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006882 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006883 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00006884 Out << ", ";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006885
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006886 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006887 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006888 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006889 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006890 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006891
Douglas Gregor87dd6972010-12-20 16:52:59 +00006892 Out << " = ";
Douglas Gregor8987b232011-09-27 23:30:47 +00006893 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006894 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00006895
6896 Out << ']';
6897 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006898}
Francois Pichet8387e2a2011-04-22 22:18:13 +00006899
6900void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
6901 if (!FD)
6902 return;
6903 FD->setLateTemplateParsed(Flag);
6904}
6905
6906bool Sema::IsInsideALocalClassWithinATemplateFunction() {
6907 DeclContext *DC = CurContext;
6908
6909 while (DC) {
6910 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
6911 const FunctionDecl *FD = RD->isLocalClass();
6912 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
6913 } else if (DC->isTranslationUnit() || DC->isNamespace())
6914 return false;
6915
6916 DC = DC->getParent();
6917 }
6918 return false;
6919}