blob: 71677fc15721521197bbaada9057bfbc64e4b20e [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"
Benjamin Kramer013b3662012-01-30 16:17:39 +000029#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000030#include "llvm/ADT/SmallString.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000032using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000033using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000034
John McCall78b81052010-11-10 02:40:36 +000035// Exported for use by Parser.
36SourceRange
37clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
38 unsigned N) {
39 if (!N) return SourceRange();
40 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
41}
42
Douglas Gregor2dd078a2009-09-02 22:59:36 +000043/// \brief Determine whether the declaration found is acceptable as the name
44/// of a template and, if so, return that template declaration. Otherwise,
45/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000046static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000047 NamedDecl *Orig,
48 bool AllowFunctionTemplates) {
John McCallad00b772010-06-16 08:42:20 +000049 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000051 if (isa<TemplateDecl>(D)) {
52 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
53 return 0;
54
John McCallad00b772010-06-16 08:42:20 +000055 return Orig;
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000056 }
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor2dd078a2009-09-02 22:59:36 +000058 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
59 // C++ [temp.local]p1:
60 // Like normal (non-template) classes, class templates have an
61 // injected-class-name (Clause 9). The injected-class-name
62 // can be used with or without a template-argument-list. When
63 // it is used without a template-argument-list, it is
64 // equivalent to the injected-class-name followed by the
65 // template-parameters of the class template enclosed in
66 // <>. When it is used with a template-argument-list, it
67 // refers to the specified class template specialization,
68 // which could be the current specialization or another
69 // specialization.
70 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000071 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000072 if (Record->getDescribedClassTemplate())
73 return Record->getDescribedClassTemplate();
74
75 if (ClassTemplateSpecializationDecl *Spec
76 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
77 return Spec->getSpecializedTemplate();
78 }
Mike Stump1eb44332009-09-09 15:08:12 +000079
Douglas Gregor2dd078a2009-09-02 22:59:36 +000080 return 0;
81 }
Mike Stump1eb44332009-09-09 15:08:12 +000082
Douglas Gregor2dd078a2009-09-02 22:59:36 +000083 return 0;
84}
85
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000086void Sema::FilterAcceptableTemplateNames(LookupResult &R,
87 bool AllowFunctionTemplates) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000088 // The set of class templates we've already seen.
89 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000090 LookupResult::Filter filter = R.makeFilter();
91 while (filter.hasNext()) {
92 NamedDecl *Orig = filter.next();
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +000093 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
94 AllowFunctionTemplates);
John McCallf7a1a742009-11-24 19:00:30 +000095 if (!Repl)
96 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000097 else if (Repl != Orig) {
98
99 // C++ [temp.local]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000100 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000101 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000102 // one base class). If all of the injected-class-names that are found
103 // refer to specializations of the same class template, and if the name
Richard Smith3e4c6c42011-05-05 21:57:07 +0000104 // is used as a template-name, the reference refers to the class
105 // template itself and not a specialization thereof, and is not
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000106 // ambiguous.
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000107 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
108 if (!ClassTemplates.insert(ClassTmpl)) {
109 filter.erase();
110 continue;
111 }
John McCall8ba66912010-08-13 07:02:08 +0000112
113 // FIXME: we promote access to public here as a workaround to
114 // the fact that LookupResult doesn't let us remember that we
115 // found this template through a particular injected class name,
116 // which means we end up doing nasty things to the invariants.
117 // Pretending that access is public is *much* safer.
118 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000119 }
John McCallf7a1a742009-11-24 19:00:30 +0000120 }
121 filter.done();
122}
123
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000124bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
125 bool AllowFunctionTemplates) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000126 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000127 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor312eadb2011-04-24 05:37:28 +0000128 return true;
129
Douglas Gregor3b887352011-04-27 04:48:22 +0000130 return false;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000131}
132
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000133TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000134 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000135 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000136 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000137 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000138 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000139 TemplateTy &TemplateResult,
140 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000141 assert(getLangOptions().CPlusPlus && "No template names in C!");
142
Douglas Gregor014e88d2009-11-03 23:16:33 +0000143 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000144 MemberOfUnknownSpecialization = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000145
Douglas Gregor014e88d2009-11-03 23:16:33 +0000146 switch (Name.getKind()) {
147 case UnqualifiedId::IK_Identifier:
148 TName = DeclarationName(Name.Identifier);
149 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000150
Douglas Gregor014e88d2009-11-03 23:16:33 +0000151 case UnqualifiedId::IK_OperatorFunctionId:
152 TName = Context.DeclarationNames.getCXXOperatorName(
153 Name.OperatorFunctionId.Operator);
154 break;
155
Sean Hunte6252d12009-11-28 08:58:14 +0000156 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000157 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
158 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000159
Douglas Gregor014e88d2009-11-03 23:16:33 +0000160 default:
161 return TNK_Non_template;
162 }
Mike Stump1eb44332009-09-09 15:08:12 +0000163
John McCallb3d87482010-08-24 05:47:05 +0000164 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Daniel Dunbar96a00142012-03-09 18:35:03 +0000166 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000167 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
168 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000169 if (R.empty()) return TNK_Non_template;
170 if (R.isAmbiguous()) {
171 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000172 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000173
174 // FIXME: we might have ambiguous templates, in which case we
175 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000177 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000178
John McCall0bd6feb2009-12-02 08:04:21 +0000179 TemplateName Template;
180 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000181
John McCall0bd6feb2009-12-02 08:04:21 +0000182 unsigned ResultCount = R.end() - R.begin();
183 if (ResultCount > 1) {
184 // We assume that we'll preserve the qualifier from a function
185 // template name in other ways.
186 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
187 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000188
189 // We'll do this lookup again later.
190 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000191 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000192 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
193
194 if (SS.isSet() && !SS.isInvalid()) {
195 NestedNameSpecifier *Qualifier
196 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000197 Template = Context.getQualifiedTemplateName(Qualifier,
198 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000199 } else {
200 Template = TemplateName(TD);
201 }
202
John McCallb8592062010-08-13 02:23:42 +0000203 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000204 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000205
206 // We'll do this lookup again later.
207 R.suppressDiagnostics();
208 } else {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000209 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
210 isa<TypeAliasTemplateDecl>(TD));
John McCall0bd6feb2009-12-02 08:04:21 +0000211 TemplateKind = TNK_Type_template;
212 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
John McCall0bd6feb2009-12-02 08:04:21 +0000215 TemplateResult = TemplateTy::make(Template);
216 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000217}
218
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000219bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor84d0a192010-01-12 21:28:44 +0000220 SourceLocation IILoc,
221 Scope *S,
222 const CXXScopeSpec *SS,
223 TemplateTy &SuggestedTemplate,
224 TemplateNameKind &SuggestedKind) {
225 // We can't recover unless there's a dependent scope specifier preceding the
226 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000227 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000228 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
229 computeDeclContext(*SS))
230 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000231
Douglas Gregor84d0a192010-01-12 21:28:44 +0000232 // The code is missing a 'template' keyword prior to the dependent template
233 // name.
234 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
235 Diag(IILoc, diag::err_template_kw_missing)
236 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000237 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000238 SuggestedTemplate
Douglas Gregor84d0a192010-01-12 21:28:44 +0000239 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
240 SuggestedKind = TNK_Dependent_template_name;
241 return true;
242}
243
John McCallf7a1a742009-11-24 19:00:30 +0000244void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000245 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000246 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000247 bool EnteringContext,
248 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000249 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000250 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000251 DeclContext *LookupCtx = 0;
252 bool isDependent = false;
253 if (!ObjectType.isNull()) {
254 // This nested-name-specifier occurs in a member access expression, e.g.,
255 // x->B::f, and we are looking into the type of the object.
256 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
257 LookupCtx = computeDeclContext(ObjectType);
258 isDependent = ObjectType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000259 assert((isDependent || !ObjectType->isIncompleteType()) &&
John McCallf7a1a742009-11-24 19:00:30 +0000260 "Caller should have completed object type");
Douglas Gregor1d7049a2012-01-12 16:11:24 +0000261
262 // Template names cannot appear inside an Objective-C class or object type.
263 if (ObjectType->isObjCObjectOrInterfaceType()) {
264 Found.clear();
265 return;
266 }
John McCallf7a1a742009-11-24 19:00:30 +0000267 } else if (SS.isSet()) {
268 // This nested-name-specifier occurs after another nested-name-specifier,
269 // so long into the context associated with the prior nested-name-specifier.
270 LookupCtx = computeDeclContext(SS, EnteringContext);
271 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272
John McCallf7a1a742009-11-24 19:00:30 +0000273 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000274 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000275 return;
276 }
277
278 bool ObjectTypeSearchedInScope = false;
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000279 bool AllowFunctionTemplatesInLookup = true;
John McCallf7a1a742009-11-24 19:00:30 +0000280 if (LookupCtx) {
281 // Perform "qualified" name lookup into the declaration context we
282 // computed, which is either the type of the base of a member access
283 // expression or the declaration context associated with a prior
284 // nested-name-specifier.
285 LookupQualifiedName(Found, LookupCtx);
John McCallf7a1a742009-11-24 19:00:30 +0000286 if (!ObjectType.isNull() && Found.empty()) {
287 // C++ [basic.lookup.classref]p1:
288 // In a class member access expression (5.2.5), if the . or -> token is
289 // immediately followed by an identifier followed by a <, the
290 // identifier must be looked up to determine whether the < is the
291 // beginning of a template argument list (14.2) or a less-than operator.
292 // The identifier is first looked up in the class of the object
293 // expression. If the identifier is not found, it is then looked up in
294 // the context of the entire postfix-expression and shall name a class
295 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000296 if (S) LookupName(Found, S);
297 ObjectTypeSearchedInScope = true;
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000298 AllowFunctionTemplatesInLookup = false;
John McCallf7a1a742009-11-24 19:00:30 +0000299 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000300 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000301 // We cannot look into a dependent object type or nested nme
302 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000303 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000304 return;
305 } else {
306 // Perform unqualified name lookup in the current scope.
307 LookupName(Found, S);
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000308
309 if (!ObjectType.isNull())
310 AllowFunctionTemplatesInLookup = false;
John McCallf7a1a742009-11-24 19:00:30 +0000311 }
312
Douglas Gregor2e933882010-01-12 17:06:20 +0000313 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000314 // If we did not find any names, attempt to correct any typos.
315 DeclarationName Name = Found.getLookupName();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000316 Found.clear();
Kaelyn Uhrainf8ec8c92012-01-13 23:10:36 +0000317 // Simple filter callback that, for keywords, only accepts the C++ *_cast
318 CorrectionCandidateCallback FilterCCC;
319 FilterCCC.WantTypeSpecifiers = false;
320 FilterCCC.WantExpressionKeywords = false;
321 FilterCCC.WantRemainingKeywords = false;
322 FilterCCC.WantCXXNamedCasts = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000323 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
324 Found.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000325 FilterCCC, LookupCtx)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000326 Found.setLookupName(Corrected.getCorrection());
327 if (Corrected.getCorrectionDecl())
328 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000329 FilterAcceptableTemplateNames(Found);
John McCallad00b772010-06-16 08:42:20 +0000330 if (!Found.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000331 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
332 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregorbfea2392009-12-31 08:11:17 +0000333 if (LookupCtx)
334 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000335 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
336 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000337 else
338 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000339 << Name << CorrectedQuotedStr
340 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000341 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
342 Diag(Template->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000343 << CorrectedQuotedStr;
John McCallad00b772010-06-16 08:42:20 +0000344 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000345 } else {
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000346 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000347 }
348 }
349
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000351 if (Found.empty()) {
352 if (isDependent)
353 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000354 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000355 }
John McCallf7a1a742009-11-24 19:00:30 +0000356
357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
358 // C++ [basic.lookup.classref]p1:
359 // [...] If the lookup in the class of the object expression finds a
360 // template, the name is also looked up in the context of the entire
361 // postfix-expression and [...]
362 //
363 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
364 LookupOrdinaryName);
365 LookupName(FoundOuter, S);
Douglas Gregor5a7a5bb2012-03-10 23:52:41 +0000366 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000367
John McCallf7a1a742009-11-24 19:00:30 +0000368 if (FoundOuter.empty()) {
369 // - if the name is not found, the name found in the class of the
370 // object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000371 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
372 FoundOuter.isAmbiguous()) {
John McCallf7a1a742009-11-24 19:00:30 +0000373 // - if the name is found in the context of the entire
374 // postfix-expression and does not name a class template, the name
375 // found in the class of the object expression is used, otherwise
Douglas Gregora6d1e762011-08-10 21:59:45 +0000376 FoundOuter.clear();
John McCallad00b772010-06-16 08:42:20 +0000377 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000378 // - if the name found is a class template, it must refer to the same
379 // entity as the one found in the class of the object expression,
380 // otherwise the program is ill-formed.
381 if (!Found.isSingleResult() ||
382 Found.getFoundDecl()->getCanonicalDecl()
383 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000385 diag::ext_nested_name_member_ref_lookup_ambiguous)
386 << Found.getLookupName()
387 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000388 Diag(Found.getRepresentativeDecl()->getLocation(),
389 diag::note_ambig_member_ref_object_type)
390 << ObjectType;
391 Diag(FoundOuter.getFoundDecl()->getLocation(),
392 diag::note_ambig_member_ref_scope);
393
394 // Recover by taking the template that we found in the object
395 // expression's type.
396 }
397 }
398 }
399}
400
John McCall2f841ba2009-12-02 03:53:29 +0000401/// ActOnDependentIdExpression - Handle a dependent id-expression that
402/// was just parsed. This is only possible with an explicit scope
403/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000404ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000405Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000406 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000407 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000408 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000409 const TemplateArgumentListInfo *TemplateArgs) {
John McCallea1471e2010-05-20 01:18:31 +0000410 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000411
John McCall2f841ba2009-12-02 03:53:29 +0000412 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000413 isa<CXXMethodDecl>(DC) &&
414 cast<CXXMethodDecl>(DC)->isInstance()) {
415 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416
John McCallf7a1a742009-11-24 19:00:30 +0000417 // Since the 'this' expression is synthesized, we don't need to
418 // perform the double-lookup check.
419 NamedDecl *FirstQualifierInScope = 0;
420
John McCallaa81e162009-12-01 22:10:20 +0000421 return Owned(CXXDependentScopeMemberExpr::Create(Context,
422 /*This*/ 0, ThisType,
423 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000424 /*Op*/ SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +0000425 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000426 TemplateKWLoc,
John McCallf7a1a742009-11-24 19:00:30 +0000427 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000428 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000429 TemplateArgs));
430 }
431
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000432 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000433}
434
John McCall60d7b3a2010-08-24 06:29:42 +0000435ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000436Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000437 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000438 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000439 const TemplateArgumentListInfo *TemplateArgs) {
440 return Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +0000441 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000442 TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000443 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000444 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000445}
446
Douglas Gregor72c3f312008-12-05 18:15:24 +0000447/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
448/// that the template parameter 'PrevDecl' is being shadowed by a new
449/// declaration at location Loc. Returns true to indicate that this is
450/// an error, and false otherwise.
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000451void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000452 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000453
454 // Microsoft Visual C++ permits template parameters to be shadowed.
Francois Pichet62ec1f22011-09-17 17:15:52 +0000455 if (getLangOptions().MicrosoftExt)
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000456 return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000457
458 // C++ [temp.local]p4:
459 // A template-parameter shall not be redeclared within its
460 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000461 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000462 << cast<NamedDecl>(PrevDecl)->getDeclName();
463 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000464 return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000465}
466
Douglas Gregor2943aed2009-03-03 04:44:36 +0000467/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000468/// the parameter D to reference the templated declaration and return a pointer
469/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000470TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
471 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
472 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000473 return Temp;
474 }
475 return 0;
476}
477
Douglas Gregorba68eca2011-01-05 17:40:24 +0000478ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
479 SourceLocation EllipsisLoc) const {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000480 assert(Kind == Template &&
Douglas Gregorba68eca2011-01-05 17:40:24 +0000481 "Only template template arguments can be pack expansions here");
482 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
483 "Template template argument pack expansion without packs");
484 ParsedTemplateArgument Result(*this);
485 Result.EllipsisLoc = EllipsisLoc;
486 return Result;
487}
488
Douglas Gregor788cd062009-11-11 01:00:40 +0000489static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
490 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000491
Douglas Gregor788cd062009-11-11 01:00:40 +0000492 switch (Arg.getKind()) {
493 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000494 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000495 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000496 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000497 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000498 return TemplateArgumentLoc(TemplateArgument(T), DI);
499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000500
Douglas Gregor788cd062009-11-11 01:00:40 +0000501 case ParsedTemplateArgument::NonType: {
502 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
503 return TemplateArgumentLoc(TemplateArgument(E), E);
504 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000505
Douglas Gregor788cd062009-11-11 01:00:40 +0000506 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000507 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor2be29f42011-01-14 23:41:42 +0000508 TemplateArgument TArg;
509 if (Arg.getEllipsisLoc().isValid())
510 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
511 else
512 TArg = Template;
513 return TemplateArgumentLoc(TArg,
Douglas Gregorb6744ef2011-03-02 17:09:35 +0000514 Arg.getScopeSpec().getWithLocInContext(
515 SemaRef.Context),
Douglas Gregorba68eca2011-01-05 17:40:24 +0000516 Arg.getLocation(),
517 Arg.getEllipsisLoc());
Douglas Gregor788cd062009-11-11 01:00:40 +0000518 }
519 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000520
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000521 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000522}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000523
Douglas Gregor788cd062009-11-11 01:00:40 +0000524/// \brief Translates template arguments as provided by the parser
525/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000526void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
527 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000528 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000529 TemplateArgs.addArgument(translateTemplateArgument(*this,
530 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000531}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000532
Douglas Gregor72c3f312008-12-05 18:15:24 +0000533/// ActOnTypeParameter - Called when a C++ template type parameter
534/// (e.g., "typename T") has been parsed. Typename specifies whether
535/// the keyword "typename" was used to declare the type parameter
536/// (otherwise, "class" was used), and KeyLoc is the location of the
537/// "class" or "typename" keyword. ParamName is the name of the
538/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000539/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000540/// If the type parameter has a default argument, it will be added
541/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000542Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
543 SourceLocation EllipsisLoc,
544 SourceLocation KeyLoc,
545 IdentifierInfo *ParamName,
546 SourceLocation ParamNameLoc,
547 unsigned Depth, unsigned Position,
548 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000549 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 assert(S->isTemplateParamScope() &&
551 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000552 bool Invalid = false;
553
554 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000555 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000556 LookupOrdinaryName,
557 ForRedeclaration);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000558 if (PrevDecl && PrevDecl->isTemplateParameter()) {
559 DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl);
560 PrevDecl = 0;
561 }
Douglas Gregor72c3f312008-12-05 18:15:24 +0000562 }
563
Douglas Gregorddc29e12009-02-06 22:42:48 +0000564 SourceLocation Loc = ParamNameLoc;
565 if (!ParamName)
566 Loc = KeyLoc;
567
Douglas Gregor72c3f312008-12-05 18:15:24 +0000568 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000569 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000570 KeyLoc, Loc, Depth, Position, ParamName,
571 Typename, Ellipsis);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000572 Param->setAccess(AS_public);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000573 if (Invalid)
574 Param->setInvalidDecl();
575
576 if (ParamName) {
577 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000578 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000579 IdResolver.AddDecl(Param);
580 }
581
Douglas Gregor61c4d282011-01-05 15:48:55 +0000582 // C++0x [temp.param]p9:
583 // A default template-argument may be specified for any kind of
584 // template-parameter that is not a template parameter pack.
585 if (DefaultArg && Ellipsis) {
586 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
587 DefaultArg = ParsedType();
588 }
589
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000590 // Handle the default argument, if provided.
591 if (DefaultArg) {
592 TypeSourceInfo *DefaultTInfo;
593 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000595 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000596
Douglas Gregor6f526752010-12-16 08:48:57 +0000597 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6f526752010-12-16 08:48:57 +0000599 UPPC_DefaultArgument))
600 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000602 // Check the template argument itself.
603 if (CheckTemplateArgument(Param, DefaultTInfo)) {
604 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000605 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000606 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000608 Param->setDefaultArgument(DefaultTInfo, false);
609 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000610
John McCalld226f652010-08-21 09:40:31 +0000611 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000612}
613
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614/// \brief Check that the type of a non-type template parameter is
615/// well-formed.
616///
617/// \returns the (possibly-promoted) parameter type if valid;
618/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000619QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000621 // We don't allow variably-modified types as the type of non-type template
622 // parameters.
623 if (T->isVariablyModifiedType()) {
624 Diag(Loc, diag::err_variably_modified_nontype_template_param)
625 << T;
626 return QualType();
627 }
628
Douglas Gregor2943aed2009-03-03 04:44:36 +0000629 // C++ [temp.param]p4:
630 //
631 // A non-type template-parameter shall have one of the following
632 // (optionally cv-qualified) types:
633 //
634 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000635 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000636 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000637 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000638 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 T->isReferenceType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000640 // -- pointer to member,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000641 T->isMemberPointerType() ||
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000642 // -- std::nullptr_t.
643 T->isNullPtrType() ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000644 // If T is a dependent type, we can't do the check now, so we
645 // assume that it is well-formed.
646 T->isDependentType())
647 return T;
648 // C++ [temp.param]p8:
649 //
650 // A non-type template-parameter of type "array of T" or
651 // "function returning T" is adjusted to be of type "pointer to
652 // T" or "pointer to function returning T", respectively.
653 else if (T->isArrayType())
654 // FIXME: Keep the type prior to promotion?
655 return Context.getArrayDecayedType(T);
656 else if (T->isFunctionType())
657 // FIXME: Keep the type prior to promotion?
658 return Context.getPointerType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000659
Douglas Gregor2943aed2009-03-03 04:44:36 +0000660 Diag(Loc, diag::err_template_nontype_parm_bad_type)
661 << T;
662
663 return QualType();
664}
665
John McCalld226f652010-08-21 09:40:31 +0000666Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
667 unsigned Depth,
668 unsigned Position,
669 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000670 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000671 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
672 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000673
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000674 assert(S->isTemplateParamScope() &&
675 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000676 bool Invalid = false;
677
678 IdentifierInfo *ParamName = D.getIdentifier();
679 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000680 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000681 LookupOrdinaryName,
682 ForRedeclaration);
Douglas Gregorcb8f9512011-10-20 17:58:49 +0000683 if (PrevDecl && PrevDecl->isTemplateParameter()) {
684 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
685 PrevDecl = 0;
686 }
Douglas Gregor72c3f312008-12-05 18:15:24 +0000687 }
688
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000689 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
690 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000691 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000692 Invalid = true;
693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694
Douglas Gregor10738d32010-12-23 23:51:58 +0000695 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000696 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000697 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +0000698 D.getLocStart(),
John McCall7a9813c2010-01-22 00:28:27 +0000699 D.getIdentifierLoc(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000700 Depth, Position, ParamName, T,
Douglas Gregor10738d32010-12-23 23:51:58 +0000701 IsParameterPack, TInfo);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000702 Param->setAccess(AS_public);
703
Douglas Gregor72c3f312008-12-05 18:15:24 +0000704 if (Invalid)
705 Param->setInvalidDecl();
706
707 if (D.getIdentifier()) {
708 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000709 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000710 IdResolver.AddDecl(Param);
711 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000712
Douglas Gregor61c4d282011-01-05 15:48:55 +0000713 // C++0x [temp.param]p9:
714 // A default template-argument may be specified for any kind of
715 // template-parameter that is not a template parameter pack.
716 if (Default && IsParameterPack) {
717 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
718 Default = 0;
719 }
720
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000721 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000722 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000723 // Check for unexpanded parameter packs.
724 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
725 return Param;
726
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000727 TemplateArgument Converted;
John Wiegley429bb272011-04-08 18:41:53 +0000728 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
729 if (DefaultRes.isInvalid()) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000730 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000731 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000732 }
John Wiegley429bb272011-04-08 18:41:53 +0000733 Default = DefaultRes.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000734
John McCall9ae2f072010-08-23 23:25:46 +0000735 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000737
John McCalld226f652010-08-21 09:40:31 +0000738 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000739}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000740
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000741/// ActOnTemplateTemplateParameter - Called when a C++ template template
742/// parameter (e.g. T in template <template <typename> class T> class array)
743/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000744Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
745 SourceLocation TmpLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +0000746 TemplateParameterList *Params,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000747 SourceLocation EllipsisLoc,
John McCalld226f652010-08-21 09:40:31 +0000748 IdentifierInfo *Name,
749 SourceLocation NameLoc,
750 unsigned Depth,
751 unsigned Position,
752 SourceLocation EqualLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000753 ParsedTemplateArgument Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000754 assert(S->isTemplateParamScope() &&
755 "Template template parameter not in template parameter scope!");
756
757 // Construct the parameter object.
Douglas Gregor61c4d282011-01-05 15:48:55 +0000758 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000759 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000760 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000761 NameLoc.isInvalid()? TmpLoc : NameLoc,
762 Depth, Position, IsParameterPack,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000763 Name, Params);
Douglas Gregor9a299e02011-03-04 17:52:15 +0000764 Param->setAccess(AS_public);
765
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000766 // If the template template parameter has a name, then link the identifier
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000767 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000768 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000769 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000770 IdResolver.AddDecl(Param);
771 }
772
Douglas Gregor6f526752010-12-16 08:48:57 +0000773 if (Params->size() == 0) {
774 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
775 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
776 Param->setInvalidDecl();
777 }
778
Douglas Gregor61c4d282011-01-05 15:48:55 +0000779 // C++0x [temp.param]p9:
780 // A default template-argument may be specified for any kind of
781 // template-parameter that is not a template parameter pack.
782 if (IsParameterPack && !Default.isInvalid()) {
783 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
784 Default = ParsedTemplateArgument();
785 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000786
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000787 if (!Default.isInvalid()) {
788 // Check only that we have a template template argument. We don't want to
789 // try to check well-formedness now, because our template template parameter
790 // might have dependent types in its template parameters, which we wouldn't
791 // be able to match now.
792 //
793 // If none of the template template parameter's template arguments mention
794 // other template parameters, we could actually perform more checking here.
795 // However, it isn't worth doing.
796 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
797 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
798 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
799 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000800 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000801 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802
Douglas Gregor6f526752010-12-16 08:48:57 +0000803 // Check for unexpanded parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000804 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6f526752010-12-16 08:48:57 +0000805 DefaultArg.getArgument().getAsTemplate(),
806 UPPC_DefaultArgument))
807 return Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000808
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000809 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000811
John McCalld226f652010-08-21 09:40:31 +0000812 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000813}
814
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000815/// ActOnTemplateParameterList - Builds a TemplateParameterList that
816/// contains the template parameters in Params/NumParams.
Richard Trieu90ab75b2011-09-09 03:18:59 +0000817TemplateParameterList *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000818Sema::ActOnTemplateParameterList(unsigned Depth,
819 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000820 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000821 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000822 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000823 SourceLocation RAngleLoc) {
824 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000825 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000826
Douglas Gregorddc29e12009-02-06 22:42:48 +0000827 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000828 (NamedDecl**)Params, NumParams,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000829 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000830}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000831
John McCallb6217662010-03-15 10:12:16 +0000832static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
833 if (SS.isSet())
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000834 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +0000835}
836
John McCallf312b1e2010-08-26 23:41:50 +0000837DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000838Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000839 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000840 IdentifierInfo *Name, SourceLocation NameLoc,
841 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000842 TemplateParameterList *TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +0000843 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +0000844 unsigned NumOuterTemplateParamLists,
845 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump1eb44332009-09-09 15:08:12 +0000846 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000847 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000848 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000849 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000850
851 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000852 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000853 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000854
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000855 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
856 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000857
858 // There is no such thing as an unnamed class template.
859 if (!Name) {
860 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000861 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000862 }
863
864 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000865 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000866 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000867 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000868 if (SS.isNotEmpty() && !SS.isInvalid()) {
869 SemanticContext = computeDeclContext(SS, true);
870 if (!SemanticContext) {
871 // FIXME: Produce a reasonable diagnostic here
872 return true;
873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
John McCall77bb1aa2010-05-01 00:40:08 +0000875 if (RequireCompleteDeclContext(SS, SemanticContext))
876 return true;
877
Douglas Gregor20606502011-10-14 15:31:12 +0000878 // If we're adding a template to a dependent context, we may need to
879 // rebuilding some of the types used within the template parameter list,
880 // now that we know what the current instantiation is.
881 if (SemanticContext->isDependentContext()) {
882 ContextRAII SavedContext(*this, SemanticContext);
883 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
884 Invalid = true;
885 }
886
John McCalla24dc2e2009-11-17 02:14:36 +0000887 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000888 } else {
889 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000890 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000891 }
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Douglas Gregor57265e32010-04-12 16:00:01 +0000893 if (Previous.isAmbiguous())
894 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000895
Douglas Gregorddc29e12009-02-06 22:42:48 +0000896 NamedDecl *PrevDecl = 0;
897 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000898 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000899
Douglas Gregorddc29e12009-02-06 22:42:48 +0000900 // If there is a previous declaration with the same name, check
901 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000902 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000903 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000904
905 // We may have found the injected-class-name of a class template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000906 // class template partial specialization, or class template specialization.
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000907 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000908 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000909 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
910 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000911 PrevClassTemplate
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000912 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
913 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
914 PrevClassTemplate
915 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
916 ->getSpecializedTemplate();
917 }
918 }
919
John McCall65c49462009-12-18 11:25:59 +0000920 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000921 // C++ [namespace.memdef]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000922 // [...] When looking for a prior declaration of a class or a function
923 // declared as a friend, and when the name of the friend class or
John McCalle129d442009-12-17 23:21:11 +0000924 // function is neither a qualified name nor a template-id, scopes outside
925 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000926 if (!SS.isSet()) {
927 DeclContext *OutermostContext = CurContext;
928 while (!OutermostContext->isFileContext())
929 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000930
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000931 if (PrevDecl &&
932 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
933 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
934 SemanticContext = PrevDecl->getDeclContext();
935 } else {
936 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000937 // context we computed is the semantic context for our new
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000938 // declaration.
939 PrevDecl = PrevClassTemplate = 0;
940 SemanticContext = OutermostContext;
941 }
John McCalle129d442009-12-17 23:21:11 +0000942 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000943
John McCalle129d442009-12-17 23:21:11 +0000944 if (CurContext->isDependentContext()) {
945 // If this is a dependent context, we don't want to link the friend
946 // class template to the template in scope, because that would perform
947 // checking of the template parameter lists that can't be performed
948 // until the outer context is instantiated.
949 PrevDecl = PrevClassTemplate = 0;
950 }
951 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
952 PrevDecl = PrevClassTemplate = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000953
Douglas Gregorddc29e12009-02-06 22:42:48 +0000954 if (PrevClassTemplate) {
955 // Ensure that the template parameter lists are compatible.
956 if (!TemplateParameterListsAreEqual(TemplateParams,
957 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000958 /*Complain=*/true,
959 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000960 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000961
962 // C++ [temp.class]p4:
963 // In a redeclaration, partial specialization, explicit
964 // specialization or explicit instantiation of a class template,
965 // the class-key shall agree in kind with the original class
966 // template declaration (7.1.5.3).
967 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieubbf34c02011-06-10 03:11:26 +0000968 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
969 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000970 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000971 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000972 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000973 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000974 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000975 }
976
Douglas Gregorddc29e12009-02-06 22:42:48 +0000977 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000978 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000979 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000980 Diag(NameLoc, diag::err_redefinition) << Name;
981 Diag(Def->getLocation(), diag::note_previous_definition);
982 // FIXME: Would it make sense to try to "forget" the previous
983 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000984 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000985 }
Douglas Gregor6311d2b2011-09-09 18:32:39 +0000986 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000987 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
988 // Maybe we will complain about the shadowed template parameter.
989 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
990 // Just pretend that we didn't see the previous declaration.
991 PrevDecl = 0;
992 } else if (PrevDecl) {
993 // C++ [temp]p5:
994 // A class template shall not have the same name as any other
995 // template, class, function, object, enumeration, enumerator,
996 // namespace, or type in the same scope (3.3), except as specified
997 // in (14.5.4).
998 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
999 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +00001000 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001001 }
1002
Douglas Gregord684b002009-02-10 19:49:53 +00001003 // Check the template parameter list of this declaration, possibly
1004 // merging in the template parameter list from the previous class
1005 // template declaration.
1006 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001007 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00001008 (SS.isSet() && SemanticContext &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00001009 SemanticContext->isRecord() &&
1010 SemanticContext->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00001011 ? TPC_ClassTemplateMember
1012 : TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +00001013 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Douglas Gregor57265e32010-04-12 16:00:01 +00001015 if (SS.isSet()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001016 // If the name of the template was qualified, we must be defining the
Douglas Gregor57265e32010-04-12 16:00:01 +00001017 // template out-of-line.
1018 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
Douglas Gregorea9f54a2011-11-01 21:35:16 +00001019 !(TUK == TUK_Friend && CurContext->isDependentContext())) {
Douglas Gregor57265e32010-04-12 16:00:01 +00001020 Diag(NameLoc, diag::err_member_def_does_not_match)
1021 << Name << SemanticContext << SS.getRange();
Douglas Gregorea9f54a2011-11-01 21:35:16 +00001022 Invalid = true;
1023 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001024 }
1025
Mike Stump1eb44332009-09-09 15:08:12 +00001026 CXXRecordDecl *NewClass =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001027 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump1eb44332009-09-09 15:08:12 +00001028 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001029 PrevClassTemplate->getTemplatedDecl() : 0,
1030 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +00001031 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00001032 if (NumOuterTemplateParamLists > 0)
1033 NewClass->setTemplateParameterListsInfo(Context,
1034 NumOuterTemplateParamLists,
1035 OuterTemplateParamLists);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001036
Eli Friedman572ae0a2012-02-10 02:02:21 +00001037 // Add alignment attributes if necessary; these attributes are checked when
1038 // the ASTContext lays out the structure.
1039 AddAlignmentAttributesForRecord(NewClass);
1040 AddMsStructLayoutForRecord(NewClass);
1041
Douglas Gregorddc29e12009-02-06 22:42:48 +00001042 ClassTemplateDecl *NewTemplate
1043 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1044 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001045 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +00001046 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001047
Douglas Gregor2ccd89c2011-12-20 18:11:52 +00001048 if (ModulePrivateLoc.isValid())
Douglas Gregor6311d2b2011-09-09 18:32:39 +00001049 NewTemplate->setModulePrivate();
Douglas Gregor8d267c52011-09-09 02:06:17 +00001050
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001051 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +00001052 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +00001053 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +00001054 assert(T->isDependentType() && "Class template type is not dependent?");
1055 (void)T;
1056
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001057 // If we are providing an explicit specialization of a member that is a
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001058 // class template, make a note of that.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001059 if (PrevClassTemplate &&
Douglas Gregorfd056bc2009-10-13 16:30:37 +00001060 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1061 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001062
Anders Carlsson4cbe82c2009-03-26 01:24:28 +00001063 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +00001064 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +00001065 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregorddc29e12009-02-06 22:42:48 +00001067 // Set the lexical context of these templates
1068 NewClass->setLexicalDeclContext(CurContext);
1069 NewTemplate->setLexicalDeclContext(CurContext);
1070
John McCall0f434ec2009-07-31 02:45:11 +00001071 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001072 NewClass->startDefinition();
1073
1074 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001075 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001076
John McCall05b23ea2009-09-14 21:59:20 +00001077 if (TUK != TUK_Friend)
1078 PushOnScopeChains(NewTemplate, S);
1079 else {
Douglas Gregord85bea22009-09-26 06:47:28 +00001080 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +00001081 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +00001082 NewClass->setAccess(PrevClassTemplate->getAccess());
1083 }
John McCall05b23ea2009-09-14 21:59:20 +00001084
Douglas Gregord85bea22009-09-26 06:47:28 +00001085 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1086 PrevClassTemplate != NULL);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087
John McCall05b23ea2009-09-14 21:59:20 +00001088 // Friend templates are visible in fairly strange ways.
1089 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001090 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +00001091 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1092 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1093 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001094 /* AddToContext = */ false);
John McCall05b23ea2009-09-14 21:59:20 +00001095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001096
Douglas Gregord85bea22009-09-26 06:47:28 +00001097 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1098 NewClass->getLocation(),
1099 NewTemplate,
1100 /*FIXME:*/NewClass->getLocation());
1101 Friend->setAccess(AS_public);
1102 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001103 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001104
Douglas Gregord684b002009-02-10 19:49:53 +00001105 if (Invalid) {
1106 NewTemplate->setInvalidDecl();
1107 NewClass->setInvalidDecl();
1108 }
John McCalld226f652010-08-21 09:40:31 +00001109 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001110}
1111
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001112/// \brief Diagnose the presence of a default template argument on a
1113/// template parameter, which is ill-formed in certain contexts.
1114///
1115/// \returns true if the default template argument should be dropped.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001117 Sema::TemplateParamListContext TPC,
1118 SourceLocation ParamLoc,
1119 SourceRange DefArgRange) {
1120 switch (TPC) {
1121 case Sema::TPC_ClassTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001122 case Sema::TPC_TypeAliasTemplate:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001123 return false;
1124
1125 case Sema::TPC_FunctionTemplate:
Douglas Gregord89d86f2011-02-04 04:20:44 +00001126 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001127 // C++ [temp.param]p9:
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001128 // A default template-argument shall not be specified in a
1129 // function template declaration or a function template
1130 // definition [...]
Douglas Gregord89d86f2011-02-04 04:20:44 +00001131 // If a friend function template declaration specifies a default
1132 // template-argument, that declaration shall be a definition and shall be
1133 // the only declaration of the function template in the translation unit.
1134 // (C++98/03 doesn't have this wording; see DR226).
Richard Smithebaf0e62011-10-18 20:49:44 +00001135 S.Diag(ParamLoc, S.getLangOptions().CPlusPlus0x ?
1136 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1137 : diag::ext_template_parameter_default_in_function_template)
1138 << DefArgRange;
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001139 return false;
1140
1141 case Sema::TPC_ClassTemplateMember:
1142 // C++0x [temp.param]p9:
1143 // A default template-argument shall not be specified in the
1144 // template-parameter-lists of the definition of a member of a
1145 // class template that appears outside of the member's class.
1146 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1147 << DefArgRange;
1148 return true;
1149
1150 case Sema::TPC_FriendFunctionTemplate:
1151 // C++ [temp.param]p9:
1152 // A default template-argument shall not be specified in a
1153 // friend template declaration.
1154 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1155 << DefArgRange;
1156 return true;
1157
1158 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1159 // for friend function templates if there is only a single
1160 // declaration (and it is a definition). Strange!
1161 }
1162
David Blaikie7530c032012-01-17 06:56:22 +00001163 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001164}
1165
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001166/// \brief Check for unexpanded parameter packs within the template parameters
1167/// of a template template parameter, recursively.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001168static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1169 TemplateTemplateParmDecl *TTP) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001170 TemplateParameterList *Params = TTP->getTemplateParameters();
1171 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1172 NamedDecl *P = Params->getParam(I);
1173 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001174 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001175 NTTP->getTypeSourceInfo(),
1176 Sema::UPPC_NonTypeTemplateParameterType))
1177 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001178
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001179 continue;
1180 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001181
1182 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001183 = dyn_cast<TemplateTemplateParmDecl>(P))
1184 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1185 return true;
1186 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001187
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001188 return false;
1189}
1190
Douglas Gregord684b002009-02-10 19:49:53 +00001191/// \brief Checks the validity of a template parameter list, possibly
1192/// considering the template parameter list from a previous
1193/// declaration.
1194///
1195/// If an "old" template parameter list is provided, it must be
1196/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1197/// template parameter list.
1198///
1199/// \param NewParams Template parameter list for a new template
1200/// declaration. This template parameter list will be updated with any
1201/// default arguments that are carried through from the previous
1202/// template parameter list.
1203///
1204/// \param OldParams If provided, template parameter list from a
1205/// previous declaration of the same template. Default template
1206/// arguments will be merged from the old template parameter list to
1207/// the new template parameter list.
1208///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001209/// \param TPC Describes the context in which we are checking the given
1210/// template parameter list.
1211///
Douglas Gregord684b002009-02-10 19:49:53 +00001212/// \returns true if an error occurred, false otherwise.
1213bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001214 TemplateParameterList *OldParams,
1215 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001216 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregord684b002009-02-10 19:49:53 +00001218 // C++ [temp.param]p10:
1219 // The set of default template-arguments available for use with a
1220 // template declaration or definition is obtained by merging the
1221 // default arguments from the definition (if in scope) and all
1222 // declarations in scope in the same way default function
1223 // arguments are (8.3.6).
1224 bool SawDefaultArgument = false;
1225 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001226
Mike Stump1a35fde2009-02-11 23:03:27 +00001227 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001228 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001229 if (OldParams)
1230 OldParam = OldParams->begin();
1231
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001232 bool RemoveDefaultArguments = false;
Douglas Gregord684b002009-02-10 19:49:53 +00001233 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1234 NewParamEnd = NewParams->end();
1235 NewParam != NewParamEnd; ++NewParam) {
1236 // Variables used to diagnose redundant default arguments
1237 bool RedundantDefaultArg = false;
1238 SourceLocation OldDefaultLoc;
1239 SourceLocation NewDefaultLoc;
1240
David Blaikie1368e582011-10-19 05:19:50 +00001241 // Variable used to diagnose missing default arguments
Douglas Gregord684b002009-02-10 19:49:53 +00001242 bool MissingDefaultArg = false;
1243
David Blaikie1368e582011-10-19 05:19:50 +00001244 // Variable used to diagnose non-final parameter packs
1245 bool SawParameterPack = false;
Anders Carlsson49d25572009-06-12 23:20:15 +00001246
Douglas Gregord684b002009-02-10 19:49:53 +00001247 if (TemplateTypeParmDecl *NewTypeParm
1248 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001249 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250 if (NewTypeParm->hasDefaultArgument() &&
1251 DiagnoseDefaultTemplateArgument(*this, TPC,
1252 NewTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001253 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001254 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001255 NewTypeParm->removeDefaultArgument();
1256
1257 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001258 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001259 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Anders Carlsson49d25572009-06-12 23:20:15 +00001261 if (NewTypeParm->isParameterPack()) {
1262 assert(!NewTypeParm->hasDefaultArgument() &&
1263 "Parameter packs can't have a default argument!");
1264 SawParameterPack = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001265 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001266 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001267 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1268 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1269 SawDefaultArgument = true;
1270 RedundantDefaultArg = true;
1271 PreviousDefaultArgLoc = NewDefaultLoc;
1272 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1273 // Merge the default argument from the old declaration to the
1274 // new declaration.
1275 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001276 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001277 true);
1278 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1279 } else if (NewTypeParm->hasDefaultArgument()) {
1280 SawDefaultArgument = true;
1281 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1282 } else if (SawDefaultArgument)
1283 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001284 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001285 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001286 // Check for unexpanded parameter packs.
1287 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001288 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001289 UPPC_NonTypeTemplateParameterType)) {
1290 Invalid = true;
1291 continue;
1292 }
1293
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001294 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001295 if (NewNonTypeParm->hasDefaultArgument() &&
1296 DiagnoseDefaultTemplateArgument(*this, TPC,
1297 NewNonTypeParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001298 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001299 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001300 }
1301
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001302 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001303 NonTypeTemplateParmDecl *OldNonTypeParm
1304 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001305 if (NewNonTypeParm->isParameterPack()) {
1306 assert(!NewNonTypeParm->hasDefaultArgument() &&
1307 "Parameter packs can't have a default argument!");
1308 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001309 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001310 NewNonTypeParm->hasDefaultArgument()) {
1311 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1312 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1313 SawDefaultArgument = true;
1314 RedundantDefaultArg = true;
1315 PreviousDefaultArgLoc = NewDefaultLoc;
1316 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1317 // Merge the default argument from the old declaration to the
1318 // new declaration.
1319 SawDefaultArgument = true;
1320 // FIXME: We need to create a new kind of "default argument"
Douglas Gregor61c4d282011-01-05 15:48:55 +00001321 // expression that points to a previous non-type template
Douglas Gregord684b002009-02-10 19:49:53 +00001322 // parameter.
1323 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001324 OldNonTypeParm->getDefaultArgument(),
1325 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001326 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1327 } else if (NewNonTypeParm->hasDefaultArgument()) {
1328 SawDefaultArgument = true;
1329 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1330 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001331 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001332 } else {
Douglas Gregord684b002009-02-10 19:49:53 +00001333 TemplateTemplateParmDecl *NewTemplateParm
1334 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001335
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001336 // Check for unexpanded parameter packs, recursively.
Douglas Gregor65019ac2011-10-25 03:44:56 +00001337 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001338 Invalid = true;
1339 continue;
1340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001341
David Blaikie1368e582011-10-19 05:19:50 +00001342 // Check the presence of a default argument here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343 if (NewTemplateParm->hasDefaultArgument() &&
1344 DiagnoseDefaultTemplateArgument(*this, TPC,
1345 NewTemplateParm->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001346 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001347 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001348
1349 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001350 TemplateTemplateParmDecl *OldTemplateParm
1351 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001352 if (NewTemplateParm->isParameterPack()) {
1353 assert(!NewTemplateParm->hasDefaultArgument() &&
1354 "Parameter packs can't have a default argument!");
1355 SawParameterPack = true;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001356 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001357 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001358 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1359 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001360 SawDefaultArgument = true;
1361 RedundantDefaultArg = true;
1362 PreviousDefaultArgLoc = NewDefaultLoc;
1363 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1364 // Merge the default argument from the old declaration to the
1365 // new declaration.
1366 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001367 // FIXME: We need to create a new kind of "default argument" expression
1368 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001369 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001370 OldTemplateParm->getDefaultArgument(),
1371 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001372 PreviousDefaultArgLoc
1373 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001374 } else if (NewTemplateParm->hasDefaultArgument()) {
1375 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001376 PreviousDefaultArgLoc
1377 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001378 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001379 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001380 }
1381
David Blaikie1368e582011-10-19 05:19:50 +00001382 // C++0x [temp.param]p11:
1383 // If a template parameter of a primary class template or alias template
1384 // is a template parameter pack, it shall be the last template parameter.
1385 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1386 (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1387 Diag((*NewParam)->getLocation(),
1388 diag::err_template_param_pack_must_be_last_template_parameter);
1389 Invalid = true;
1390 }
1391
Douglas Gregord684b002009-02-10 19:49:53 +00001392 if (RedundantDefaultArg) {
1393 // C++ [temp.param]p12:
1394 // A template-parameter shall not be given default arguments
1395 // by two different declarations in the same scope.
1396 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1397 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1398 Invalid = true;
Douglas Gregoree5d21f2011-02-04 03:57:22 +00001399 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregord684b002009-02-10 19:49:53 +00001400 // C++ [temp.param]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401 // If a template-parameter of a class template has a default
1402 // template-argument, each subsequent template-parameter shall either
Douglas Gregorb49e4152011-01-05 16:21:17 +00001403 // have a default template-argument supplied or be a template parameter
1404 // pack.
Mike Stump1eb44332009-09-09 15:08:12 +00001405 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001406 diag::err_template_param_default_arg_missing);
1407 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1408 Invalid = true;
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001409 RemoveDefaultArguments = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001410 }
1411
1412 // If we have an old template parameter list that we're merging
1413 // in, move on to the next parameter.
1414 if (OldParams)
1415 ++OldParam;
1416 }
1417
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001418 // We were missing some default arguments at the end of the list, so remove
1419 // all of the default arguments.
1420 if (RemoveDefaultArguments) {
1421 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1422 NewParamEnd = NewParams->end();
1423 NewParam != NewParamEnd; ++NewParam) {
1424 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1425 TTP->removeDefaultArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001426 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorfd1a8fd2011-01-27 01:40:17 +00001427 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1428 NTTP->removeDefaultArgument();
1429 else
1430 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1431 }
1432 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001433
Douglas Gregord684b002009-02-10 19:49:53 +00001434 return Invalid;
1435}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001436
John McCall4e2cbb22010-10-20 05:44:58 +00001437namespace {
1438
1439/// A class which looks for a use of a certain level of template
1440/// parameter.
1441struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1442 typedef RecursiveASTVisitor<DependencyChecker> super;
1443
1444 unsigned Depth;
1445 bool Match;
1446
1447 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1448 NamedDecl *ND = Params->getParam(0);
1449 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1450 Depth = PD->getDepth();
1451 } else if (NonTypeTemplateParmDecl *PD =
1452 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1453 Depth = PD->getDepth();
1454 } else {
1455 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1456 }
1457 }
1458
1459 bool Matches(unsigned ParmDepth) {
1460 if (ParmDepth >= Depth) {
1461 Match = true;
1462 return true;
1463 }
1464 return false;
1465 }
1466
1467 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1468 return !Matches(T->getDepth());
1469 }
1470
1471 bool TraverseTemplateName(TemplateName N) {
1472 if (TemplateTemplateParmDecl *PD =
1473 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1474 if (Matches(PD->getDepth())) return false;
1475 return super::TraverseTemplateName(N);
1476 }
1477
1478 bool VisitDeclRefExpr(DeclRefExpr *E) {
1479 if (NonTypeTemplateParmDecl *PD =
1480 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1481 if (PD->getDepth() == Depth) {
1482 Match = true;
1483 return false;
1484 }
1485 }
1486 return super::VisitDeclRefExpr(E);
1487 }
Douglas Gregor18c83392011-05-13 00:34:01 +00001488
1489 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1490 return TraverseType(T->getInjectedSpecializationType());
1491 }
John McCall4e2cbb22010-10-20 05:44:58 +00001492};
1493}
1494
Douglas Gregorc8406492011-05-10 18:27:06 +00001495/// Determines whether a given type depends on the given parameter
John McCall4e2cbb22010-10-20 05:44:58 +00001496/// list.
1497static bool
Douglas Gregorc8406492011-05-10 18:27:06 +00001498DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCall4e2cbb22010-10-20 05:44:58 +00001499 DependencyChecker Checker(Params);
Douglas Gregorc8406492011-05-10 18:27:06 +00001500 Checker.TraverseType(T);
John McCall4e2cbb22010-10-20 05:44:58 +00001501 return Checker.Match;
1502}
1503
Douglas Gregorc8406492011-05-10 18:27:06 +00001504// Find the source range corresponding to the named type in the given
1505// nested-name-specifier, if any.
1506static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1507 QualType T,
1508 const CXXScopeSpec &SS) {
1509 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1510 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1511 if (const Type *CurType = NNS->getAsType()) {
1512 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1513 return NNSLoc.getTypeLoc().getSourceRange();
1514 } else
1515 break;
1516
1517 NNSLoc = NNSLoc.getPrefix();
1518 }
1519
1520 return SourceRange();
1521}
1522
Mike Stump1eb44332009-09-09 15:08:12 +00001523/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001524/// specifier, returning the template parameter list that applies to the
1525/// name.
1526///
1527/// \param DeclStartLoc the start of the declaration that has a scope
1528/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001529///
Douglas Gregorc8406492011-05-10 18:27:06 +00001530/// \param DeclLoc The location of the declaration itself.
1531///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001532/// \param SS the scope specifier that will be matched to the given template
1533/// parameter lists. This scope specifier precedes a qualified name that is
1534/// being declared.
1535///
1536/// \param ParamLists the template parameter lists, from the outermost to the
1537/// innermost template parameter lists.
1538///
1539/// \param NumParamLists the number of template parameter lists in ParamLists.
1540///
John McCall77e8b112010-04-13 20:37:33 +00001541/// \param IsFriend Whether to apply the slightly different rules for
1542/// matching template parameters to scope specifiers in friend
1543/// declarations.
1544///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001545/// \param IsExplicitSpecialization will be set true if the entity being
1546/// declared is an explicit specialization, false otherwise.
1547///
Mike Stump1eb44332009-09-09 15:08:12 +00001548/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001549/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001550/// parameter list may have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001551/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001552/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001553/// itself a template).
1554TemplateParameterList *
1555Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
Douglas Gregorc8406492011-05-10 18:27:06 +00001556 SourceLocation DeclLoc,
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001557 const CXXScopeSpec &SS,
1558 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001559 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001560 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001561 bool &IsExplicitSpecialization,
1562 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001563 IsExplicitSpecialization = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001564 Invalid = false;
1565
1566 // The sequence of nested types to which we will match up the template
1567 // parameter lists. We first build this list by starting with the type named
1568 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001569 SmallVector<QualType, 4> NestedTypes;
Douglas Gregorc8406492011-05-10 18:27:06 +00001570 QualType T;
Douglas Gregor714c9922011-05-15 17:27:27 +00001571 if (SS.getScopeRep()) {
1572 if (CXXRecordDecl *Record
1573 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1574 T = Context.getTypeDeclType(Record);
1575 else
1576 T = QualType(SS.getScopeRep()->getAsType(), 0);
1577 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001578
1579 // If we found an explicit specialization that prevents us from needing
1580 // 'template<>' headers, this will be set to the location of that
1581 // explicit specialization.
1582 SourceLocation ExplicitSpecLoc;
1583
1584 while (!T.isNull()) {
1585 NestedTypes.push_back(T);
1586
1587 // Retrieve the parent of a record type.
1588 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1589 // If this type is an explicit specialization, we're done.
1590 if (ClassTemplateSpecializationDecl *Spec
1591 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1592 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1593 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1594 ExplicitSpecLoc = Spec->getLocation();
1595 break;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001596 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001597 } else if (Record->getTemplateSpecializationKind()
1598 == TSK_ExplicitSpecialization) {
1599 ExplicitSpecLoc = Record->getLocation();
John McCall77e8b112010-04-13 20:37:33 +00001600 break;
1601 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001602
1603 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1604 T = Context.getTypeDeclType(Parent);
1605 else
1606 T = QualType();
1607 continue;
1608 }
1609
1610 if (const TemplateSpecializationType *TST
1611 = T->getAs<TemplateSpecializationType>()) {
1612 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1613 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1614 T = Context.getTypeDeclType(Parent);
1615 else
1616 T = QualType();
1617 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001618 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001619 }
1620
1621 // Look one step prior in a dependent template specialization type.
1622 if (const DependentTemplateSpecializationType *DependentTST
1623 = T->getAs<DependentTemplateSpecializationType>()) {
1624 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1625 T = QualType(NNS->getAsType(), 0);
1626 else
1627 T = QualType();
1628 continue;
1629 }
1630
1631 // Look one step prior in a dependent name type.
1632 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1633 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1634 T = QualType(NNS->getAsType(), 0);
1635 else
1636 T = QualType();
1637 continue;
1638 }
1639
1640 // Retrieve the parent of an enumeration type.
1641 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1642 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1643 // check here.
1644 EnumDecl *Enum = EnumT->getDecl();
1645
1646 // Get to the parent type.
1647 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1648 T = Context.getTypeDeclType(Parent);
1649 else
1650 T = QualType();
1651 continue;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001652 }
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Douglas Gregorc8406492011-05-10 18:27:06 +00001654 T = QualType();
1655 }
1656 // Reverse the nested types list, since we want to traverse from the outermost
1657 // to the innermost while checking template-parameter-lists.
1658 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregorb88e8882009-07-30 17:40:51 +00001659
Douglas Gregorc8406492011-05-10 18:27:06 +00001660 // C++0x [temp.expl.spec]p17:
1661 // A member or a member template may be nested within many
1662 // enclosing class templates. In an explicit specialization for
1663 // such a member, the member declaration shall be preceded by a
1664 // template<> for each enclosing class template that is
1665 // explicitly specialized.
Douglas Gregor89b9f102011-06-06 15:22:55 +00001666 bool SawNonEmptyTemplateParameterList = false;
Douglas Gregorc8406492011-05-10 18:27:06 +00001667 unsigned ParamIdx = 0;
1668 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1669 ++TypeIdx) {
1670 T = NestedTypes[TypeIdx];
1671
1672 // Whether we expect a 'template<>' header.
1673 bool NeedEmptyTemplateHeader = false;
1674
1675 // Whether we expect a template header with parameters.
1676 bool NeedNonemptyTemplateHeader = false;
1677
1678 // For a dependent type, the set of template parameters that we
1679 // expect to see.
1680 TemplateParameterList *ExpectedTemplateParams = 0;
1681
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001682 // C++0x [temp.expl.spec]p15:
1683 // A member or a member template may be nested within many enclosing
1684 // class templates. In an explicit specialization for such a member, the
1685 // member declaration shall be preceded by a template<> for each
1686 // enclosing class template that is explicitly specialized.
Douglas Gregorc8406492011-05-10 18:27:06 +00001687 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1688 if (ClassTemplatePartialSpecializationDecl *Partial
1689 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1690 ExpectedTemplateParams = Partial->getTemplateParameters();
1691 NeedNonemptyTemplateHeader = true;
1692 } else if (Record->isDependentType()) {
1693 if (Record->getDescribedClassTemplate()) {
John McCall31f17ec2010-04-27 00:57:59 +00001694 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregorc8406492011-05-10 18:27:06 +00001695 ->getTemplateParameters();
1696 NeedNonemptyTemplateHeader = true;
1697 }
1698 } else if (ClassTemplateSpecializationDecl *Spec
1699 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1700 // C++0x [temp.expl.spec]p4:
1701 // Members of an explicitly specialized class template are defined
1702 // in the same manner as members of normal classes, and not using
1703 // the template<> syntax.
1704 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1705 NeedEmptyTemplateHeader = true;
1706 else
Douglas Gregor95ea4502011-06-01 22:37:07 +00001707 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001708 } else if (Record->getTemplateSpecializationKind()) {
1709 if (Record->getTemplateSpecializationKind()
Douglas Gregor175c5bb2011-05-11 23:26:17 +00001710 != TSK_ExplicitSpecialization &&
1711 TypeIdx == NumTypes - 1)
1712 IsExplicitSpecialization = true;
1713
1714 continue;
Douglas Gregorc8406492011-05-10 18:27:06 +00001715 }
1716 } else if (const TemplateSpecializationType *TST
1717 = T->getAs<TemplateSpecializationType>()) {
1718 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1719 ExpectedTemplateParams = Template->getTemplateParameters();
1720 NeedNonemptyTemplateHeader = true;
1721 }
1722 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1723 // FIXME: We actually could/should check the template arguments here
1724 // against the corresponding template parameter list.
1725 NeedNonemptyTemplateHeader = false;
1726 }
1727
Douglas Gregor89b9f102011-06-06 15:22:55 +00001728 // C++ [temp.expl.spec]p16:
1729 // In an explicit specialization declaration for a member of a class
1730 // template or a member template that ap- pears in namespace scope, the
1731 // member template and some of its enclosing class templates may remain
1732 // unspecialized, except that the declaration shall not explicitly
1733 // specialize a class member template if its en- closing class templates
1734 // are not explicitly specialized as well.
1735 if (ParamIdx < NumParamLists) {
1736 if (ParamLists[ParamIdx]->size() == 0) {
1737 if (SawNonEmptyTemplateParameterList) {
1738 Diag(DeclLoc, diag::err_specialize_member_of_template)
1739 << ParamLists[ParamIdx]->getSourceRange();
1740 Invalid = true;
1741 IsExplicitSpecialization = false;
1742 return 0;
1743 }
1744 } else
1745 SawNonEmptyTemplateParameterList = true;
1746 }
1747
Douglas Gregorc8406492011-05-10 18:27:06 +00001748 if (NeedEmptyTemplateHeader) {
1749 // If we're on the last of the types, and we need a 'template<>' header
1750 // here, then it's an explicit specialization.
1751 if (TypeIdx == NumTypes - 1)
1752 IsExplicitSpecialization = true;
1753
1754 if (ParamIdx < NumParamLists) {
1755 if (ParamLists[ParamIdx]->size() > 0) {
1756 // The header has template parameters when it shouldn't. Complain.
1757 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1758 diag::err_template_param_list_matches_nontemplate)
1759 << T
1760 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1761 ParamLists[ParamIdx]->getRAngleLoc())
1762 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1763 Invalid = true;
1764 return 0;
1765 }
1766
1767 // Consume this template header.
1768 ++ParamIdx;
1769 continue;
1770 }
1771
1772 if (!IsFriend) {
1773 // We don't have a template header, but we should.
1774 SourceLocation ExpectedTemplateLoc;
1775 if (NumParamLists > 0)
1776 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1777 else
1778 ExpectedTemplateLoc = DeclStartLoc;
1779
1780 Diag(DeclLoc, diag::err_template_spec_needs_header)
1781 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1782 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1783 }
1784
1785 continue;
1786 }
1787
1788 if (NeedNonemptyTemplateHeader) {
1789 // In friend declarations we can have template-ids which don't
1790 // depend on the corresponding template parameter lists. But
1791 // assume that empty parameter lists are supposed to match this
1792 // template-id.
1793 if (IsFriend && T->isDependentType()) {
1794 if (ParamIdx < NumParamLists &&
1795 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1796 ExpectedTemplateParams = 0;
1797 else
1798 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001799 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001800
Douglas Gregorc8406492011-05-10 18:27:06 +00001801 if (ParamIdx < NumParamLists) {
1802 // Check the template parameter list, if we can.
1803 if (ExpectedTemplateParams &&
1804 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1805 ExpectedTemplateParams,
1806 true, TPL_TemplateMatch))
1807 Invalid = true;
1808
1809 if (!Invalid &&
1810 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1811 TPC_ClassTemplateMember))
1812 Invalid = true;
1813
1814 ++ParamIdx;
1815 continue;
1816 }
1817
1818 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1819 << T
1820 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1821 Invalid = true;
1822 continue;
1823 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001824 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001825
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001826 // If there were at least as many template-ids as there were template
1827 // parameter lists, then there are no template parameter lists remaining for
1828 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001829 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001830 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001832 // If there were too many template parameter lists, complain about that now.
Douglas Gregorc8406492011-05-10 18:27:06 +00001833 if (ParamIdx < NumParamLists - 1) {
1834 bool HasAnyExplicitSpecHeader = false;
1835 bool AllExplicitSpecHeaders = true;
1836 for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1837 if (ParamLists[I]->size() == 0)
1838 HasAnyExplicitSpecHeader = true;
1839 else
1840 AllExplicitSpecHeaders = false;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001841 }
Douglas Gregorc8406492011-05-10 18:27:06 +00001842
1843 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1844 AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1845 : diag::err_template_spec_extra_headers)
1846 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1847 ParamLists[NumParamLists - 2]->getRAngleLoc());
1848
1849 // If there was a specialization somewhere, such that 'template<>' is
1850 // not required, and there were any 'template<>' headers, note where the
1851 // specialization occurred.
1852 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1853 Diag(ExplicitSpecLoc,
1854 diag::note_explicit_template_spec_does_not_need_header)
1855 << NestedTypes.back();
1856
1857 // We have a template parameter list with no corresponding scope, which
1858 // means that the resulting template declaration can't be instantiated
1859 // properly (we'll end up with dependent nodes when we shouldn't).
1860 if (!AllExplicitSpecHeaders)
1861 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001862 }
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Douglas Gregor89b9f102011-06-06 15:22:55 +00001864 // C++ [temp.expl.spec]p16:
1865 // In an explicit specialization declaration for a member of a class
1866 // template or a member template that ap- pears in namespace scope, the
1867 // member template and some of its enclosing class templates may remain
1868 // unspecialized, except that the declaration shall not explicitly
1869 // specialize a class member template if its en- closing class templates
1870 // are not explicitly specialized as well.
1871 if (ParamLists[NumParamLists - 1]->size() == 0 &&
1872 SawNonEmptyTemplateParameterList) {
1873 Diag(DeclLoc, diag::err_specialize_member_of_template)
1874 << ParamLists[ParamIdx]->getSourceRange();
1875 Invalid = true;
1876 IsExplicitSpecialization = false;
1877 return 0;
1878 }
1879
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001880 // Return the last template parameter list, which corresponds to the
1881 // entity being declared.
1882 return ParamLists[NumParamLists - 1];
1883}
1884
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001885void Sema::NoteAllFoundTemplates(TemplateName Name) {
1886 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1887 Diag(Template->getLocation(), diag::note_template_declared_here)
1888 << (isa<FunctionTemplateDecl>(Template)? 0
1889 : isa<ClassTemplateDecl>(Template)? 1
Richard Smith3e4c6c42011-05-05 21:57:07 +00001890 : isa<TypeAliasTemplateDecl>(Template)? 2
1891 : 3)
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001892 << Template->getDeclName();
1893 return;
1894 }
1895
1896 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1897 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1898 IEnd = OST->end();
1899 I != IEnd; ++I)
1900 Diag((*I)->getLocation(), diag::note_template_declared_here)
1901 << 0 << (*I)->getDeclName();
1902
1903 return;
1904 }
1905}
1906
Douglas Gregor7532dc62009-03-30 22:58:21 +00001907QualType Sema::CheckTemplateIdType(TemplateName Name,
1908 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00001909 TemplateArgumentListInfo &TemplateArgs) {
John McCall14606042011-06-30 08:33:18 +00001910 DependentTemplateName *DTN
1911 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001912 if (DTN && DTN->isIdentifier())
1913 // When building a template-id where the template-name is dependent,
1914 // assume the template is a type template. Either our assumption is
1915 // correct, or the code is ill-formed and will be diagnosed when the
1916 // dependent name is substituted.
1917 return Context.getDependentTemplateSpecializationType(ETK_None,
1918 DTN->getQualifier(),
1919 DTN->getIdentifier(),
1920 TemplateArgs);
1921
Douglas Gregor7532dc62009-03-30 22:58:21 +00001922 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001923 if (!Template || isa<FunctionTemplateDecl>(Template)) {
1924 // We might have a substituted template template parameter pack. If so,
1925 // build a template specialization type for it.
1926 if (Name.getAsSubstTemplateTemplateParmPack())
1927 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3e4c6c42011-05-05 21:57:07 +00001928
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +00001929 Diag(TemplateLoc, diag::err_template_id_not_a_type)
1930 << Name;
1931 NoteAllFoundTemplates(Name);
1932 return QualType();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001933 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001934
Douglas Gregor40808ce2009-03-09 23:48:35 +00001935 // Check that the template argument list is well-formed for this
1936 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001937 SmallVector<TemplateArgument, 4> Converted;
Douglas Gregorb70126a2012-02-03 17:16:23 +00001938 bool ExpansionIntoFixedList = false;
John McCalld5532b62009-11-23 01:53:49 +00001939 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregorb70126a2012-02-03 17:16:23 +00001940 false, Converted, &ExpansionIntoFixedList))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001941 return QualType();
1942
Douglas Gregor40808ce2009-03-09 23:48:35 +00001943 QualType CanonType;
1944
Douglas Gregor561f8122011-07-01 01:22:09 +00001945 bool InstantiationDependent = false;
Douglas Gregorb70126a2012-02-03 17:16:23 +00001946 TypeAliasTemplateDecl *AliasTemplate = 0;
1947 if (!ExpansionIntoFixedList &&
1948 (AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Template))) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00001949 // Find the canonical type for this type alias template specialization.
1950 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
1951 if (Pattern->isInvalidDecl())
1952 return QualType();
1953
1954 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1955 Converted.data(), Converted.size());
1956
1957 // Only substitute for the innermost template argument list.
1958 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith18041742011-05-14 15:04:18 +00001959 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smithaff37b42011-05-12 00:06:17 +00001960 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
1961 for (unsigned I = 0; I < Depth; ++I)
1962 TemplateArgLists.addOuterTemplateArguments(0, 0);
Richard Smith3e4c6c42011-05-05 21:57:07 +00001963
1964 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
1965 CanonType = SubstType(Pattern->getUnderlyingType(),
1966 TemplateArgLists, AliasTemplate->getLocation(),
1967 AliasTemplate->getDeclName());
1968 if (CanonType.isNull())
1969 return QualType();
1970 } else if (Name.isDependent() ||
1971 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor561f8122011-07-01 01:22:09 +00001972 TemplateArgs, InstantiationDependent)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001973 // This class template specialization is a dependent
1974 // type. Therefore, its canonical type is another class template
1975 // specialization type that contains all of the converted
1976 // arguments in canonical form. This ensures that, e.g., A<T> and
1977 // A<T, T> have identical types when A is declared as:
1978 //
1979 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001980 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001981 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001982 Converted.data(),
1983 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Douglas Gregor1275ae02009-07-28 23:00:59 +00001985 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001986 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001987 // In the future, we need to teach getTemplateSpecializationType to only
1988 // build the canonical type and return that to us.
1989 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001990
1991 // This might work out to be a current instantiation, in which
1992 // case the canonical type needs to be the InjectedClassNameType.
1993 //
1994 // TODO: in theory this could be a simple hashtable lookup; most
1995 // changes to CurContext don't change the set of current
1996 // instantiations.
1997 if (isa<ClassTemplateDecl>(Template)) {
1998 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1999 // If we get out to a namespace, we're done.
2000 if (Ctx->isFileContext()) break;
2001
2002 // If this isn't a record, keep looking.
2003 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2004 if (!Record) continue;
2005
2006 // Look for one of the two cases with InjectedClassNameTypes
2007 // and check whether it's the same template.
2008 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2009 !Record->getDescribedClassTemplate())
2010 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002011
John McCall31f17ec2010-04-27 00:57:59 +00002012 // Fetch the injected class name type and check whether its
2013 // injected type is equal to the type we just built.
2014 QualType ICNT = Context.getTypeDeclType(Record);
2015 QualType Injected = cast<InjectedClassNameType>(ICNT)
2016 ->getInjectedSpecializationType();
2017
2018 if (CanonType != Injected->getCanonicalTypeInternal())
2019 continue;
2020
2021 // If so, the canonical type of this TST is the injected
2022 // class name type of the record we just found.
2023 assert(ICNT.isCanonical());
2024 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00002025 break;
2026 }
2027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002029 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002030 // Find the class template specialization declaration that
2031 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002032 void *InsertPos = 0;
2033 ClassTemplateSpecializationDecl *Decl
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002034 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002035 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002036 if (!Decl) {
2037 // This is the first time we have referenced this class template
2038 // specialization. Create the canonical declaration and add it to
2039 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002040 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002041 ClassTemplate->getTemplatedDecl()->getTagKind(),
2042 ClassTemplate->getDeclContext(),
Abramo Bagnara09d82122011-10-03 20:34:03 +00002043 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002044 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002045 ClassTemplate,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002046 Converted.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002047 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002048 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002049 Decl->setLexicalDeclContext(CurContext);
2050 }
2051
2052 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00002053 assert(isa<RecordType>(CanonType) &&
2054 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00002055 }
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Douglas Gregor40808ce2009-03-09 23:48:35 +00002057 // Build the fully-sugared type for this class template
2058 // specialization, which refers back to the class template
2059 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00002060 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002061}
2062
John McCallf312b1e2010-08-26 23:41:50 +00002063TypeResult
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002064Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00002065 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002066 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002067 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002068 SourceLocation RAngleLoc,
2069 bool IsCtorOrDtorName) {
Douglas Gregor059101f2011-03-02 00:47:37 +00002070 if (SS.isInvalid())
2071 return true;
2072
Douglas Gregor7532dc62009-03-30 22:58:21 +00002073 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00002074
Douglas Gregor40808ce2009-03-09 23:48:35 +00002075 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00002076 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00002077 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002078
Douglas Gregora88f09f2011-02-28 17:23:35 +00002079 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002080 QualType T
2081 = Context.getDependentTemplateSpecializationType(ETK_None,
2082 DTN->getQualifier(),
2083 DTN->getIdentifier(),
2084 TemplateArgs);
2085 // Build type-source information.
Douglas Gregora88f09f2011-02-28 17:23:35 +00002086 TypeLocBuilder TLB;
2087 DependentTemplateSpecializationTypeLoc SpecTL
2088 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002089 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2090 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara66581d42012-02-06 22:45:07 +00002091 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002092 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregora88f09f2011-02-28 17:23:35 +00002093 SpecTL.setLAngleLoc(LAngleLoc);
2094 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregora88f09f2011-02-28 17:23:35 +00002095 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2096 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2097 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2098 }
2099
John McCalld5532b62009-11-23 01:53:49 +00002100 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002101 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00002102
2103 if (Result.isNull())
2104 return true;
2105
Douglas Gregor059101f2011-03-02 00:47:37 +00002106 // Build type-source information.
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002107 TypeLocBuilder TLB;
Douglas Gregor059101f2011-03-02 00:47:37 +00002108 TemplateSpecializationTypeLoc SpecTL
2109 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002110 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002111 SpecTL.setTemplateNameLoc(TemplateLoc);
2112 SpecTL.setLAngleLoc(LAngleLoc);
2113 SpecTL.setRAngleLoc(RAngleLoc);
2114 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2115 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall833ca992009-10-29 08:12:44 +00002116
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002117 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2118 // constructor or destructor name (in such a case, the scope specifier
2119 // will be attached to the enclosing Decl or Expr node).
2120 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor059101f2011-03-02 00:47:37 +00002121 // Create an elaborated-type-specifier containing the nested-name-specifier.
2122 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2123 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara38a42912012-02-06 19:09:27 +00002124 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor059101f2011-03-02 00:47:37 +00002125 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2126 }
2127
2128 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall6b2becf2009-09-08 17:47:29 +00002129}
John McCallf1bbbb42009-09-04 01:14:41 +00002130
Douglas Gregor059101f2011-03-02 00:47:37 +00002131TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallf312b1e2010-08-26 23:41:50 +00002132 TypeSpecifierType TagSpec,
Douglas Gregor059101f2011-03-02 00:47:37 +00002133 SourceLocation TagLoc,
2134 CXXScopeSpec &SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002135 SourceLocation TemplateKWLoc,
2136 TemplateTy TemplateD,
Douglas Gregor059101f2011-03-02 00:47:37 +00002137 SourceLocation TemplateLoc,
2138 SourceLocation LAngleLoc,
2139 ASTTemplateArgsPtr TemplateArgsIn,
2140 SourceLocation RAngleLoc) {
2141 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2142
2143 // Translate the parser's template argument list in our AST format.
2144 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2145 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2146
2147 // Determine the tag kind
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002148 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregor059101f2011-03-02 00:47:37 +00002149 ElaboratedTypeKeyword Keyword
2150 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Douglas Gregor059101f2011-03-02 00:47:37 +00002152 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2153 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2154 DTN->getQualifier(),
2155 DTN->getIdentifier(),
2156 TemplateArgs);
2157
2158 // Build type-source information.
2159 TypeLocBuilder TLB;
2160 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002161 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2162 SpecTL.setElaboratedKeywordLoc(TagLoc);
2163 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara66581d42012-02-06 22:45:07 +00002164 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002165 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002166 SpecTL.setLAngleLoc(LAngleLoc);
2167 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002168 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2169 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2170 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2171 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00002172
2173 if (TypeAliasTemplateDecl *TAT =
2174 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2175 // C++0x [dcl.type.elab]p2:
2176 // If the identifier resolves to a typedef-name or the simple-template-id
2177 // resolves to an alias template specialization, the
2178 // elaborated-type-specifier is ill-formed.
2179 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2180 Diag(TAT->getLocation(), diag::note_declared_at);
2181 }
Douglas Gregor059101f2011-03-02 00:47:37 +00002182
2183 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2184 if (Result.isNull())
Matt Beaumont-Gay3a51d412011-08-25 23:22:24 +00002185 return TypeResult(true);
Douglas Gregor059101f2011-03-02 00:47:37 +00002186
2187 // Check the tag kind
2188 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00002189 RecordDecl *D = RT->getDecl();
Douglas Gregor059101f2011-03-02 00:47:37 +00002190
John McCall6b2becf2009-09-08 17:47:29 +00002191 IdentifierInfo *Id = D->getIdentifier();
2192 assert(Id && "templated class must have an identifier");
Douglas Gregor059101f2011-03-02 00:47:37 +00002193
Richard Trieubbf34c02011-06-10 03:11:26 +00002194 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2195 TagLoc, *Id)) {
John McCall6b2becf2009-09-08 17:47:29 +00002196 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregor059101f2011-03-02 00:47:37 +00002197 << Result
Douglas Gregor849b2432010-03-31 17:46:05 +00002198 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00002199 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00002200 }
2201 }
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002202
Douglas Gregor059101f2011-03-02 00:47:37 +00002203 // Provide source-location information for the template specialization.
2204 TypeLocBuilder TLB;
2205 TemplateSpecializationTypeLoc SpecTL
2206 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002207 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002208 SpecTL.setTemplateNameLoc(TemplateLoc);
2209 SpecTL.setLAngleLoc(LAngleLoc);
2210 SpecTL.setRAngleLoc(RAngleLoc);
2211 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2212 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCallf1bbbb42009-09-04 01:14:41 +00002213
Douglas Gregor059101f2011-03-02 00:47:37 +00002214 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002215 // and tag keyword.
Douglas Gregor059101f2011-03-02 00:47:37 +00002216 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2217 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara38a42912012-02-06 19:09:27 +00002218 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00002219 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2220 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor55f6b142009-02-09 18:46:07 +00002221}
2222
John McCall60d7b3a2010-08-24 06:29:42 +00002223ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002224 SourceLocation TemplateKWLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00002225 LookupResult &R,
2226 bool RequiresADL,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002227 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002228 // FIXME: Can we do any checking at this point? I guess we could check the
2229 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00002230 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002231 // though.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002232 // foo<int> could identify a single function unambiguously
2233 // This approach does NOT work, since f<int>(1);
2234 // gets resolved prior to resorting to overload resolution
2235 // i.e., template<class T> void f(double);
2236 // vs template<class T, class U> void f(U);
John McCallf7a1a742009-11-24 19:00:30 +00002237
2238 // These should be filtered out by our callers.
2239 assert(!R.empty() && "empty lookup results when building templateid");
2240 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2241
John McCallc373d482010-01-27 01:50:18 +00002242 // We don't want lookup warnings at this point.
2243 R.suppressDiagnostics();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
John McCallf7a1a742009-11-24 19:00:30 +00002245 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002246 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002247 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002248 TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00002249 R.getLookupNameInfo(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002250 RequiresADL, TemplateArgs,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002251 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00002252
2253 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002254}
2255
John McCallf7a1a742009-11-24 19:00:30 +00002256// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00002257ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002258Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002259 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00002260 const DeclarationNameInfo &NameInfo,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002261 const TemplateArgumentListInfo *TemplateArgs) {
2262 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCallf7a1a742009-11-24 19:00:30 +00002263 DeclContext *DC;
2264 if (!(DC = computeDeclContext(SS, false)) ||
2265 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00002266 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002267 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002269 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00002270 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002271 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2272 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00002273
John McCallf7a1a742009-11-24 19:00:30 +00002274 if (R.isAmbiguous())
2275 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002276
John McCallf7a1a742009-11-24 19:00:30 +00002277 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002278 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2279 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002280 return ExprError();
2281 }
2282
2283 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002284 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2285 << (NestedNameSpecifier*) SS.getScopeRep()
2286 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002287 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2288 return ExprError();
2289 }
2290
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002291 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002292}
2293
Douglas Gregorc45c2322009-03-31 00:43:58 +00002294/// \brief Form a dependent template name.
2295///
2296/// This action forms a dependent template name given the template
2297/// name and its (presumably dependent) scope specifier. For
2298/// example, given "MetaFun::template apply", the scope specifier \p
2299/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2300/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002301TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002302 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002303 SourceLocation TemplateKWLoc,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002304 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00002305 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002306 bool EnteringContext,
2307 TemplateTy &Result) {
Richard Smithebaf0e62011-10-18 20:49:44 +00002308 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2309 Diag(TemplateKWLoc,
2310 getLangOptions().CPlusPlus0x ?
2311 diag::warn_cxx98_compat_template_outside_of_template :
2312 diag::ext_template_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002313 << FixItHint::CreateRemoval(TemplateKWLoc);
2314
Douglas Gregor0707bc52010-01-19 16:01:07 +00002315 DeclContext *LookupCtx = 0;
2316 if (SS.isSet())
2317 LookupCtx = computeDeclContext(SS, EnteringContext);
2318 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00002319 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00002320 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00002321 // C++0x [temp.names]p5:
2322 // If a name prefixed by the keyword template is not the name of
2323 // a template, the program is ill-formed. [Note: the keyword
2324 // template may not be applied to non-template members of class
2325 // templates. -end note ] [ Note: as is the case with the
2326 // typename prefix, the template prefix is allowed in cases
2327 // where it is not strictly necessary; i.e., when the
2328 // nested-name-specifier or the expression on the left of the ->
2329 // or . is not dependent on a template-parameter, or the use
2330 // does not appear in the scope of a template. -end note]
2331 //
2332 // Note: C++03 was more strict here, because it banned the use of
2333 // the "template" keyword prior to a template-name that was not a
2334 // dependent name. C++ DR468 relaxed this requirement (the
2335 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00002336 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002337 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00002338 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
2339 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002340 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00002341 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2342 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregord078bd22011-03-11 23:27:41 +00002343 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2344 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00002345 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002346 } else if (TNK == TNK_Non_template) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002347 Diag(Name.getLocStart(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002348 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002349 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002350 << Name.getSourceRange()
2351 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002352 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00002353 } else {
2354 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00002355 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002356 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00002357 }
2358
Mike Stump1eb44332009-09-09 15:08:12 +00002359 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002360 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002361
Douglas Gregor014e88d2009-11-03 23:16:33 +00002362 switch (Name.getKind()) {
2363 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002364 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregord6ab2322010-06-16 23:00:59 +00002365 Name.Identifier));
2366 return TNK_Dependent_template_name;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002367
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002368 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00002369 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002370 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00002371 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00002372
2373 case UnqualifiedId::IK_LiteralOperatorId:
David Blaikieb219cfc2011-09-23 05:06:16 +00002374 llvm_unreachable(
2375 "We don't support these; Parse shouldn't have allowed propagation");
Sean Hunte6252d12009-11-28 08:58:14 +00002376
Douglas Gregor014e88d2009-11-03 23:16:33 +00002377 default:
2378 break;
2379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002380
Daniel Dunbar96a00142012-03-09 18:35:03 +00002381 Diag(Name.getLocStart(),
Douglas Gregor014e88d2009-11-03 23:16:33 +00002382 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00002383 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00002384 << Name.getSourceRange()
2385 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00002386 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00002387}
2388
Mike Stump1eb44332009-09-09 15:08:12 +00002389bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00002390 const TemplateArgumentLoc &AL,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002391 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00002392 const TemplateArgument &Arg = AL.getArgument();
2393
Anders Carlsson436b1562009-06-13 00:33:33 +00002394 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002395 switch(Arg.getKind()) {
2396 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00002397 // C++ [temp.arg.type]p1:
2398 // A template-argument for a template-parameter which is a
2399 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002400 break;
2401 case TemplateArgument::Template: {
2402 // We have a template type parameter but the template argument
2403 // is a template without any arguments.
2404 SourceRange SR = AL.getSourceRange();
2405 TemplateName Name = Arg.getAsTemplate();
2406 Diag(SR.getBegin(), diag::err_template_missing_args)
2407 << Name << SR;
2408 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2409 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00002410
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002411 return true;
2412 }
2413 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00002414 // We have a template type parameter but the template argument
2415 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00002416 SourceRange SR = AL.getSourceRange();
2417 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00002418 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002419
Anders Carlsson436b1562009-06-13 00:33:33 +00002420 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002421 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00002422 }
Anders Carlsson436b1562009-06-13 00:33:33 +00002423
John McCalla93c9342009-12-07 02:54:59 +00002424 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00002425 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Anders Carlsson436b1562009-06-13 00:33:33 +00002427 // Add the converted template type argument.
Douglas Gregore559ca12011-06-17 22:11:49 +00002428 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
2429
2430 // Objective-C ARC:
2431 // If an explicitly-specified template argument type is a lifetime type
2432 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
2433 if (getLangOptions().ObjCAutoRefCount &&
2434 ArgType->isObjCLifetimeType() &&
2435 !ArgType.getObjCLifetime()) {
2436 Qualifiers Qs;
2437 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
2438 ArgType = Context.getQualifiedType(ArgType, Qs);
2439 }
2440
2441 Converted.push_back(TemplateArgument(ArgType));
Anders Carlsson436b1562009-06-13 00:33:33 +00002442 return false;
2443}
2444
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002445/// \brief Substitute template arguments into the default template argument for
2446/// the given template type parameter.
2447///
2448/// \param SemaRef the semantic analysis object for which we are performing
2449/// the substitution.
2450///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002451/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002452/// for.
2453///
2454/// \param TemplateLoc the location of the template name that started the
2455/// template-id we are checking.
2456///
2457/// \param RAngleLoc the location of the right angle bracket ('>') that
2458/// terminates the template-id.
2459///
2460/// \param Param the template template parameter whose default we are
2461/// substituting into.
2462///
2463/// \param Converted the list of template arguments provided for template
2464/// parameters that precede \p Param in the template parameter list.
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002465/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00002466static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002467SubstDefaultTemplateArgument(Sema &SemaRef,
2468 TemplateDecl *Template,
2469 SourceLocation TemplateLoc,
2470 SourceLocation RAngleLoc,
2471 TemplateTypeParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002472 SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00002473 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002474
2475 // If the argument type is dependent, instantiate it now based
2476 // on the previously-computed template arguments.
2477 if (ArgType->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002478 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002479 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002480
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002481 MultiLevelTemplateArgumentList AllTemplateArgs
2482 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2483
2484 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002485 Template, Converted.data(),
2486 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002487 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002488
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002489 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2490 Param->getDefaultArgumentLoc(),
2491 Param->getDeclName());
2492 }
2493
2494 return ArgType;
2495}
2496
2497/// \brief Substitute template arguments into the default template argument for
2498/// the given non-type template parameter.
2499///
2500/// \param SemaRef the semantic analysis object for which we are performing
2501/// the substitution.
2502///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002503/// \param Template the template that we are synthesizing template arguments
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002504/// for.
2505///
2506/// \param TemplateLoc the location of the template name that started the
2507/// template-id we are checking.
2508///
2509/// \param RAngleLoc the location of the right angle bracket ('>') that
2510/// terminates the template-id.
2511///
Douglas Gregor788cd062009-11-11 01:00:40 +00002512/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002513/// substituting into.
2514///
2515/// \param Converted the list of template arguments provided for template
2516/// parameters that precede \p Param in the template parameter list.
2517///
2518/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002519static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002520SubstDefaultTemplateArgument(Sema &SemaRef,
2521 TemplateDecl *Template,
2522 SourceLocation TemplateLoc,
2523 SourceLocation RAngleLoc,
2524 NonTypeTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002525 SmallVectorImpl<TemplateArgument> &Converted) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002526 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002527 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002528
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002529 MultiLevelTemplateArgumentList AllTemplateArgs
2530 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002531
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002532 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002533 Template, Converted.data(),
2534 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002535 SourceRange(TemplateLoc, RAngleLoc));
2536
2537 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2538}
2539
Douglas Gregor788cd062009-11-11 01:00:40 +00002540/// \brief Substitute template arguments into the default template argument for
2541/// the given template template parameter.
2542///
2543/// \param SemaRef the semantic analysis object for which we are performing
2544/// the substitution.
2545///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002546/// \param Template the template that we are synthesizing template arguments
Douglas Gregor788cd062009-11-11 01:00:40 +00002547/// for.
2548///
2549/// \param TemplateLoc the location of the template name that started the
2550/// template-id we are checking.
2551///
2552/// \param RAngleLoc the location of the right angle bracket ('>') that
2553/// terminates the template-id.
2554///
2555/// \param Param the template template parameter whose default we are
2556/// substituting into.
2557///
2558/// \param Converted the list of template arguments provided for template
2559/// parameters that precede \p Param in the template parameter list.
2560///
Douglas Gregor1d752d72011-03-02 18:46:51 +00002561/// \param QualifierLoc Will be set to the nested-name-specifier (with
2562/// source-location information) that precedes the template name.
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002563///
Douglas Gregor788cd062009-11-11 01:00:40 +00002564/// \returns the substituted template argument, or NULL if an error occurred.
2565static TemplateName
2566SubstDefaultTemplateArgument(Sema &SemaRef,
2567 TemplateDecl *Template,
2568 SourceLocation TemplateLoc,
2569 SourceLocation RAngleLoc,
2570 TemplateTemplateParmDecl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002571 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002572 NestedNameSpecifierLoc &QualifierLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002573 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002574 Converted.data(), Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002575
Douglas Gregor788cd062009-11-11 01:00:40 +00002576 MultiLevelTemplateArgumentList AllTemplateArgs
2577 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002578
Douglas Gregor788cd062009-11-11 01:00:40 +00002579 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002580 Template, Converted.data(),
2581 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002582 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002583
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002584 // Substitute into the nested-name-specifier first,
Douglas Gregor1d752d72011-03-02 18:46:51 +00002585 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002586 if (QualifierLoc) {
2587 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2588 AllTemplateArgs);
2589 if (!QualifierLoc)
2590 return TemplateName();
2591 }
2592
Douglas Gregor1d752d72011-03-02 18:46:51 +00002593 return SemaRef.SubstTemplateName(QualifierLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +00002594 Param->getDefaultArgument().getArgument().getAsTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595 Param->getDefaultArgument().getTemplateNameLoc(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002596 AllTemplateArgs);
2597}
2598
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002599/// \brief If the given template parameter has a default template
2600/// argument, substitute into that default template argument and
2601/// return the corresponding template argument.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002602TemplateArgumentLoc
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002603Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2604 SourceLocation TemplateLoc,
2605 SourceLocation RAngleLoc,
2606 Decl *Param,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002607 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002608 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002609 if (!TypeParm->hasDefaultArgument())
2610 return TemplateArgumentLoc();
2611
John McCalla93c9342009-12-07 02:54:59 +00002612 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002613 TemplateLoc,
2614 RAngleLoc,
2615 TypeParm,
2616 Converted);
2617 if (DI)
2618 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2619
2620 return TemplateArgumentLoc();
2621 }
2622
2623 if (NonTypeTemplateParmDecl *NonTypeParm
2624 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2625 if (!NonTypeParm->hasDefaultArgument())
2626 return TemplateArgumentLoc();
2627
John McCall60d7b3a2010-08-24 06:29:42 +00002628 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002629 TemplateLoc,
2630 RAngleLoc,
2631 NonTypeParm,
2632 Converted);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002633 if (Arg.isInvalid())
2634 return TemplateArgumentLoc();
2635
2636 Expr *ArgE = Arg.takeAs<Expr>();
2637 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2638 }
2639
2640 TemplateTemplateParmDecl *TempTempParm
2641 = cast<TemplateTemplateParmDecl>(Param);
2642 if (!TempTempParm->hasDefaultArgument())
2643 return TemplateArgumentLoc();
2644
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002645
Douglas Gregor1d752d72011-03-02 18:46:51 +00002646 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002647 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002648 TemplateLoc,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002649 RAngleLoc,
2650 TempTempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002651 Converted,
2652 QualifierLoc);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002653 if (TName.isNull())
2654 return TemplateArgumentLoc();
2655
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002657 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002658 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2659}
2660
Douglas Gregore7526412009-11-11 19:31:23 +00002661/// \brief Check that the given template argument corresponds to the given
2662/// template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002663///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002664/// \param Param The template parameter against which the argument will be
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002665/// checked.
2666///
2667/// \param Arg The template argument.
2668///
2669/// \param Template The template in which the template argument resides.
2670///
2671/// \param TemplateLoc The location of the template name for the template
2672/// whose argument list we're matching.
2673///
2674/// \param RAngleLoc The location of the right angle bracket ('>') that closes
2675/// the template argument list.
2676///
2677/// \param ArgumentPackIndex The index into the argument pack where this
2678/// argument will be placed. Only valid if the parameter is a parameter pack.
2679///
2680/// \param Converted The checked, converted argument will be added to the
2681/// end of this small vector.
2682///
2683/// \param CTAK Describes how we arrived at this particular template argument:
2684/// explicitly written, deduced, etc.
2685///
2686/// \returns true on error, false otherwise.
Douglas Gregore7526412009-11-11 19:31:23 +00002687bool Sema::CheckTemplateArgument(NamedDecl *Param,
2688 const TemplateArgumentLoc &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002689 NamedDecl *Template,
Douglas Gregore7526412009-11-11 19:31:23 +00002690 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002691 SourceLocation RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002692 unsigned ArgumentPackIndex,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002693 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002694 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002695 // Check template type parameters.
2696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002697 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002698
Douglas Gregord9e15302009-11-11 19:41:09 +00002699 // Check non-type template parameters.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002701 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002702 // with the template arguments we've seen thus far. But if the
2703 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002704 QualType NTTPType = NTTP->getType();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002705 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2706 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002707
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002708 if (NTTPType->isDependentType() &&
2709 !isa<TemplateTemplateParmDecl>(Template) &&
2710 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002711 // Do substitution on the type of the non-type template parameter.
2712 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002713 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002714 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715
2716 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002717 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002718 NTTPType = SubstType(NTTPType,
2719 MultiLevelTemplateArgumentList(TemplateArgs),
2720 NTTP->getLocation(),
2721 NTTP->getDeclName());
2722 // If that worked, check the non-type template parameter type
2723 // for validity.
2724 if (!NTTPType.isNull())
2725 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2726 NTTP->getLocation());
2727 if (NTTPType.isNull())
2728 return true;
2729 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002730
Douglas Gregore7526412009-11-11 19:31:23 +00002731 switch (Arg.getArgument().getKind()) {
2732 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002733 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002734
Douglas Gregore7526412009-11-11 19:31:23 +00002735 case TemplateArgument::Expression: {
Douglas Gregore7526412009-11-11 19:31:23 +00002736 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002737 ExprResult Res =
2738 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2739 Result, CTAK);
2740 if (Res.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002741 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002742
Douglas Gregor910f8002010-11-07 23:05:16 +00002743 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002744 break;
2745 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002746
Douglas Gregore7526412009-11-11 19:31:23 +00002747 case TemplateArgument::Declaration:
2748 case TemplateArgument::Integral:
2749 // We've already checked this template argument, so just copy
2750 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002751 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002752 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002753
Douglas Gregore7526412009-11-11 19:31:23 +00002754 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002755 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002756 // We were given a template template argument. It may not be ill-formed;
2757 // see below.
2758 if (DependentTemplateName *DTN
Douglas Gregora7fc9012011-01-05 18:58:31 +00002759 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2760 .getAsDependentTemplateName()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002761 // We have a template argument such as \c T::template X, which we
2762 // parsed as a template template argument. However, since we now
2763 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002764 // template name into an expression.
2765
2766 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2767 Arg.getTemplateNameLoc());
2768
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002769 CXXScopeSpec SS;
Douglas Gregorb6744ef2011-03-02 17:09:35 +00002770 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002771 // FIXME: the template-template arg was a DependentTemplateName,
2772 // so it was provided with a template keyword. However, its source
2773 // location is not stored in the template argument structure.
2774 SourceLocation TemplateKWLoc;
John Wiegley429bb272011-04-08 18:41:53 +00002775 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002776 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002777 TemplateKWLoc,
2778 NameInfo, 0));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002779
Douglas Gregora7fc9012011-01-05 18:58:31 +00002780 // If we parsed the template argument as a pack expansion, create a
2781 // pack expansion expression.
2782 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
John Wiegley429bb272011-04-08 18:41:53 +00002783 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2784 if (E.isInvalid())
Douglas Gregora7fc9012011-01-05 18:58:31 +00002785 return true;
Douglas Gregora7fc9012011-01-05 18:58:31 +00002786 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002787
Douglas Gregore7526412009-11-11 19:31:23 +00002788 TemplateArgument Result;
John Wiegley429bb272011-04-08 18:41:53 +00002789 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2790 if (E.isInvalid())
Douglas Gregore7526412009-11-11 19:31:23 +00002791 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002792
Douglas Gregor910f8002010-11-07 23:05:16 +00002793 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002794 break;
2795 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002796
Douglas Gregore7526412009-11-11 19:31:23 +00002797 // We have a template argument that actually does refer to a class
Richard Smith3e4c6c42011-05-05 21:57:07 +00002798 // template, alias template, or template template parameter, and
Douglas Gregore7526412009-11-11 19:31:23 +00002799 // therefore cannot be a non-type template argument.
2800 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2801 << Arg.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002802
Douglas Gregore7526412009-11-11 19:31:23 +00002803 Diag(Param->getLocation(), diag::note_template_param_here);
2804 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805
Douglas Gregore7526412009-11-11 19:31:23 +00002806 case TemplateArgument::Type: {
2807 // We have a non-type template parameter but the template
2808 // argument is a type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002809
Douglas Gregore7526412009-11-11 19:31:23 +00002810 // C++ [temp.arg]p2:
2811 // In a template-argument, an ambiguity between a type-id and
2812 // an expression is resolved to a type-id, regardless of the
2813 // form of the corresponding template-parameter.
2814 //
2815 // We warn specifically about this case, since it can be rather
2816 // confusing for users.
2817 QualType T = Arg.getArgument().getAsType();
2818 SourceRange SR = Arg.getSourceRange();
2819 if (T->isFunctionType())
2820 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2821 else
2822 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2823 Diag(Param->getLocation(), diag::note_template_param_here);
2824 return true;
2825 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002826
Douglas Gregore7526412009-11-11 19:31:23 +00002827 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002828 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002829 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830
Douglas Gregore7526412009-11-11 19:31:23 +00002831 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002832 }
2833
2834
Douglas Gregore7526412009-11-11 19:31:23 +00002835 // Check template template parameters.
2836 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002837
Douglas Gregore7526412009-11-11 19:31:23 +00002838 // Substitute into the template parameter list of the template
2839 // template parameter, since previously-supplied template arguments
2840 // may appear within the template template parameter.
2841 {
2842 // Set up a template instantiation context.
2843 LocalInstantiationScope Scope(*this);
2844 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002845 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002846 SourceRange(TemplateLoc, RAngleLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847
2848 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor910f8002010-11-07 23:05:16 +00002849 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002850 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002851 SubstDecl(TempParm, CurContext,
Douglas Gregore7526412009-11-11 19:31:23 +00002852 MultiLevelTemplateArgumentList(TemplateArgs)));
2853 if (!TempParm)
2854 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002855 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002856
Douglas Gregore7526412009-11-11 19:31:23 +00002857 switch (Arg.getArgument().getKind()) {
2858 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00002859 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002860
Douglas Gregore7526412009-11-11 19:31:23 +00002861 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002862 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002863 if (CheckTemplateArgument(TempParm, Arg))
2864 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002865
Douglas Gregor910f8002010-11-07 23:05:16 +00002866 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002867 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002868
Douglas Gregore7526412009-11-11 19:31:23 +00002869 case TemplateArgument::Expression:
2870 case TemplateArgument::Type:
2871 // We have a template template parameter but the template
2872 // argument does not refer to a template.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002873 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
2874 << getLangOptions().CPlusPlus0x;
Douglas Gregore7526412009-11-11 19:31:23 +00002875 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876
Douglas Gregore7526412009-11-11 19:31:23 +00002877 case TemplateArgument::Declaration:
David Blaikie7530c032012-01-17 06:56:22 +00002878 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregore7526412009-11-11 19:31:23 +00002879 case TemplateArgument::Integral:
David Blaikie7530c032012-01-17 06:56:22 +00002880 llvm_unreachable("Integral argument with template template parameter");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002881
Douglas Gregore7526412009-11-11 19:31:23 +00002882 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002883 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002884 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885
Douglas Gregore7526412009-11-11 19:31:23 +00002886 return false;
2887}
2888
Douglas Gregor8fbbae52012-02-03 07:34:46 +00002889/// \brief Diagnose an arity mismatch in the
2890static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
2891 SourceLocation TemplateLoc,
2892 TemplateArgumentListInfo &TemplateArgs) {
2893 TemplateParameterList *Params = Template->getTemplateParameters();
2894 unsigned NumParams = Params->size();
2895 unsigned NumArgs = TemplateArgs.size();
2896
2897 SourceRange Range;
2898 if (NumArgs > NumParams)
2899 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
2900 TemplateArgs.getRAngleLoc());
2901 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2902 << (NumArgs > NumParams)
2903 << (isa<ClassTemplateDecl>(Template)? 0 :
2904 isa<FunctionTemplateDecl>(Template)? 1 :
2905 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2906 << Template << Range;
2907 S.Diag(Template->getLocation(), diag::note_template_decl_here)
2908 << Params->getSourceRange();
2909 return true;
2910}
2911
Douglas Gregorc15cb382009-02-09 23:23:08 +00002912/// \brief Check that the given template argument list is well-formed
2913/// for specializing the given template.
2914bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2915 SourceLocation TemplateLoc,
Douglas Gregor67714232011-03-03 02:41:12 +00002916 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002917 bool PartialTemplateArgs,
Douglas Gregorb70126a2012-02-03 17:16:23 +00002918 SmallVectorImpl<TemplateArgument> &Converted,
2919 bool *ExpansionIntoFixedList) {
2920 if (ExpansionIntoFixedList)
2921 *ExpansionIntoFixedList = false;
2922
Douglas Gregorc15cb382009-02-09 23:23:08 +00002923 TemplateParameterList *Params = Template->getTemplateParameters();
2924 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002925 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002926 bool Invalid = false;
2927
John McCalld5532b62009-11-23 01:53:49 +00002928 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2929
Mike Stump1eb44332009-09-09 15:08:12 +00002930 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002931 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Douglas Gregorb70126a2012-02-03 17:16:23 +00002932
Mike Stump1eb44332009-09-09 15:08:12 +00002933 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002934 // [...] The type and form of each template-argument specified in
2935 // a template-id shall match the type and form specified for the
2936 // corresponding parameter declared by the template in its
2937 // template-parameter-list.
Douglas Gregor67714232011-03-03 02:41:12 +00002938 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002939 SmallVector<TemplateArgument, 2> ArgumentPack;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002940 TemplateParameterList::iterator Param = Params->begin(),
2941 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002942 unsigned ArgIdx = 0;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00002943 LocalInstantiationScope InstScope(*this, true);
Douglas Gregor8fbbae52012-02-03 07:34:46 +00002944 bool SawPackExpansion = false;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002945 while (Param != ParamEnd) {
Douglas Gregorf35f8282009-11-11 21:54:23 +00002946 if (ArgIdx < NumArgs) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002947 // If we have an expanded parameter pack, make sure we don't have too
2948 // many arguments.
Douglas Gregor8fbbae52012-02-03 07:34:46 +00002949 // FIXME: This really should fall out from the normal arity checking.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002950 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002951 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002952 if (NTTP->isExpandedParameterPack() &&
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002953 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
2954 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2955 << true
2956 << (isa<ClassTemplateDecl>(Template)? 0 :
2957 isa<FunctionTemplateDecl>(Template)? 1 :
2958 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2959 << Template;
2960 Diag(Template->getLocation(), diag::note_template_decl_here)
2961 << Params->getSourceRange();
2962 return true;
2963 }
2964 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002965
Douglas Gregorf35f8282009-11-11 21:54:23 +00002966 // Check the template argument we were given.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002967 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2968 TemplateLoc, RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002969 ArgumentPack.size(), Converted))
Douglas Gregorf35f8282009-11-11 21:54:23 +00002970 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002971
Douglas Gregor14be16b2010-12-20 16:57:52 +00002972 if ((*Param)->isTemplateParameterPack()) {
2973 // The template parameter was a template parameter pack, so take the
2974 // deduced argument and place it on the argument pack. Note that we
2975 // stay on the same template parameter so that we can deduce more
2976 // arguments.
2977 ArgumentPack.push_back(Converted.back());
2978 Converted.pop_back();
2979 } else {
2980 // Move to the next template parameter.
2981 ++Param;
2982 }
Douglas Gregor8fbbae52012-02-03 07:34:46 +00002983
2984 // If this template argument is a pack expansion, record that fact
2985 // and break out; we can't actually check any more.
2986 if (TemplateArgs[ArgIdx].getArgument().isPackExpansion()) {
2987 SawPackExpansion = true;
2988 ++ArgIdx;
2989 break;
2990 }
2991
Douglas Gregor14be16b2010-12-20 16:57:52 +00002992 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002993 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002994 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002995
Douglas Gregor8735b292011-06-03 02:59:40 +00002996 // If we're checking a partial template argument list, we're done.
2997 if (PartialTemplateArgs) {
2998 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
2999 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3000 ArgumentPack.data(),
3001 ArgumentPack.size()));
3002
3003 return Invalid;
3004 }
3005
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003006 // If we have a template parameter pack with no more corresponding
Douglas Gregor14be16b2010-12-20 16:57:52 +00003007 // arguments, just break out now and we'll fill in the argument pack below.
3008 if ((*Param)->isTemplateParameterPack())
3009 break;
Douglas Gregorf968d832011-05-27 01:19:52 +00003010
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003011 // Check whether we have a default argument.
Douglas Gregorf35f8282009-11-11 21:54:23 +00003012 TemplateArgumentLoc Arg;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003013
Douglas Gregorf35f8282009-11-11 21:54:23 +00003014 // Retrieve the default template argument from the template
3015 // parameter. For each kind of template parameter, we substitute the
3016 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017 // (when the template parameter was part of a nested template) into
Douglas Gregorf35f8282009-11-11 21:54:23 +00003018 // the default argument.
3019 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003020 if (!TTP->hasDefaultArgument())
3021 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3022 TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003023
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003024 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003025 Template,
3026 TemplateLoc,
3027 RAngleLoc,
3028 TTP,
3029 Converted);
3030 if (!ArgType)
3031 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003032
Douglas Gregorf35f8282009-11-11 21:54:23 +00003033 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3034 ArgType);
3035 } else if (NonTypeTemplateParmDecl *NTTP
3036 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003037 if (!NTTP->hasDefaultArgument())
3038 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3039 TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003040
John McCall60d7b3a2010-08-24 06:29:42 +00003041 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003042 TemplateLoc,
3043 RAngleLoc,
3044 NTTP,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003045 Converted);
3046 if (E.isInvalid())
3047 return true;
3048
3049 Expr *Ex = E.takeAs<Expr>();
3050 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3051 } else {
3052 TemplateTemplateParmDecl *TempParm
3053 = cast<TemplateTemplateParmDecl>(*Param);
3054
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003055 if (!TempParm->hasDefaultArgument())
3056 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3057 TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003058
Douglas Gregor1d752d72011-03-02 18:46:51 +00003059 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregorf35f8282009-11-11 21:54:23 +00003060 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003061 TemplateLoc,
3062 RAngleLoc,
Douglas Gregorf35f8282009-11-11 21:54:23 +00003063 TempParm,
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003064 Converted,
3065 QualifierLoc);
Douglas Gregorf35f8282009-11-11 21:54:23 +00003066 if (Name.isNull())
3067 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003068
Douglas Gregorb6744ef2011-03-02 17:09:35 +00003069 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3070 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregorf35f8282009-11-11 21:54:23 +00003071 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003072
Douglas Gregorf35f8282009-11-11 21:54:23 +00003073 // Introduce an instantiation record that describes where we are using
3074 // the default template argument.
3075 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00003076 Converted.data(), Converted.size(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003077 SourceRange(TemplateLoc, RAngleLoc));
3078
Douglas Gregorf35f8282009-11-11 21:54:23 +00003079 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00003080 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00003081 RAngleLoc, 0, Converted))
Douglas Gregore7526412009-11-11 19:31:23 +00003082 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003083
Douglas Gregor67714232011-03-03 02:41:12 +00003084 // Core issue 150 (assumed resolution): if this is a template template
3085 // parameter, keep track of the default template arguments from the
3086 // template definition.
3087 if (isTemplateTemplateParameter)
3088 TemplateArgs.addArgument(Arg);
3089
Douglas Gregor14be16b2010-12-20 16:57:52 +00003090 // Move to the next template parameter and argument.
3091 ++Param;
3092 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003093 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003094
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003095 // If we saw a pack expansion, then directly convert the remaining arguments,
3096 // because we don't know what parameters they'll match up with.
3097 if (SawPackExpansion) {
3098 bool AddToArgumentPack
3099 = Param != ParamEnd && (*Param)->isTemplateParameterPack();
3100 while (ArgIdx < NumArgs) {
3101 if (AddToArgumentPack)
3102 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3103 else
3104 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3105 ++ArgIdx;
3106 }
3107
3108 // Push the argument pack onto the list of converted arguments.
3109 if (AddToArgumentPack) {
3110 if (ArgumentPack.empty())
3111 Converted.push_back(TemplateArgument(0, 0));
3112 else {
3113 Converted.push_back(
3114 TemplateArgument::CreatePackCopy(Context,
3115 ArgumentPack.data(),
3116 ArgumentPack.size()));
3117 ArgumentPack.clear();
3118 }
Douglas Gregorb70126a2012-02-03 17:16:23 +00003119 } else if (ExpansionIntoFixedList) {
3120 // We have expanded a pack into a fixed list.
3121 *ExpansionIntoFixedList = true;
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003122 }
3123
3124 return Invalid;
3125 }
3126
3127 // If we have any leftover arguments, then there were too many arguments.
3128 // Complain and fail.
3129 if (ArgIdx < NumArgs)
3130 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3131
3132 // If we have an expanded parameter pack, make sure we don't have too
3133 // many arguments.
3134 // FIXME: This really should fall out from the normal arity checking.
3135 if (Param != ParamEnd) {
3136 if (NonTypeTemplateParmDecl *NTTP
3137 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3138 if (NTTP->isExpandedParameterPack() &&
3139 ArgumentPack.size() < NTTP->getNumExpansionTypes()) {
3140 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3141 << false
3142 << (isa<ClassTemplateDecl>(Template)? 0 :
3143 isa<FunctionTemplateDecl>(Template)? 1 :
3144 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3145 << Template;
3146 Diag(Template->getLocation(), diag::note_template_decl_here)
3147 << Params->getSourceRange();
3148 return true;
3149 }
3150 }
3151 }
3152
Douglas Gregor14be16b2010-12-20 16:57:52 +00003153 // Form argument packs for each of the parameter packs remaining.
3154 while (Param != ParamEnd) {
Douglas Gregord3731192011-01-10 07:32:04 +00003155 // If we're checking a partial list of template arguments, don't fill
3156 // in arguments for non-template parameter packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003157 if ((*Param)->isTemplateParameterPack()) {
David Blaikie1368e582011-10-19 05:19:50 +00003158 if (!HasParameterPack)
3159 return true;
Douglas Gregor8735b292011-06-03 02:59:40 +00003160 if (ArgumentPack.empty())
Douglas Gregor14be16b2010-12-20 16:57:52 +00003161 Converted.push_back(TemplateArgument(0, 0));
Douglas Gregor203e6a32011-01-11 23:09:57 +00003162 else {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3164 ArgumentPack.data(),
Douglas Gregor203e6a32011-01-11 23:09:57 +00003165 ArgumentPack.size()));
Douglas Gregor14be16b2010-12-20 16:57:52 +00003166 ArgumentPack.clear();
3167 }
Douglas Gregor8fbbae52012-02-03 07:34:46 +00003168 } else if (!PartialTemplateArgs)
3169 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003170
Douglas Gregor14be16b2010-12-20 16:57:52 +00003171 ++Param;
3172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173
Douglas Gregorc15cb382009-02-09 23:23:08 +00003174 return Invalid;
3175}
3176
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003177namespace {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003178 class UnnamedLocalNoLinkageFinder
3179 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003180 {
3181 Sema &S;
3182 SourceRange SR;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003184 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003185
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003186 public:
3187 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3188
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003189 bool Visit(QualType T) {
3190 return inherited::Visit(T.getTypePtr());
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003191 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003192
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003193#define TYPE(Class, Parent) \
3194 bool Visit##Class##Type(const Class##Type *);
3195#define ABSTRACT_TYPE(Class, Parent) \
3196 bool Visit##Class##Type(const Class##Type *) { return false; }
3197#define NON_CANONICAL_TYPE(Class, Parent) \
3198 bool Visit##Class##Type(const Class##Type *) { return false; }
3199#include "clang/AST/TypeNodes.def"
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003200
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003201 bool VisitTagDecl(const TagDecl *Tag);
3202 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3203 };
3204}
3205
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003206bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003207 return false;
3208}
3209
3210bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3211 return Visit(T->getElementType());
3212}
3213
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003215 return Visit(T->getPointeeType());
3216}
3217
3218bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219 const BlockPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003220 return Visit(T->getPointeeType());
3221}
3222
3223bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003224 const LValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003225 return Visit(T->getPointeeType());
3226}
3227
3228bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229 const RValueReferenceType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003230 return Visit(T->getPointeeType());
3231}
3232
3233bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003234 const MemberPointerType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003235 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3236}
3237
3238bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003239 const ConstantArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003240 return Visit(T->getElementType());
3241}
3242
3243bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003244 const IncompleteArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003245 return Visit(T->getElementType());
3246}
3247
3248bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003249 const VariableArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003250 return Visit(T->getElementType());
3251}
3252
3253bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003254 const DependentSizedArrayType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003255 return Visit(T->getElementType());
3256}
3257
3258bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259 const DependentSizedExtVectorType* T) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003260 return Visit(T->getElementType());
3261}
3262
3263bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3264 return Visit(T->getElementType());
3265}
3266
3267bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3268 return Visit(T->getElementType());
3269}
3270
3271bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3272 const FunctionProtoType* T) {
3273 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003274 AEnd = T->arg_type_end();
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003275 A != AEnd; ++A) {
3276 if (Visit(*A))
3277 return true;
3278 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003280 return Visit(T->getResultType());
3281}
3282
3283bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3284 const FunctionNoProtoType* T) {
3285 return Visit(T->getResultType());
3286}
3287
3288bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3289 const UnresolvedUsingType*) {
3290 return false;
3291}
3292
3293bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3294 return false;
3295}
3296
3297bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3298 return Visit(T->getUnderlyingType());
3299}
3300
3301bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3302 return false;
3303}
3304
Sean Huntca63c202011-05-24 22:41:36 +00003305bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3306 const UnaryTransformType*) {
3307 return false;
3308}
3309
Richard Smith34b41d92011-02-20 03:19:35 +00003310bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3311 return Visit(T->getDeducedType());
3312}
3313
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003314bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3315 return VisitTagDecl(T->getDecl());
3316}
3317
3318bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3319 return VisitTagDecl(T->getDecl());
3320}
3321
3322bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3323 const TemplateTypeParmType*) {
3324 return false;
3325}
3326
Douglas Gregorc3069d62011-01-14 02:55:32 +00003327bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3328 const SubstTemplateTypeParmPackType *) {
3329 return false;
3330}
3331
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003332bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3333 const TemplateSpecializationType*) {
3334 return false;
3335}
3336
3337bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3338 const InjectedClassNameType* T) {
3339 return VisitTagDecl(T->getDecl());
3340}
3341
3342bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3343 const DependentNameType* T) {
3344 return VisitNestedNameSpecifier(T->getQualifier());
3345}
3346
3347bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3348 const DependentTemplateSpecializationType* T) {
3349 return VisitNestedNameSpecifier(T->getQualifier());
3350}
3351
Douglas Gregor7536dd52010-12-20 02:24:11 +00003352bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3353 const PackExpansionType* T) {
3354 return Visit(T->getPattern());
3355}
3356
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003357bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3358 return false;
3359}
3360
3361bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3362 const ObjCInterfaceType *) {
3363 return false;
3364}
3365
3366bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3367 const ObjCObjectPointerType *) {
3368 return false;
3369}
3370
Eli Friedmanb001de72011-10-06 23:00:33 +00003371bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3372 return Visit(T->getValueType());
3373}
3374
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003375bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3376 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003377 S.Diag(SR.getBegin(),
3378 S.getLangOptions().CPlusPlus0x ?
3379 diag::warn_cxx98_compat_template_arg_local_type :
3380 diag::ext_template_arg_local_type)
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003381 << S.Context.getTypeDeclType(Tag) << SR;
3382 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003383 }
3384
Richard Smith162e1c12011-04-15 14:24:37 +00003385 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003386 S.Diag(SR.getBegin(),
3387 S.getLangOptions().CPlusPlus0x ?
3388 diag::warn_cxx98_compat_template_arg_unnamed_type :
3389 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003390 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3391 return true;
3392 }
3393
3394 return false;
3395}
3396
3397bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3398 NestedNameSpecifier *NNS) {
3399 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3400 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003402 switch (NNS->getKind()) {
3403 case NestedNameSpecifier::Identifier:
3404 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00003405 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003406 case NestedNameSpecifier::Global:
3407 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003408
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003409 case NestedNameSpecifier::TypeSpec:
3410 case NestedNameSpecifier::TypeSpecWithTemplate:
3411 return Visit(QualType(NNS->getAsType(), 0));
3412 }
David Blaikie7530c032012-01-17 06:56:22 +00003413 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003414}
3415
3416
Douglas Gregorc15cb382009-02-09 23:23:08 +00003417/// \brief Check a template argument against its corresponding
3418/// template type parameter.
3419///
3420/// This routine implements the semantics of C++ [temp.arg.type]. It
3421/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003422bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00003423 TypeSourceInfo *ArgInfo) {
3424 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00003425 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00003426 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00003427
3428 if (Arg->isVariablyModifiedType()) {
3429 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00003430 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00003431 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00003432 }
3433
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003434 // C++03 [temp.arg.type]p2:
3435 // A local type, a type with no linkage, an unnamed type or a type
3436 // compounded from any of these types shall not be used as a
3437 // template-argument for a template type-parameter.
3438 //
Richard Smithebaf0e62011-10-18 20:49:44 +00003439 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003440 // a warning.
Richard Smithebaf0e62011-10-18 20:49:44 +00003441 if (LangOpts.CPlusPlus0x ?
3442 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
3443 SR.getBegin()) != DiagnosticsEngine::Ignored ||
3444 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
3445 SR.getBegin()) != DiagnosticsEngine::Ignored :
3446 Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00003447 UnnamedLocalNoLinkageFinder Finder(*this, SR);
3448 (void)Finder.Visit(Context.getCanonicalType(Arg));
3449 }
3450
Douglas Gregorc15cb382009-02-09 23:23:08 +00003451 return false;
3452}
3453
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003454/// \brief Checks whether the given template argument is the address
3455/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003456static bool
Douglas Gregorb7a09262010-04-01 18:32:35 +00003457CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3458 NonTypeTemplateParmDecl *Param,
3459 QualType ParamType,
3460 Expr *ArgIn,
3461 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003462 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003463 Expr *Arg = ArgIn;
3464 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003465
3466 // See through any implicit casts we added to fix the type.
John McCall91a57552011-07-15 05:09:51 +00003467 Arg = Arg->IgnoreImpCasts();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003468
3469 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003470 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003471 // A template-argument for a non-type, non-template
3472 // template-parameter shall be one of: [...]
3473 //
3474 // -- the address of an object or function with external
3475 // linkage, including function templates and function
3476 // template-ids but excluding non-static class members,
3477 // expressed as & id-expression where the & is optional if
3478 // the name refers to a function or array, or if the
3479 // corresponding template-parameter is a reference; or
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003481 // In C++98/03 mode, give an extension warning on any extra parentheses.
3482 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3483 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003484 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003485 if (!Invalid && !ExtraParens) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003486 S.Diag(Arg->getLocStart(),
Richard Smithebaf0e62011-10-18 20:49:44 +00003487 S.getLangOptions().CPlusPlus0x ?
3488 diag::warn_cxx98_compat_template_arg_extra_parens :
3489 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003490 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003491 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003492 }
3493
3494 Arg = Parens->getSubExpr();
3495 }
3496
John McCall91a57552011-07-15 05:09:51 +00003497 while (SubstNonTypeTemplateParmExpr *subst =
3498 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3499 Arg = subst->getReplacement()->IgnoreImpCasts();
3500
Douglas Gregorb7a09262010-04-01 18:32:35 +00003501 bool AddressTaken = false;
3502 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003503 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003504 if (UnOp->getOpcode() == UO_AddrOf) {
John McCall91a57552011-07-15 05:09:51 +00003505 Arg = UnOp->getSubExpr();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003506 AddressTaken = true;
3507 AddrOpLoc = UnOp->getOperatorLoc();
3508 }
Francois Picheta343a412011-04-29 09:08:14 +00003509 }
John McCall91a57552011-07-15 05:09:51 +00003510
Francois Pichet62ec1f22011-09-17 17:15:52 +00003511 if (S.getLangOptions().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
John McCall91a57552011-07-15 05:09:51 +00003512 Converted = TemplateArgument(ArgIn);
3513 return false;
3514 }
3515
3516 while (SubstNonTypeTemplateParmExpr *subst =
3517 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3518 Arg = subst->getReplacement()->IgnoreImpCasts();
3519
3520 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003521 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003522 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3523 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003524 S.Diag(Param->getLocation(), diag::note_template_param_here);
3525 return true;
3526 }
Chandler Carruth038cc392010-01-31 10:01:20 +00003527
3528 // Stop checking the precise nature of the argument if it is value dependent,
3529 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00003530 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00003531 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00003532 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003533 }
Chandler Carruth038cc392010-01-31 10:01:20 +00003534
Douglas Gregorb7a09262010-04-01 18:32:35 +00003535 if (!isa<ValueDecl>(DRE->getDecl())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003536 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003537 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003538 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003539 S.Diag(Param->getLocation(), diag::note_template_param_here);
3540 return true;
3541 }
3542
3543 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003544
3545 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00003546 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003547 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003548 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003549 S.Diag(Param->getLocation(), diag::note_template_param_here);
3550 return true;
3551 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003552
3553 // Cannot refer to non-static member functions
3554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00003555 if (!Method->isStatic()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003556 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003557 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003558 S.Diag(Param->getLocation(), diag::note_template_param_here);
3559 return true;
3560 }
Mike Stump1eb44332009-09-09 15:08:12 +00003561
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003562 // Functions must have external linkage.
3563 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00003564 if (!isExternalLinkage(Func->getLinkage())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003565 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003566 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003567 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003568 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003569 << true;
3570 return true;
3571 }
3572
3573 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003574 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003575
Douglas Gregorb7a09262010-04-01 18:32:35 +00003576 // If the template parameter has pointer type, the function decays.
3577 if (ParamType->isPointerType() && !AddressTaken)
3578 ArgType = S.Context.getPointerType(Func->getType());
3579 else if (AddressTaken && ParamType->isReferenceType()) {
3580 // If we originally had an address-of operator, but the
3581 // parameter has reference type, complain and (if things look
3582 // like they will work) drop the address-of operator.
3583 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3584 ParamType.getNonReferenceType())) {
3585 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3586 << ParamType;
3587 S.Diag(Param->getLocation(), diag::note_template_param_here);
3588 return true;
3589 }
3590
3591 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3592 << ParamType
3593 << FixItHint::CreateRemoval(AddrOpLoc);
3594 S.Diag(Param->getLocation(), diag::note_template_param_here);
3595
3596 ArgType = Func->getType();
3597 }
3598 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00003599 if (!isExternalLinkage(Var->getLinkage())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003600 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003601 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003602 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003603 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003604 << true;
3605 return true;
3606 }
3607
Douglas Gregorb7a09262010-04-01 18:32:35 +00003608 // A value of reference type is not an object.
3609 if (Var->getType()->isReferenceType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003610 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003611 diag::err_template_arg_reference_var)
3612 << Var->getType() << Arg->getSourceRange();
3613 S.Diag(Param->getLocation(), diag::note_template_param_here);
3614 return true;
3615 }
3616
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003617 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003618 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003619
3620 // If the template parameter has pointer type, we must have taken
3621 // the address of this object.
3622 if (ParamType->isReferenceType()) {
3623 if (AddressTaken) {
3624 // If we originally had an address-of operator, but the
3625 // parameter has reference type, complain and (if things look
3626 // like they will work) drop the address-of operator.
3627 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3628 ParamType.getNonReferenceType())) {
3629 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3630 << ParamType;
3631 S.Diag(Param->getLocation(), diag::note_template_param_here);
3632 return true;
3633 }
3634
3635 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3636 << ParamType
3637 << FixItHint::CreateRemoval(AddrOpLoc);
3638 S.Diag(Param->getLocation(), diag::note_template_param_here);
3639
3640 ArgType = Var->getType();
3641 }
3642 } else if (!AddressTaken && ParamType->isPointerType()) {
3643 if (Var->getType()->isArrayType()) {
3644 // Array-to-pointer decay.
3645 ArgType = S.Context.getArrayDecayedType(Var->getType());
3646 } else {
3647 // If the template parameter has pointer type but the address of
3648 // this object was not taken, complain and (possibly) recover by
3649 // taking the address of the entity.
3650 ArgType = S.Context.getPointerType(Var->getType());
3651 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3652 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3653 << ParamType;
3654 S.Diag(Param->getLocation(), diag::note_template_param_here);
3655 return true;
3656 }
3657
3658 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3659 << ParamType
3660 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3661
3662 S.Diag(Param->getLocation(), diag::note_template_param_here);
3663 }
3664 }
3665 } else {
3666 // We found something else, but we don't know specifically what it is.
Daniel Dunbar96a00142012-03-09 18:35:03 +00003667 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003668 diag::err_template_arg_not_object_or_func)
3669 << Arg->getSourceRange();
3670 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3671 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003672 }
Mike Stump1eb44332009-09-09 15:08:12 +00003673
John McCallf85e1932011-06-15 23:02:42 +00003674 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003675 if (ParamType->isPointerType() &&
Douglas Gregorb7a09262010-04-01 18:32:35 +00003676 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
John McCallf85e1932011-06-15 23:02:42 +00003677 S.IsQualificationConversion(ArgType, ParamType, false,
3678 ObjCLifetimeConversion)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003679 // For pointer-to-object types, qualification conversions are
3680 // permitted.
3681 } else {
3682 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3683 if (!ParamRef->getPointeeType()->isFunctionType()) {
3684 // C++ [temp.arg.nontype]p5b3:
3685 // For a non-type template-parameter of type reference to
3686 // object, no conversions apply. The type referred to by the
3687 // reference may be more cv-qualified than the (otherwise
3688 // identical) type of the template- argument. The
3689 // template-parameter is bound directly to the
3690 // template-argument, which shall be an lvalue.
3691
3692 // FIXME: Other qualifiers?
3693 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3694 unsigned ArgQuals = ArgType.getCVRQualifiers();
3695
3696 if ((ParamQuals | ArgQuals) != ParamQuals) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003697 S.Diag(Arg->getLocStart(),
Douglas Gregorb7a09262010-04-01 18:32:35 +00003698 diag::err_template_arg_ref_bind_ignores_quals)
3699 << ParamType << Arg->getType()
3700 << Arg->getSourceRange();
3701 S.Diag(Param->getLocation(), diag::note_template_param_here);
3702 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003703 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00003704 }
3705 }
3706
3707 // At this point, the template argument refers to an object or
3708 // function with external linkage. We now need to check whether the
3709 // argument and parameter types are compatible.
3710 if (!S.Context.hasSameUnqualifiedType(ArgType,
3711 ParamType.getNonReferenceType())) {
3712 // We can't perform this conversion or binding.
3713 if (ParamType->isReferenceType())
3714 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
John McCall91a57552011-07-15 05:09:51 +00003715 << ParamType << ArgIn->getType() << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003716 else
3717 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
John McCall91a57552011-07-15 05:09:51 +00003718 << ArgIn->getType() << ParamType << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003719 S.Diag(Param->getLocation(), diag::note_template_param_here);
3720 return true;
3721 }
3722 }
3723
3724 // Create the template argument.
3725 Converted = TemplateArgument(Entity->getCanonicalDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +00003726 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003727 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003728}
3729
3730/// \brief Checks whether the given template argument is a pointer to
3731/// member constant according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003732bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
Douglas Gregorcaddba02009-11-12 18:38:13 +00003733 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003734 bool Invalid = false;
3735
3736 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003737 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003738 Arg = Cast->getSubExpr();
3739
3740 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003741 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003742 // A template-argument for a non-type, non-template
3743 // template-parameter shall be one of: [...]
3744 //
3745 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003746 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003747
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003748 // In C++98/03 mode, give an extension warning on any extra parentheses.
3749 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3750 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003751 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smithebaf0e62011-10-18 20:49:44 +00003752 if (!Invalid && !ExtraParens) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003753 Diag(Arg->getLocStart(),
Richard Smithebaf0e62011-10-18 20:49:44 +00003754 getLangOptions().CPlusPlus0x ?
3755 diag::warn_cxx98_compat_template_arg_extra_parens :
3756 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003757 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003758 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003759 }
3760
3761 Arg = Parens->getSubExpr();
3762 }
3763
John McCall91a57552011-07-15 05:09:51 +00003764 while (SubstNonTypeTemplateParmExpr *subst =
3765 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3766 Arg = subst->getReplacement()->IgnoreImpCasts();
3767
Douglas Gregorcaddba02009-11-12 18:38:13 +00003768 // A pointer-to-member constant written &Class::member.
3769 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003770 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003771 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3772 if (DRE && !DRE->getQualifier())
3773 DRE = 0;
3774 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003775 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003776 // A constant of pointer-to-member type.
3777 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3778 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3779 if (VD->getType()->isMemberPointerType()) {
3780 if (isa<NonTypeTemplateParmDecl>(VD) ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003781 (isa<VarDecl>(VD) &&
Douglas Gregorcaddba02009-11-12 18:38:13 +00003782 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3783 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003784 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003785 else
3786 Converted = TemplateArgument(VD->getCanonicalDecl());
3787 return Invalid;
3788 }
3789 }
3790 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003791
Douglas Gregorcaddba02009-11-12 18:38:13 +00003792 DRE = 0;
3793 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003794
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003795 if (!DRE)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003796 return Diag(Arg->getLocStart(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003797 diag::err_template_arg_not_pointer_to_member_form)
3798 << Arg->getSourceRange();
3799
3800 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3801 assert((isa<FieldDecl>(DRE->getDecl()) ||
3802 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3803 "Only non-static member pointers can make it here");
3804
3805 // Okay: this is the address of a non-static member, and therefore
3806 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003807 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003808 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003809 else
3810 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003811 return Invalid;
3812 }
3813
3814 // We found something else, but we don't know specifically what it is.
Daniel Dunbar96a00142012-03-09 18:35:03 +00003815 Diag(Arg->getLocStart(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003816 diag::err_template_arg_not_pointer_to_member_form)
3817 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003818 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003819 diag::note_template_arg_refers_here);
3820 return true;
3821}
3822
Douglas Gregorc15cb382009-02-09 23:23:08 +00003823/// \brief Check a template argument against its corresponding
3824/// non-type template parameter.
3825///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003826/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley429bb272011-04-08 18:41:53 +00003827/// If an error occurred, it returns ExprError(); otherwise, it
3828/// returns the converted template argument. \p
Douglas Gregor2943aed2009-03-03 04:44:36 +00003829/// InstantiatedParamType is the type of the non-type template
3830/// parameter after it has been instantiated.
John Wiegley429bb272011-04-08 18:41:53 +00003831ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3832 QualType InstantiatedParamType, Expr *Arg,
3833 TemplateArgument &Converted,
3834 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003835 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregor40808ce2009-03-09 23:48:35 +00003836
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003837 // If either the parameter has a dependent type or the argument is
3838 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003839 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3840 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003841 Converted = TemplateArgument(Arg);
John Wiegley429bb272011-04-08 18:41:53 +00003842 return Owned(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003843 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003844
3845 // C++ [temp.arg.nontype]p5:
3846 // The following conversions are performed on each expression used
3847 // as a non-type template-argument. If a non-type
3848 // template-argument cannot be converted to the type of the
3849 // corresponding template-parameter then the program is
3850 // ill-formed.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003851 QualType ParamType = InstantiatedParamType;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003852 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00003853 // C++11:
3854 // -- for a non-type template-parameter of integral or
3855 // enumeration type, conversions permitted in a converted
3856 // constant expression are applied.
3857 //
3858 // C++98:
3859 // -- for a non-type template-parameter of integral or
3860 // enumeration type, integral promotions (4.5) and integral
3861 // conversions (4.7) are applied.
3862
3863 if (CTAK == CTAK_Deduced &&
3864 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
3865 // C++ [temp.deduct.type]p17:
3866 // If, in the declaration of a function template with a non-type
3867 // template-parameter, the non-type template-parameter is used
3868 // in an expression in the function parameter-list and, if the
3869 // corresponding template-argument is deduced, the
3870 // template-argument type shall match the type of the
3871 // template-parameter exactly, except that a template-argument
3872 // deduced from an array bound may be of any integral type.
3873 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3874 << Arg->getType().getUnqualifiedType()
3875 << ParamType.getUnqualifiedType();
3876 Diag(Param->getLocation(), diag::note_template_param_here);
3877 return ExprError();
3878 }
3879
3880 if (getLangOptions().CPlusPlus0x) {
3881 // We can't check arbitrary value-dependent arguments.
3882 // FIXME: If there's no viable conversion to the template parameter type,
3883 // we should be able to diagnose that prior to instantiation.
3884 if (Arg->isValueDependent()) {
3885 Converted = TemplateArgument(Arg);
3886 return Owned(Arg);
3887 }
3888
3889 // C++ [temp.arg.nontype]p1:
3890 // A template-argument for a non-type, non-template template-parameter
3891 // shall be one of:
3892 //
3893 // -- for a non-type template-parameter of integral or enumeration
3894 // type, a converted constant expression of the type of the
3895 // template-parameter; or
3896 llvm::APSInt Value;
3897 ExprResult ArgResult =
3898 CheckConvertedConstantExpression(Arg, ParamType, Value,
3899 CCEK_TemplateArg);
3900 if (ArgResult.isInvalid())
3901 return ExprError();
3902
3903 // Widen the argument value to sizeof(parameter type). This is almost
3904 // always a no-op, except when the parameter type is bool. In
3905 // that case, this may extend the argument from 1 bit to 8 bits.
3906 QualType IntegerType = ParamType;
3907 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
3908 IntegerType = Enum->getDecl()->getIntegerType();
3909 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
3910
3911 Converted = TemplateArgument(Value, Context.getCanonicalType(ParamType));
3912 return ArgResult;
3913 }
3914
Richard Smith4f870622011-10-27 22:11:44 +00003915 ExprResult ArgResult = DefaultLvalueConversion(Arg);
3916 if (ArgResult.isInvalid())
3917 return ExprError();
3918 Arg = ArgResult.take();
3919
3920 QualType ArgType = Arg->getType();
3921
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003922 // C++ [temp.arg.nontype]p1:
3923 // A template-argument for a non-type, non-template
3924 // template-parameter shall be one of:
3925 //
3926 // -- an integral constant-expression of integral or enumeration
3927 // type; or
3928 // -- the name of a non-type template-parameter; or
3929 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003930 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003931 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003932 Diag(Arg->getLocStart(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003933 diag::err_template_arg_not_integral_or_enumeral)
3934 << ArgType << Arg->getSourceRange();
3935 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003936 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00003937 } else if (!Arg->isValueDependent()) {
3938 Arg = VerifyIntegerConstantExpression(Arg, &Value,
3939 PDiag(diag::err_template_arg_not_ice) << ArgType, false).take();
3940 if (!Arg)
3941 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003942 }
3943
Douglas Gregor02024a92010-03-28 02:42:43 +00003944 // From here on out, all we care about are the unqualified forms
3945 // of the parameter and argument types.
3946 ParamType = ParamType.getUnqualifiedType();
3947 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003948
3949 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003950 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003951 // Okay: no conversion necessary
John McCalldaa8e4e2010-11-15 09:13:47 +00003952 } else if (ParamType->isBooleanType()) {
3953 // This is an integral-to-boolean conversion.
John Wiegley429bb272011-04-08 18:41:53 +00003954 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003955 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3956 !ParamType->isEnumeralType()) {
3957 // This is an integral promotion or conversion.
John Wiegley429bb272011-04-08 18:41:53 +00003958 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003959 } else {
3960 // We can't perform this conversion.
Daniel Dunbar96a00142012-03-09 18:35:03 +00003961 Diag(Arg->getLocStart(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003962 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003963 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003964 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00003965 return ExprError();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003966 }
3967
Douglas Gregorc7469372011-05-04 21:55:00 +00003968 // Add the value of this argument to the list of converted
3969 // arguments. We use the bitwidth and signedness of the template
3970 // parameter.
3971 if (Arg->isValueDependent()) {
3972 // The argument is value-dependent. Create a new
3973 // TemplateArgument with the converted expression.
3974 Converted = TemplateArgument(Arg);
3975 return Owned(Arg);
3976 }
3977
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003978 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003979 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003980 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003981
Douglas Gregorc7469372011-05-04 21:55:00 +00003982 if (ParamType->isBooleanType()) {
3983 // Value must be zero or one.
3984 Value = Value != 0;
3985 unsigned AllowedBits = Context.getTypeSize(IntegerType);
3986 if (Value.getBitWidth() != AllowedBits)
3987 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00003988 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00003989 } else {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003990 llvm::APSInt OldValue = Value;
Douglas Gregorc7469372011-05-04 21:55:00 +00003991
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003992 // Coerce the template argument's value to the value it will have
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003993 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003994 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003995 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003996 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor575a1c92011-05-20 16:38:50 +00003997 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorc7469372011-05-04 21:55:00 +00003998
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003999 // Complain if an unsigned parameter received a negative value.
Douglas Gregor575a1c92011-05-20 16:38:50 +00004000 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorc7469372011-05-04 21:55:00 +00004001 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004002 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004003 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4004 << Arg->getSourceRange();
4005 Diag(Param->getLocation(), diag::note_template_param_here);
4006 }
Douglas Gregorc7469372011-05-04 21:55:00 +00004007
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004008 // Complain if we overflowed the template parameter's type.
4009 unsigned RequiredBits;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004010 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004011 RequiredBits = OldValue.getActiveBits();
4012 else if (OldValue.isUnsigned())
4013 RequiredBits = OldValue.getActiveBits() + 1;
4014 else
4015 RequiredBits = OldValue.getMinSignedBits();
4016 if (RequiredBits > AllowedBits) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004017 Diag(Arg->getLocStart(),
Douglas Gregor1a6e0342010-03-26 02:38:37 +00004018 diag::warn_template_arg_too_large)
4019 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4020 << Arg->getSourceRange();
4021 Diag(Param->getLocation(), diag::note_template_param_here);
4022 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00004023 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00004024
John McCall833ca992009-10-29 08:12:44 +00004025 Converted = TemplateArgument(Value,
Douglas Gregor6b63f552011-08-09 01:55:14 +00004026 ParamType->isEnumeralType()
4027 ? Context.getCanonicalType(ParamType)
4028 : IntegerType);
John Wiegley429bb272011-04-08 18:41:53 +00004029 return Owned(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00004030 }
Douglas Gregora35284b2009-02-11 00:19:33 +00004031
Richard Smith4f870622011-10-27 22:11:44 +00004032 QualType ArgType = Arg->getType();
John McCall6bb80172010-03-30 21:47:33 +00004033 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4034
Douglas Gregorb7a09262010-04-01 18:32:35 +00004035 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
4036 // from a template argument of type std::nullptr_t to a non-type
4037 // template parameter of type pointer to object, pointer to
4038 // function, or pointer-to-member, respectively.
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004039 if (ArgType->isNullPtrType()) {
4040 if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
4041 Converted = TemplateArgument((NamedDecl *)0);
4042 return Owned(Arg);
4043 }
4044
4045 if (ParamType->isNullPtrType()) {
4046 llvm::APSInt Zero(Context.getTypeSize(Context.NullPtrTy), true);
4047 Converted = TemplateArgument(Zero, Context.NullPtrTy);
4048 return Owned(Arg);
4049 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00004050 }
4051
Douglas Gregorb86b0572009-02-11 01:18:59 +00004052 // Handle pointer-to-function, reference-to-function, and
4053 // pointer-to-member-function all in (roughly) the same way.
4054 if (// -- For a non-type template-parameter of type pointer to
4055 // function, only the function-to-pointer conversion (4.3) is
4056 // applied. If the template-argument represents a set of
4057 // overloaded functions (or a pointer to such), the matching
4058 // function is selected from the set (13.4).
4059 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004060 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00004061 // -- For a non-type template-parameter of type reference to
4062 // function, no conversions apply. If the template-argument
4063 // represents a set of overloaded functions, the matching
4064 // function is selected from the set (13.4).
4065 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004066 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00004067 // -- For a non-type template-parameter of type pointer to
4068 // member function, no conversions apply. If the
4069 // template-argument represents a set of overloaded member
4070 // functions, the matching member function is selected from
4071 // the set (13.4).
4072 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004073 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00004074 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00004075
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004076 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004078 true,
4079 FoundResult)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004080 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00004081 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004082
4083 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4084 ArgType = Arg->getType();
4085 } else
John Wiegley429bb272011-04-08 18:41:53 +00004086 return ExprError();
Douglas Gregora35284b2009-02-11 00:19:33 +00004087 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004088
John Wiegley429bb272011-04-08 18:41:53 +00004089 if (!ParamType->isMemberPointerType()) {
4090 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4091 ParamType,
4092 Arg, Converted))
4093 return ExprError();
4094 return Owned(Arg);
4095 }
Douglas Gregorb7a09262010-04-01 18:32:35 +00004096
John McCallf85e1932011-06-15 23:02:42 +00004097 bool ObjCLifetimeConversion;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004098 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(),
John McCallf85e1932011-06-15 23:02:42 +00004099 false, ObjCLifetimeConversion)) {
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00004100 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp,
4101 Arg->getValueKind()).take();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004102 } else if (!Context.hasSameUnqualifiedType(ArgType,
4103 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00004104 // We can't perform this conversion.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004105 Diag(Arg->getLocStart(),
Douglas Gregora35284b2009-02-11 00:19:33 +00004106 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00004107 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00004108 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00004109 return ExprError();
Douglas Gregora35284b2009-02-11 00:19:33 +00004110 }
Mike Stump1eb44332009-09-09 15:08:12 +00004111
John Wiegley429bb272011-04-08 18:41:53 +00004112 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
4113 return ExprError();
4114 return Owned(Arg);
Douglas Gregora35284b2009-02-11 00:19:33 +00004115 }
4116
Chris Lattnerfe90de72009-02-20 21:37:53 +00004117 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00004118 // -- for a non-type template-parameter of type pointer to
4119 // object, qualification conversions (4.4) and the
4120 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004121 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00004122 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00004123 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004124
John Wiegley429bb272011-04-08 18:41:53 +00004125 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4126 ParamType,
4127 Arg, Converted))
4128 return ExprError();
4129 return Owned(Arg);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004130 }
Mike Stump1eb44332009-09-09 15:08:12 +00004131
Ted Kremenek6217b802009-07-29 21:53:49 +00004132 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00004133 // -- For a non-type template-parameter of type reference to
4134 // object, no conversions apply. The type referred to by the
4135 // reference may be more cv-qualified than the (otherwise
4136 // identical) type of the template-argument. The
4137 // template-parameter is bound directly to the
4138 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00004139 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00004140 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00004141
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004142 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004143 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
4144 ParamRefType->getPointeeType(),
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004145 true,
4146 FoundResult)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004147 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00004148 return ExprError();
Douglas Gregor1a8cf732010-04-14 23:11:21 +00004149
4150 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4151 ArgType = Arg->getType();
4152 } else
John Wiegley429bb272011-04-08 18:41:53 +00004153 return ExprError();
Douglas Gregorb86b0572009-02-11 01:18:59 +00004154 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004155
John Wiegley429bb272011-04-08 18:41:53 +00004156 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4157 ParamType,
4158 Arg, Converted))
4159 return ExprError();
4160 return Owned(Arg);
Douglas Gregorb86b0572009-02-11 01:18:59 +00004161 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00004162
4163 // -- For a non-type template-parameter of type pointer to data
4164 // member, qualification conversions (4.4) are applied.
4165 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4166
John McCallf85e1932011-06-15 23:02:42 +00004167 bool ObjCLifetimeConversion;
Douglas Gregor8e6563b2009-02-11 18:22:40 +00004168 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00004169 // Types match exactly: nothing more to do here.
John McCallf85e1932011-06-15 23:02:42 +00004170 } else if (IsQualificationConversion(ArgType, ParamType, false,
4171 ObjCLifetimeConversion)) {
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00004172 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp,
4173 Arg->getValueKind()).take();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004174 } else {
4175 // We can't perform this conversion.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004176 Diag(Arg->getLocStart(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00004177 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00004178 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004179 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley429bb272011-04-08 18:41:53 +00004180 return ExprError();
Douglas Gregor658bbb52009-02-11 16:16:59 +00004181 }
4182
John Wiegley429bb272011-04-08 18:41:53 +00004183 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
4184 return ExprError();
4185 return Owned(Arg);
Douglas Gregorc15cb382009-02-09 23:23:08 +00004186}
4187
4188/// \brief Check a template argument against its corresponding
4189/// template template parameter.
4190///
4191/// This routine implements the semantics of C++ [temp.arg.template].
4192/// It returns true if an error occurred, and false otherwise.
4193bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00004194 const TemplateArgumentLoc &Arg) {
4195 TemplateName Name = Arg.getArgument().getAsTemplate();
4196 TemplateDecl *Template = Name.getAsTemplateDecl();
4197 if (!Template) {
4198 // Any dependent template name is fine.
4199 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
4200 return false;
4201 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00004202
Richard Smith3e4c6c42011-05-05 21:57:07 +00004203 // C++0x [temp.arg.template]p1:
Douglas Gregordd0574e2009-02-10 00:24:35 +00004204 // A template-argument for a template template-parameter shall be
Richard Smith3e4c6c42011-05-05 21:57:07 +00004205 // the name of a class template or an alias template, expressed as an
4206 // id-expression. When the template-argument names a class template, only
Douglas Gregordd0574e2009-02-10 00:24:35 +00004207 // primary class templates are considered when matching the
4208 // template template argument with the corresponding parameter;
4209 // partial specializations are not considered even if their
4210 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004211 //
4212 // Note that we also allow template template parameters here, which
4213 // will happen when we are dealing with, e.g., class template
4214 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00004215 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00004216 !isa<TemplateTemplateParmDecl>(Template) &&
4217 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004218 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00004219 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00004220 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00004221 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00004222 << Template;
4223 }
4224
4225 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
4226 Param->getTemplateParameters(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004227 true,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004228 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00004229 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00004230}
4231
Douglas Gregor02024a92010-03-28 02:42:43 +00004232/// \brief Given a non-type template argument that refers to a
4233/// declaration and the type of its corresponding non-type template
4234/// parameter, produce an expression that properly refers to that
4235/// declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004237Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4238 QualType ParamType,
4239 SourceLocation Loc) {
4240 assert(Arg.getKind() == TemplateArgument::Declaration &&
4241 "Only declaration template arguments permitted here");
4242 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4243
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244 if (VD->getDeclContext()->isRecord() &&
Douglas Gregor02024a92010-03-28 02:42:43 +00004245 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4246 // If the value is a class member, we might have a pointer-to-member.
4247 // Determine whether the non-type template template parameter is of
4248 // pointer-to-member type. If so, we need to build an appropriate
4249 // expression for a pointer-to-member, since a "normal" DeclRefExpr
4250 // would refer to the member itself.
4251 if (ParamType->isMemberPointerType()) {
4252 QualType ClassType
4253 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4254 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00004255 = NestedNameSpecifier::Create(Context, 0, false,
4256 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00004257 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00004258 SS.MakeTrivial(Context, Qualifier, Loc);
John McCalldfa1edb2010-11-23 20:48:44 +00004259
4260 // The actual value-ness of this is unimportant, but for
4261 // internal consistency's sake, references to instance methods
4262 // are r-values.
4263 ExprValueKind VK = VK_LValue;
4264 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4265 VK = VK_RValue;
4266
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00004268 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00004269 VK,
John McCallf89e55a2010-11-18 06:31:45 +00004270 Loc,
4271 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00004272 if (RefExpr.isInvalid())
4273 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274
John McCall2de56d12010-08-25 11:45:40 +00004275 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004276
Douglas Gregorc0c83002010-04-30 21:46:38 +00004277 // We might need to perform a trailing qualification conversion, since
4278 // the element type on the parameter could be more qualified than the
4279 // element type in the expression we constructed.
John McCallf85e1932011-06-15 23:02:42 +00004280 bool ObjCLifetimeConversion;
Douglas Gregorc0c83002010-04-30 21:46:38 +00004281 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCallf85e1932011-06-15 23:02:42 +00004282 ParamType.getUnqualifiedType(), false,
4283 ObjCLifetimeConversion))
John Wiegley429bb272011-04-08 18:41:53 +00004284 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285
Douglas Gregor02024a92010-03-28 02:42:43 +00004286 assert(!RefExpr.isInvalid() &&
4287 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00004288 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00004289 return move(RefExpr);
4290 }
4291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292
Douglas Gregor02024a92010-03-28 02:42:43 +00004293 QualType T = VD->getType().getNonReferenceType();
4294 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00004295 // When the non-type template parameter is a pointer, take the
4296 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00004297 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004298 if (RefExpr.isInvalid())
4299 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004300
4301 if (T->isFunctionType() || T->isArrayType()) {
4302 // Decay functions and arrays.
John Wiegley429bb272011-04-08 18:41:53 +00004303 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4304 if (RefExpr.isInvalid())
4305 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00004306
4307 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00004308 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309
Douglas Gregorb7a09262010-04-01 18:32:35 +00004310 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00004311 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00004312 }
4313
John McCallf89e55a2010-11-18 06:31:45 +00004314 ExprValueKind VK = VK_RValue;
4315
Douglas Gregor02024a92010-03-28 02:42:43 +00004316 // If the non-type template parameter has reference type, qualify the
4317 // resulting declaration reference with the extra qualifiers on the
4318 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00004319 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4320 VK = VK_LValue;
4321 T = Context.getQualifiedType(T,
4322 TargetRef->getPointeeType().getQualifiers());
4323 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004324
John McCallf89e55a2010-11-18 06:31:45 +00004325 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00004326}
4327
4328/// \brief Construct a new expression that refers to the given
4329/// integral template argument with the given source-location
4330/// information.
4331///
4332/// This routine takes care of the mapping from an integral template
4333/// argument (which may have any integral type) to the appropriate
4334/// literal value.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004335ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00004336Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4337 SourceLocation Loc) {
4338 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregord3731192011-01-10 07:32:04 +00004339 "Operation is only valid for integral template arguments");
Douglas Gregor02024a92010-03-28 02:42:43 +00004340 QualType T = Arg.getIntegralType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00004341 if (T->isAnyCharacterType()) {
4342 CharacterLiteral::CharacterKind Kind;
4343 if (T->isWideCharType())
4344 Kind = CharacterLiteral::Wide;
4345 else if (T->isChar16Type())
4346 Kind = CharacterLiteral::UTF16;
4347 else if (T->isChar32Type())
4348 Kind = CharacterLiteral::UTF32;
4349 else
4350 Kind = CharacterLiteral::Ascii;
4351
Douglas Gregor02024a92010-03-28 02:42:43 +00004352 return Owned(new (Context) CharacterLiteral(
Douglas Gregor5cee1192011-07-27 05:40:30 +00004353 Arg.getAsIntegral()->getZExtValue(),
4354 Kind, T, Loc));
4355 }
4356
Douglas Gregor02024a92010-03-28 02:42:43 +00004357 if (T->isBooleanType())
4358 return Owned(new (Context) CXXBoolLiteralExpr(
4359 Arg.getAsIntegral()->getBoolValue(),
Chris Lattner223de242011-04-25 20:37:58 +00004360 T, Loc));
Douglas Gregor02024a92010-03-28 02:42:43 +00004361
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004362 if (T->isNullPtrType())
4363 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
4364
Chris Lattner223de242011-04-25 20:37:58 +00004365 // If this is an enum type that we're instantiating, we need to use an integer
4366 // type the same size as the enumerator. We don't want to build an
4367 // IntegerLiteral with enum type.
Peter Collingbournefb7b3632010-12-15 15:06:14 +00004368 QualType BT;
4369 if (const EnumType *ET = T->getAs<EnumType>())
Chris Lattner223de242011-04-25 20:37:58 +00004370 BT = ET->getDecl()->getIntegerType();
Peter Collingbournefb7b3632010-12-15 15:06:14 +00004371 else
4372 BT = T;
4373
John McCall4e9272d2011-07-15 07:47:58 +00004374 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
4375 if (T->isEnumeralType()) {
4376 // FIXME: This is a hack. We need a better way to handle substituted
4377 // non-type template parameters.
4378 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0,
4379 Context.getTrivialTypeSourceInfo(T, Loc),
4380 Loc, Loc);
4381 }
4382
4383 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00004384}
4385
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004386/// \brief Match two template parameters within template parameter lists.
4387static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4388 bool Complain,
4389 Sema::TemplateParameterListEqualKind Kind,
4390 SourceLocation TemplateArgLoc) {
4391 // Check the actual kind (type, non-type, template).
4392 if (Old->getKind() != New->getKind()) {
4393 if (Complain) {
4394 unsigned NextDiag = diag::err_template_param_different_kind;
4395 if (TemplateArgLoc.isValid()) {
4396 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4397 NextDiag = diag::note_template_param_different_kind;
4398 }
4399 S.Diag(New->getLocation(), NextDiag)
4400 << (Kind != Sema::TPL_TemplateMatch);
4401 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4402 << (Kind != Sema::TPL_TemplateMatch);
4403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004404
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004405 return false;
4406 }
4407
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004408 // Check that both are parameter packs are neither are parameter packs.
4409 // However, if we are matching a template template argument to a
Douglas Gregora0347822011-01-13 00:08:50 +00004410 // template template parameter, the template template parameter can have
4411 // a parameter pack where the template template argument does not.
4412 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4413 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4414 Old->isTemplateParameterPack())) {
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004415 if (Complain) {
4416 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4417 if (TemplateArgLoc.isValid()) {
4418 S.Diag(TemplateArgLoc,
4419 diag::err_template_arg_template_params_mismatch);
4420 NextDiag = diag::note_template_parameter_pack_non_pack;
4421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004423 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4424 : isa<NonTypeTemplateParmDecl>(New)? 1
4425 : 2;
4426 S.Diag(New->getLocation(), NextDiag)
4427 << ParamKind << New->isParameterPack();
4428 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4429 << ParamKind << Old->isParameterPack();
4430 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004431
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004432 return false;
4433 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004435 // For non-type template parameters, check the type of the parameter.
4436 if (NonTypeTemplateParmDecl *OldNTTP
4437 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4438 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004440 // If we are matching a template template argument to a template
4441 // template parameter and one of the non-type template parameter types
4442 // is dependent, then we must wait until template instantiation time
4443 // to actually compare the arguments.
4444 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4445 (OldNTTP->getType()->isDependentType() ||
4446 NewNTTP->getType()->isDependentType()))
4447 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004448
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004449 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4450 if (Complain) {
4451 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4452 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004453 S.Diag(TemplateArgLoc,
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004454 diag::err_template_arg_template_params_mismatch);
4455 NextDiag = diag::note_template_nontype_parm_different_type;
4456 }
4457 S.Diag(NewNTTP->getLocation(), NextDiag)
4458 << NewNTTP->getType()
4459 << (Kind != Sema::TPL_TemplateMatch);
4460 S.Diag(OldNTTP->getLocation(),
4461 diag::note_template_nontype_parm_prev_declaration)
4462 << OldNTTP->getType();
4463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004464
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004465 return false;
4466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004468 return true;
4469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004470
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004471 // For template template parameters, check the template parameter types.
4472 // The template parameter lists of template template
4473 // parameters must agree.
4474 if (TemplateTemplateParmDecl *OldTTP
4475 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004476 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004477 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4478 OldTTP->getTemplateParameters(),
4479 Complain,
4480 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004482 : Kind),
4483 TemplateArgLoc);
4484 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004485
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004486 return true;
4487}
Douglas Gregor02024a92010-03-28 02:42:43 +00004488
Douglas Gregora0347822011-01-13 00:08:50 +00004489/// \brief Diagnose a known arity mismatch when comparing template argument
4490/// lists.
4491static
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregora0347822011-01-13 00:08:50 +00004493 TemplateParameterList *New,
4494 TemplateParameterList *Old,
4495 Sema::TemplateParameterListEqualKind Kind,
4496 SourceLocation TemplateArgLoc) {
4497 unsigned NextDiag = diag::err_template_param_list_different_arity;
4498 if (TemplateArgLoc.isValid()) {
4499 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4500 NextDiag = diag::note_template_param_list_different_arity;
4501 }
4502 S.Diag(New->getTemplateLoc(), NextDiag)
4503 << (New->size() > Old->size())
4504 << (Kind != Sema::TPL_TemplateMatch)
4505 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4506 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4507 << (Kind != Sema::TPL_TemplateMatch)
4508 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4509}
4510
Douglas Gregorddc29e12009-02-06 22:42:48 +00004511/// \brief Determine whether the given template parameter lists are
4512/// equivalent.
4513///
Mike Stump1eb44332009-09-09 15:08:12 +00004514/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00004515/// source code as part of a new template declaration.
4516///
4517/// \param Old The old template parameter list, typically found via
4518/// name lookup of the template declared with this template parameter
4519/// list.
4520///
4521/// \param Complain If true, this routine will produce a diagnostic if
4522/// the template parameter lists are not equivalent.
4523///
Douglas Gregorfb898e12009-11-12 16:20:59 +00004524/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00004525///
4526/// \param TemplateArgLoc If this source location is valid, then we
4527/// are actually checking the template parameter list of a template
4528/// argument (New) against the template parameter list of its
4529/// corresponding template template parameter (Old). We produce
4530/// slightly different diagnostics in this scenario.
4531///
Douglas Gregorddc29e12009-02-06 22:42:48 +00004532/// \returns True if the template parameter lists are equal, false
4533/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00004534bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00004535Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4536 TemplateParameterList *Old,
4537 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00004538 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00004539 SourceLocation TemplateArgLoc) {
Douglas Gregora0347822011-01-13 00:08:50 +00004540 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4541 if (Complain)
4542 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4543 TemplateArgLoc);
Douglas Gregorddc29e12009-02-06 22:42:48 +00004544
4545 return false;
4546 }
4547
Douglas Gregorab7ddf02011-01-12 23:45:44 +00004548 // C++0x [temp.arg.template]p3:
4549 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004550 // when each of the template parameters in the template-parameter-list of
Richard Smith3e4c6c42011-05-05 21:57:07 +00004551 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004552 // (call it A) matches the corresponding template parameter in the
Douglas Gregora0347822011-01-13 00:08:50 +00004553 // template-parameter-list of P. [...]
4554 TemplateParameterList::iterator NewParm = New->begin();
4555 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004556 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregora0347822011-01-13 00:08:50 +00004557 OldParmEnd = Old->end();
4558 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregorc421f542011-01-13 18:47:47 +00004559 if (Kind != TPL_TemplateTemplateArgumentMatch ||
4560 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregora0347822011-01-13 00:08:50 +00004561 if (NewParm == NewParmEnd) {
4562 if (Complain)
4563 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4564 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565
Douglas Gregora0347822011-01-13 00:08:50 +00004566 return false;
4567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568
Douglas Gregora0347822011-01-13 00:08:50 +00004569 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4570 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004571 return false;
4572
Douglas Gregora0347822011-01-13 00:08:50 +00004573 ++NewParm;
4574 continue;
4575 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004576
Douglas Gregora0347822011-01-13 00:08:50 +00004577 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004578 // [...] When P's template- parameter-list contains a template parameter
4579 // pack (14.5.3), the template parameter pack will match zero or more
4580 // template parameters or template parameter packs in the
Douglas Gregora0347822011-01-13 00:08:50 +00004581 // template-parameter-list of A with the same type and form as the
4582 // template parameter pack in P (ignoring whether those template
4583 // parameters are template parameter packs).
4584 for (; NewParm != NewParmEnd; ++NewParm) {
4585 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4586 Kind, TemplateArgLoc))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004587 return false;
Douglas Gregora0347822011-01-13 00:08:50 +00004588 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00004589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004590
Douglas Gregora0347822011-01-13 00:08:50 +00004591 // Make sure we exhausted all of the arguments.
4592 if (NewParm != NewParmEnd) {
4593 if (Complain)
4594 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4595 TemplateArgLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004596
Douglas Gregora0347822011-01-13 00:08:50 +00004597 return false;
4598 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004599
Douglas Gregorddc29e12009-02-06 22:42:48 +00004600 return true;
4601}
4602
4603/// \brief Check whether a template can be declared within this scope.
4604///
4605/// If the template declaration is valid in this scope, returns
4606/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00004607bool
Douglas Gregor05396e22009-08-25 17:23:04 +00004608Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorfb35e8f2011-11-03 16:37:14 +00004609 if (!S)
4610 return false;
4611
Douglas Gregorddc29e12009-02-06 22:42:48 +00004612 // Find the nearest enclosing declaration scope.
4613 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4614 (S->getFlags() & Scope::TemplateParamScope) != 0)
4615 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004616
Douglas Gregorddc29e12009-02-06 22:42:48 +00004617 // C++ [temp]p2:
4618 // A template-declaration can appear only as a namespace scope or
4619 // class scope declaration.
4620 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00004621 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4622 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00004623 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00004624 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004625
Eli Friedman1503f772009-07-31 01:43:05 +00004626 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00004627 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004628
4629 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4630 return false;
4631
Mike Stump1eb44332009-09-09 15:08:12 +00004632 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004633 diag::err_template_outside_namespace_or_class_scope)
4634 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00004635}
Douglas Gregorcc636682009-02-17 23:15:12 +00004636
Douglas Gregord5cb8762009-10-07 00:13:32 +00004637/// \brief Determine what kind of template specialization the given declaration
4638/// is.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00004639static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004640 if (!D)
4641 return TSK_Undeclared;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004642
Douglas Gregorf6b11852009-10-08 15:14:33 +00004643 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4644 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00004645 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4646 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004647 if (VarDecl *Var = dyn_cast<VarDecl>(D))
4648 return Var->getTemplateSpecializationKind();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004649
Douglas Gregord5cb8762009-10-07 00:13:32 +00004650 return TSK_Undeclared;
4651}
4652
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004653/// \brief Check whether a specialization is well-formed in the current
Douglas Gregor9302da62009-10-14 23:50:59 +00004654/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00004655///
Douglas Gregor9302da62009-10-14 23:50:59 +00004656/// This routine determines whether a template specialization can be declared
4657/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004658///
4659/// \param S the semantic analysis object for which this check is being
4660/// performed.
4661///
4662/// \param Specialized the entity being specialized or instantiated, which
4663/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004664/// a member of a class template (member function, static data member,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004665/// member class).
4666///
4667/// \param PrevDecl the previous declaration of this entity, if any.
4668///
4669/// \param Loc the location of the explicit specialization or instantiation of
4670/// this entity.
4671///
4672/// \param IsPartialSpecialization whether this is a partial specialization of
4673/// a class template.
4674///
Douglas Gregord5cb8762009-10-07 00:13:32 +00004675/// \returns true if there was an error that we cannot recover from, false
4676/// otherwise.
4677static bool CheckTemplateSpecializationScope(Sema &S,
4678 NamedDecl *Specialized,
4679 NamedDecl *PrevDecl,
4680 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00004681 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004682 // Keep these "kind" numbers in sync with the %select statements in the
4683 // various diagnostics emitted by this routine.
4684 int EntityKind = 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004685 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004686 EntityKind = IsPartialSpecialization? 1 : 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004687 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004688 EntityKind = 2;
Ted Kremenekfe62b062011-01-14 22:31:36 +00004689 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004690 EntityKind = 3;
4691 else if (isa<VarDecl>(Specialized))
4692 EntityKind = 4;
4693 else if (isa<RecordDecl>(Specialized))
4694 EntityKind = 5;
4695 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00004696 S.Diag(Loc, diag::err_template_spec_unknown_kind);
4697 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00004698 return true;
4699 }
4700
Douglas Gregor88b70942009-02-25 22:02:03 +00004701 // C++ [temp.expl.spec]p2:
4702 // An explicit specialization shall be declared in the namespace
4703 // of which the template is a member, or, for member templates, in
4704 // the namespace of which the enclosing class or enclosing class
4705 // template is a member. An explicit specialization of a member
4706 // function, member class or static data member of a class
4707 // template shall be declared in the namespace of which the class
4708 // template is a member. Such a declaration may also be a
4709 // definition. If the declaration is not a definition, the
4710 // specialization may be defined later in the name- space in which
4711 // the explicit specialization was declared, or in a namespace
4712 // that encloses the one in which the explicit specialization was
4713 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004714 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004715 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00004716 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00004717 return true;
4718 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004719
Douglas Gregor0a407472009-10-07 17:30:37 +00004720 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
Francois Pichet62ec1f22011-09-17 17:15:52 +00004721 if (S.getLangOptions().MicrosoftExt) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004722 // Do not warn for class scope explicit specialization during
4723 // instantiation, warning was already emitted during pattern
4724 // semantic analysis.
4725 if (!S.ActiveTemplateInstantiations.size())
4726 S.Diag(Loc, diag::ext_function_specialization_in_class)
4727 << Specialized;
4728 } else {
4729 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4730 << Specialized;
4731 return true;
4732 }
Douglas Gregor0a407472009-10-07 17:30:37 +00004733 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004734
Douglas Gregor8e0c1182011-10-20 16:41:18 +00004735 if (S.CurContext->isRecord() &&
4736 !S.CurContext->Equals(Specialized->getDeclContext())) {
4737 // Make sure that we're specializing in the right record context.
4738 // Otherwise, things can go horribly wrong.
4739 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4740 << Specialized;
4741 return true;
4742 }
4743
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004744 // C++ [temp.class.spec]p6:
4745 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004746 // in any namespace scope in which its definition may be defined (14.5.1
4747 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004748 bool ComplainedAboutScope = false;
Douglas Gregor8e0c1182011-10-20 16:41:18 +00004749 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00004750 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004751 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004752 if ((!PrevDecl ||
Douglas Gregor9302da62009-10-14 23:50:59 +00004753 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4754 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004755 // C++ [temp.exp.spec]p2:
4756 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004757 // the template is a member, or, for member templates, in the namespace
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004758 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004759 // An explicit specialization of a member function, member class or
4760 // static data member of a class template shall be declared in the
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004761 // namespace of which the class template is a member.
4762 //
4763 // C++0x [temp.expl.spec]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004764 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004765 // the specialized template.
Richard Smithebaf0e62011-10-18 20:49:44 +00004766 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
4767 bool IsCPlusPlus0xExtension = DC->Encloses(SpecializedContext);
4768 if (isa<TranslationUnitDecl>(SpecializedContext)) {
4769 assert(!IsCPlusPlus0xExtension &&
4770 "DC encloses TU but isn't in enclosing namespace set");
4771 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregora4d5de52010-09-12 05:24:55 +00004772 << EntityKind << Specialized;
Richard Smithebaf0e62011-10-18 20:49:44 +00004773 } else if (isa<NamespaceDecl>(SpecializedContext)) {
4774 int Diag;
4775 if (!IsCPlusPlus0xExtension)
4776 Diag = diag::err_template_spec_decl_out_of_scope;
4777 else if (!S.getLangOptions().CPlusPlus0x)
4778 Diag = diag::ext_template_spec_decl_out_of_scope;
4779 else
4780 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
4781 S.Diag(Loc, Diag)
4782 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
4783 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004784
Douglas Gregor9302da62009-10-14 23:50:59 +00004785 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Richard Smithebaf0e62011-10-18 20:49:44 +00004786 ComplainedAboutScope =
4787 !(IsCPlusPlus0xExtension && S.getLangOptions().CPlusPlus0x);
Douglas Gregor88b70942009-02-25 22:02:03 +00004788 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004789 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004790
4791 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00004792 // namespace.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004793 // Note that HandleDeclarator() performs this check for explicit
Douglas Gregord5cb8762009-10-07 00:13:32 +00004794 // specializations of function templates, static data members, and member
4795 // functions, so we skip the check here for those kinds of entities.
4796 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004797 // Should we refactor that check, so that it occurs later?
4798 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00004799 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4800 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004801 if (isa<TranslationUnitDecl>(SpecializedContext))
4802 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4803 << EntityKind << Specialized;
4804 else if (isa<NamespaceDecl>(SpecializedContext))
4805 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4806 << EntityKind << Specialized
4807 << cast<NamedDecl>(SpecializedContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004808
Douglas Gregor9302da62009-10-14 23:50:59 +00004809 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00004810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004811
Douglas Gregord5cb8762009-10-07 00:13:32 +00004812 // FIXME: check for specialization-after-instantiation errors and such.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004813
Douglas Gregor88b70942009-02-25 22:02:03 +00004814 return false;
4815}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004816
Douglas Gregorbacb9492011-01-03 21:13:47 +00004817/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4818/// that checks non-type template partial specialization arguments.
4819static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4820 NonTypeTemplateParmDecl *Param,
4821 const TemplateArgument *Args,
4822 unsigned NumArgs) {
4823 for (unsigned I = 0; I != NumArgs; ++I) {
4824 if (Args[I].getKind() == TemplateArgument::Pack) {
4825 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004826 Args[I].pack_begin(),
Douglas Gregorbacb9492011-01-03 21:13:47 +00004827 Args[I].pack_size()))
4828 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004829
Douglas Gregore94866f2009-06-12 21:21:02 +00004830 continue;
Douglas Gregorbacb9492011-01-03 21:13:47 +00004831 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004832
Douglas Gregorbacb9492011-01-03 21:13:47 +00004833 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004834 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004835 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004836 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004837
Douglas Gregor7a21fd42011-01-03 21:37:45 +00004838 // We can have a pack expansion of any of the bullets below.
Douglas Gregorbacb9492011-01-03 21:13:47 +00004839 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4840 ArgExpr = Expansion->getPattern();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004841
4842 // Strip off any implicit casts we added as part of type checking.
4843 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4844 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004845
Douglas Gregore94866f2009-06-12 21:21:02 +00004846 // C++ [temp.class.spec]p8:
4847 // A non-type argument is non-specialized if it is the name of a
4848 // non-type parameter. All other non-type arguments are
4849 // specialized.
4850 //
4851 // Below, we check the two conditions that only apply to
4852 // specialized non-type arguments, so skip any non-specialized
4853 // arguments.
4854 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004855 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00004856 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004857
Douglas Gregore94866f2009-06-12 21:21:02 +00004858 // C++ [temp.class.spec]p9:
4859 // Within the argument list of a class template partial
4860 // specialization, the following restrictions apply:
4861 // -- A partially specialized non-type argument expression
4862 // shall not involve a template parameter of the partial
4863 // specialization except when the argument expression is a
4864 // simple identifier.
4865 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004866 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004867 diag::err_dependent_non_type_arg_in_partial_spec)
4868 << ArgExpr->getSourceRange();
4869 return true;
4870 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004871
Douglas Gregore94866f2009-06-12 21:21:02 +00004872 // -- The type of a template parameter corresponding to a
4873 // specialized non-type argument shall not be dependent on a
4874 // parameter of the specialization.
4875 if (Param->getType()->isDependentType()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004876 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004877 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4878 << Param->getType()
4879 << ArgExpr->getSourceRange();
Douglas Gregorbacb9492011-01-03 21:13:47 +00004880 S.Diag(Param->getLocation(), diag::note_template_param_here);
Douglas Gregore94866f2009-06-12 21:21:02 +00004881 return true;
4882 }
4883 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004884
Douglas Gregorbacb9492011-01-03 21:13:47 +00004885 return false;
4886}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004887
Douglas Gregorbacb9492011-01-03 21:13:47 +00004888/// \brief Check the non-type template arguments of a class template
4889/// partial specialization according to C++ [temp.class.spec]p9.
4890///
4891/// \param TemplateParams the template parameters of the primary class
4892/// template.
4893///
4894/// \param TemplateArg the template arguments of the class template
4895/// partial specialization.
4896///
4897/// \returns true if there was an error, false otherwise.
4898static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4899 TemplateParameterList *TemplateParams,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004900 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004901 const TemplateArgument *ArgList = TemplateArgs.data();
4902
4903 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4904 NonTypeTemplateParmDecl *Param
4905 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4906 if (!Param)
4907 continue;
4908
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004909 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
Douglas Gregorbacb9492011-01-03 21:13:47 +00004910 &ArgList[I], 1))
4911 return true;
4912 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004913
4914 return false;
4915}
4916
John McCalld226f652010-08-21 09:40:31 +00004917DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004918Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4919 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004920 SourceLocation KWLoc,
Douglas Gregord023aec2011-09-09 20:53:38 +00004921 SourceLocation ModulePrivateLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004922 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004923 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004924 SourceLocation TemplateNameLoc,
4925 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004926 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004927 SourceLocation RAngleLoc,
4928 AttributeList *Attr,
4929 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004930 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004931
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004932 // NOTE: KWLoc is the location of the tag keyword. This will instead
4933 // store the location of the outermost template keyword in the declaration.
4934 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
4935 ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation();
4936
Douglas Gregorcc636682009-02-17 23:15:12 +00004937 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004938 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004939 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004940 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4941
4942 if (!ClassTemplate) {
4943 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004944 << (Name.getAsTemplateDecl() &&
Douglas Gregor8b13c082009-11-12 00:46:20 +00004945 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4946 return true;
4947 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004948
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004949 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004950 bool isPartialSpecialization = false;
4951
Douglas Gregor88b70942009-02-25 22:02:03 +00004952 // Check the validity of the template headers that introduce this
4953 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004954 // FIXME: We probably shouldn't complain about these headers for
4955 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004956 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004957 TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00004958 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
4959 TemplateNameLoc,
4960 SS,
Mike Stump1eb44332009-09-09 15:08:12 +00004961 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004962 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004963 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004964 isExplicitSpecialization,
4965 Invalid);
4966 if (Invalid)
4967 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004968
Douglas Gregor05396e22009-08-25 17:23:04 +00004969 if (TemplateParams && TemplateParams->size() > 0) {
4970 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004971
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004972 if (TUK == TUK_Friend) {
4973 Diag(KWLoc, diag::err_partial_specialization_friend)
4974 << SourceRange(LAngleLoc, RAngleLoc);
4975 return true;
4976 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004977
Douglas Gregor05396e22009-08-25 17:23:04 +00004978 // C++ [temp.class.spec]p10:
4979 // The template parameter list of a specialization shall not
4980 // contain default template argument values.
4981 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4982 Decl *Param = TemplateParams->getParam(I);
4983 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4984 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004985 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004986 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004987 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004988 }
4989 } else if (NonTypeTemplateParmDecl *NTTP
4990 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4991 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004992 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004993 diag::err_default_arg_in_partial_spec)
4994 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004995 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004996 }
4997 } else {
4998 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004999 if (TTP->hasDefaultArgument()) {
5000 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00005001 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00005002 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00005003 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00005004 }
5005 }
5006 }
Douglas Gregora735b202009-10-13 14:39:41 +00005007 } else if (TemplateParams) {
5008 if (TUK == TUK_Friend)
5009 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00005010 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00005011 SourceRange(TemplateParams->getTemplateLoc(),
5012 TemplateParams->getRAngleLoc()))
5013 << SourceRange(LAngleLoc, RAngleLoc);
5014 else
5015 isExplicitSpecialization = true;
5016 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00005017 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00005018 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005019 isExplicitSpecialization = true;
5020 }
Douglas Gregor88b70942009-02-25 22:02:03 +00005021
Douglas Gregorcc636682009-02-17 23:15:12 +00005022 // Check that the specialization uses the same tag kind as the
5023 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005024 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5025 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005026 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00005027 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005028 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005029 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00005030 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005031 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00005032 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005033 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00005034 diag::note_previous_use);
5035 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5036 }
5037
Douglas Gregor40808ce2009-03-09 23:48:35 +00005038 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005039 TemplateArgumentListInfo TemplateArgs;
5040 TemplateArgs.setLAngleLoc(LAngleLoc);
5041 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005042 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00005043
Douglas Gregor925910d2011-01-03 20:35:03 +00005044 // Check for unexpanded parameter packs in any of the template arguments.
5045 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005046 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor925910d2011-01-03 20:35:03 +00005047 UPPC_PartialSpecialization))
5048 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005049
Douglas Gregorcc636682009-02-17 23:15:12 +00005050 // Check that the template argument list is well-formed for this
5051 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005052 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005053 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5054 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00005055 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00005056
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005057 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00005058 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00005059 if (isPartialSpecialization) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00005060 if (CheckClassTemplatePartialSpecializationArgs(*this,
Douglas Gregore94866f2009-06-12 21:21:02 +00005061 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00005062 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00005063 return true;
5064
Douglas Gregor561f8122011-07-01 01:22:09 +00005065 bool InstantiationDependent;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005066 if (!Name.isDependent() &&
Douglas Gregorde090962010-02-09 00:37:32 +00005067 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005068 TemplateArgs.getArgumentArray(),
Douglas Gregor561f8122011-07-01 01:22:09 +00005069 TemplateArgs.size(),
5070 InstantiationDependent)) {
Douglas Gregorde090962010-02-09 00:37:32 +00005071 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5072 << ClassTemplate->getDeclName();
5073 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00005074 }
5075 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005076
Douglas Gregorcc636682009-02-17 23:15:12 +00005077 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005078 ClassTemplateSpecializationDecl *PrevDecl = 0;
5079
5080 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005081 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005082 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005083 = ClassTemplate->findPartialSpecialization(Converted.data(),
5084 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005085 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005086 else
5087 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005088 = ClassTemplate->findSpecialization(Converted.data(),
5089 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00005090
5091 ClassTemplateSpecializationDecl *Specialization = 0;
5092
Douglas Gregor88b70942009-02-25 22:02:03 +00005093 // Check whether we can declare a class template specialization in
5094 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005095 if (TUK != TUK_Friend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005096 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
5097 TemplateNameLoc,
Douglas Gregor9302da62009-10-14 23:50:59 +00005098 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00005099 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005100
Douglas Gregorb88e8882009-07-30 17:40:51 +00005101 // The canonical type
5102 QualType CanonType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005103 if (PrevDecl &&
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005104 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00005105 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00005106 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005107 // arguments was referenced but not declared, or we're only
5108 // referencing this specialization as a friend, reuse that
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005109 // declaration node as our own, updating its source location and
5110 // the list of outer template parameters to reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00005111 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00005112 Specialization->setLocation(TemplateNameLoc);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005113 if (TemplateParameterLists.size() > 0) {
5114 Specialization->setTemplateParameterListsInfo(Context,
5115 TemplateParameterLists.size(),
5116 (TemplateParameterList**) TemplateParameterLists.release());
5117 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005118 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00005119 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005120 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00005121 // Build the canonical type that describes the converted template
5122 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00005123 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5124 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00005125 Converted.data(),
5126 Converted.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005127
5128 if (Context.hasSameType(CanonType,
Douglas Gregorb9c66312010-12-23 17:13:55 +00005129 ClassTemplate->getInjectedClassNameSpecialization())) {
5130 // C++ [temp.class.spec]p9b3:
5131 //
5132 // -- The argument list of the specialization shall not be identical
5133 // to the implicit argument list of the primary template.
5134 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Douglas Gregor8d267c52011-09-09 02:06:17 +00005135 << (TUK == TUK_Definition)
5136 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregorb9c66312010-12-23 17:13:55 +00005137 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
5138 ClassTemplate->getIdentifier(),
5139 TemplateNameLoc,
5140 Attr,
5141 TemplateParams,
Douglas Gregore7612302011-09-09 19:05:14 +00005142 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005143 TemplateParameterLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00005144 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregorb9c66312010-12-23 17:13:55 +00005145 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00005146
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005147 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005148 ClassTemplatePartialSpecializationDecl *PrevPartial
5149 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005150 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005151 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00005152 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00005153 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005154 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005155 KWLoc, TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00005156 TemplateParams,
5157 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005158 Converted.data(),
5159 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00005160 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00005161 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00005162 PrevPartial,
5163 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00005164 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005165 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005166 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005167 TemplateParameterLists.size() - 1,
Abramo Bagnara9b934882010-06-12 08:15:14 +00005168 (TemplateParameterList**) TemplateParameterLists.release());
5169 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005170
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005171 if (!PrevPartial)
5172 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005173 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00005174
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005175 // If we are providing an explicit specialization of a member class
Douglas Gregored9c0f92009-10-29 00:04:11 +00005176 // template specialization, make a note of that.
5177 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5178 PrevPartial->setMemberSpecialization();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005179
Douglas Gregor031a5882009-06-13 00:26:55 +00005180 // Check that all of the template parameters of the class template
5181 // partial specialization are deducible from the template
5182 // arguments. If not, this class template partial specialization
5183 // will never be used.
Benjamin Kramer013b3662012-01-30 16:17:39 +00005184 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005185 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00005186 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00005187 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00005188
Benjamin Kramer013b3662012-01-30 16:17:39 +00005189 if (!DeducibleParams.all()) {
5190 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor031a5882009-06-13 00:26:55 +00005191 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
5192 << (NumNonDeducible > 1)
5193 << SourceRange(TemplateNameLoc, RAngleLoc);
5194 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5195 if (!DeducibleParams[I]) {
5196 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
5197 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00005198 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005199 diag::note_partial_spec_unused_parameter)
5200 << Param->getDeclName();
5201 else
Mike Stump1eb44332009-09-09 15:08:12 +00005202 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00005203 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00005204 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00005205 }
5206 }
5207 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005208 } else {
5209 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005210 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00005211 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005212 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00005213 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005214 KWLoc, TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005215 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005216 Converted.data(),
5217 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00005218 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005219 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005220 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005221 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005222 TemplateParameterLists.size(),
Abramo Bagnara9b934882010-06-12 08:15:14 +00005223 (TemplateParameterList**) TemplateParameterLists.release());
5224 }
Douglas Gregorcc636682009-02-17 23:15:12 +00005225
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005226 if (!PrevDecl)
5227 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00005228
5229 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005230 }
5231
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005232 // C++ [temp.expl.spec]p6:
5233 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005234 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005235 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005236 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005237 // use occurs; no diagnostic is required.
5238 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005239 bool Okay = false;
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005240 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005241 // Is there any previous explicit specialization declaration?
5242 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5243 Okay = true;
5244 break;
5245 }
5246 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005247
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005248 if (!Okay) {
5249 SourceRange Range(TemplateNameLoc, RAngleLoc);
5250 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5251 << Context.getTypeDeclType(Specialization) << Range;
5252
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005253 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005254 diag::note_instantiation_required_here)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005255 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005256 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005257 return true;
5258 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005259 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005260
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005261 // If this is not a friend, note that this is an explicit specialization.
5262 if (TUK != TUK_Friend)
5263 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00005264
5265 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005266 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00005267 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00005268 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005269 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00005270 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00005271 Diag(Def->getLocation(), diag::note_previous_definition);
5272 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00005273 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00005274 }
5275 }
5276
John McCall7f1b9872010-12-18 03:30:47 +00005277 if (Attr)
5278 ProcessDeclAttributeList(S, Specialization, Attr);
5279
Douglas Gregord023aec2011-09-09 20:53:38 +00005280 if (ModulePrivateLoc.isValid())
5281 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
5282 << (isPartialSpecialization? 1 : 0)
5283 << FixItHint::CreateRemoval(ModulePrivateLoc);
5284
Douglas Gregorfc705b82009-02-26 22:19:44 +00005285 // Build the fully-sugared type for this class template
5286 // specialization as the user wrote in the specialization
5287 // itself. This means that we'll pretty-print the type retrieved
5288 // from the specialization's declaration the way that the user
5289 // actually wrote the specialization, rather than formatting the
5290 // name based on the "canonical" representation used to store the
5291 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005292 TypeSourceInfo *WrittenTy
5293 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5294 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005295 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005296 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005297 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005298 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00005299 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00005300
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00005301 // C++ [temp.expl.spec]p9:
5302 // A template explicit specialization is in the scope of the
5303 // namespace in which the template was defined.
5304 //
5305 // We actually implement this paragraph where we set the semantic
5306 // context (in the creation of the ClassTemplateSpecializationDecl),
5307 // but we also maintain the lexical context where the actual
5308 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00005309 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005310
Douglas Gregorcc636682009-02-17 23:15:12 +00005311 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00005312 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00005313 Specialization->startDefinition();
5314
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005315 if (TUK == TUK_Friend) {
5316 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5317 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00005318 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00005319 /*FIXME:*/KWLoc);
5320 Friend->setAccess(AS_public);
5321 CurContext->addDecl(Friend);
5322 } else {
5323 // Add the specialization into its lexical context, so that it can
5324 // be seen when iterating through the list of declarations in that
5325 // context. However, specializations are not found by name lookup.
5326 CurContext->addDecl(Specialization);
5327 }
John McCalld226f652010-08-21 09:40:31 +00005328 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00005329}
Douglas Gregord57959a2009-03-27 23:10:48 +00005330
John McCalld226f652010-08-21 09:40:31 +00005331Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00005332 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005333 Declarator &D) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005334 return HandleDeclarator(S, D, move(TemplateParameterLists));
Douglas Gregore542c862009-06-23 23:11:28 +00005335}
5336
John McCalld226f652010-08-21 09:40:31 +00005337Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00005338 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00005339 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00005340 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005341 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00005342
Douglas Gregor52591bf2009-06-24 00:54:41 +00005343 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00005344 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00005345 }
Mike Stump1eb44332009-09-09 15:08:12 +00005346
Douglas Gregor52591bf2009-06-24 00:54:41 +00005347 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00005348
Douglas Gregor45fa5602011-11-07 20:56:01 +00005349 D.setFunctionDefinitionKind(FDK_Definition);
John McCalld226f652010-08-21 09:40:31 +00005350 Decl *DP = HandleDeclarator(ParentScope, D,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005351 move(TemplateParameterLists));
Mike Stump1eb44332009-09-09 15:08:12 +00005352 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00005353 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00005354 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00005355 FunctionTemplate->getTemplatedDecl());
5356 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
5357 return ActOnStartOfFunctionDef(FnBodyScope, Function);
5358 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00005359}
5360
John McCall75042392010-02-11 01:33:53 +00005361/// \brief Strips various properties off an implicit instantiation
5362/// that has just been explicitly specialized.
5363static void StripImplicitInstantiation(NamedDecl *D) {
Rafael Espindola860097c2012-02-23 04:17:32 +00005364 // FIXME: "make check" is clean if the call to dropAttrs() is commented out.
Sean Huntcf807c42010-08-18 23:23:40 +00005365 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00005366
5367 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5368 FD->setInlineSpecified(false);
5369 }
5370}
5371
Nico Weberd1d512a2012-01-09 19:52:25 +00005372/// \brief Compute the diagnostic location for an explicit instantiation
5373// declaration or definition.
5374static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005375 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Weberd1d512a2012-01-09 19:52:25 +00005376 // Explicit instantiations following a specialization have no effect and
5377 // hence no PointOfInstantiation. In that case, walk decl backwards
5378 // until a valid name loc is found.
5379 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005380 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
5381 Prev = Prev->getPreviousDecl()) {
Nico Weberd1d512a2012-01-09 19:52:25 +00005382 PrevDiagLoc = Prev->getLocation();
5383 }
5384 assert(PrevDiagLoc.isValid() &&
5385 "Explicit instantiation without point of instantiation?");
5386 return PrevDiagLoc;
5387}
5388
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005389/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregor454885e2009-10-15 15:54:05 +00005390/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005391/// for those cases where they are required and determining whether the
Douglas Gregor454885e2009-10-15 15:54:05 +00005392/// new specialization/instantiation will have any effect.
5393///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005394/// \param NewLoc the location of the new explicit specialization or
Douglas Gregor454885e2009-10-15 15:54:05 +00005395/// instantiation.
5396///
5397/// \param NewTSK the kind of the new explicit specialization or instantiation.
5398///
5399/// \param PrevDecl the previous declaration of the entity.
5400///
5401/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5402///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005403/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregor454885e2009-10-15 15:54:05 +00005404/// declaration was instantiated (either implicitly or explicitly).
5405///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005406/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00005407/// specialization or instantiation has no effect and should be ignored.
5408///
5409/// \returns true if there was an error that should prevent the introduction of
5410/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00005411bool
5412Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5413 TemplateSpecializationKind NewTSK,
5414 NamedDecl *PrevDecl,
5415 TemplateSpecializationKind PrevTSK,
5416 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005417 bool &HasNoEffect) {
5418 HasNoEffect = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005419
Douglas Gregor454885e2009-10-15 15:54:05 +00005420 switch (NewTSK) {
5421 case TSK_Undeclared:
5422 case TSK_ImplicitInstantiation:
David Blaikieb219cfc2011-09-23 05:06:16 +00005423 llvm_unreachable("Don't check implicit instantiations here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
Douglas Gregor454885e2009-10-15 15:54:05 +00005425 case TSK_ExplicitSpecialization:
5426 switch (PrevTSK) {
5427 case TSK_Undeclared:
5428 case TSK_ExplicitSpecialization:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005429 // Okay, we're just specializing something that is either already
Douglas Gregor454885e2009-10-15 15:54:05 +00005430 // explicitly specialized or has merely been mentioned without any
5431 // instantiation.
5432 return false;
5433
5434 case TSK_ImplicitInstantiation:
5435 if (PrevPointOfInstantiation.isInvalid()) {
5436 // The declaration itself has not actually been instantiated, so it is
5437 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00005438 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00005439 return false;
5440 }
5441 // Fall through
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005442
Douglas Gregor454885e2009-10-15 15:54:05 +00005443 case TSK_ExplicitInstantiationDeclaration:
5444 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005445 assert((PrevTSK == TSK_ImplicitInstantiation ||
5446 PrevPointOfInstantiation.isValid()) &&
Douglas Gregor454885e2009-10-15 15:54:05 +00005447 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005448
Douglas Gregor454885e2009-10-15 15:54:05 +00005449 // C++ [temp.expl.spec]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005450 // If a template, a member template or the member of a class template
Douglas Gregor454885e2009-10-15 15:54:05 +00005451 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005452 // before the first use of that specialization that would cause an
Douglas Gregor454885e2009-10-15 15:54:05 +00005453 // implicit instantiation to take place, in every translation unit in
5454 // which such a use occurs; no diagnostic is required.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005455 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00005456 // Is there any previous explicit specialization declaration?
5457 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5458 return false;
5459 }
5460
Douglas Gregor0d035142009-10-27 18:42:08 +00005461 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00005462 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00005463 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00005464 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005465
Douglas Gregor454885e2009-10-15 15:54:05 +00005466 return true;
5467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005468
Douglas Gregor454885e2009-10-15 15:54:05 +00005469 case TSK_ExplicitInstantiationDeclaration:
5470 switch (PrevTSK) {
5471 case TSK_ExplicitInstantiationDeclaration:
5472 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005473 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005474 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005475
Douglas Gregor454885e2009-10-15 15:54:05 +00005476 case TSK_Undeclared:
5477 case TSK_ImplicitInstantiation:
5478 // We're explicitly instantiating something that may have already been
5479 // implicitly instantiated; that's fine.
5480 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005481
Douglas Gregor454885e2009-10-15 15:54:05 +00005482 case TSK_ExplicitSpecialization:
5483 // C++0x [temp.explicit]p4:
5484 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005485 // of a template appears after a declaration of an explicit
Douglas Gregor454885e2009-10-15 15:54:05 +00005486 // specialization for that template, the explicit instantiation has no
5487 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005488 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005489 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005490
Douglas Gregor454885e2009-10-15 15:54:05 +00005491 case TSK_ExplicitInstantiationDefinition:
5492 // C++0x [temp.explicit]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005493 // If an entity is the subject of both an explicit instantiation
5494 // declaration and an explicit instantiation definition in the same
Douglas Gregor454885e2009-10-15 15:54:05 +00005495 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005496 Diag(NewLoc,
Douglas Gregor0d035142009-10-27 18:42:08 +00005497 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberff91d242011-12-23 20:58:04 +00005498
5499 // Explicit instantiations following a specialization have no effect and
5500 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
5501 // until a valid name loc is found.
Nico Weberd1d512a2012-01-09 19:52:25 +00005502 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5503 diag::note_explicit_instantiation_definition_here);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005504 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005505 return false;
5506 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005507
Douglas Gregor454885e2009-10-15 15:54:05 +00005508 case TSK_ExplicitInstantiationDefinition:
5509 switch (PrevTSK) {
5510 case TSK_Undeclared:
5511 case TSK_ImplicitInstantiation:
5512 // We're explicitly instantiating something that may have already been
5513 // implicitly instantiated; that's fine.
5514 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005515
Douglas Gregor454885e2009-10-15 15:54:05 +00005516 case TSK_ExplicitSpecialization:
5517 // C++ DR 259, C++0x [temp.explicit]p4:
5518 // For a given set of template parameters, if an explicit
5519 // instantiation of a template appears after a declaration of
5520 // an explicit specialization for that template, the explicit
5521 // instantiation has no effect.
5522 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005523 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00005524 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00005525 // has been explicitly specialized.
Richard Smithebaf0e62011-10-18 20:49:44 +00005526 Diag(NewLoc, getLangOptions().CPlusPlus0x ?
5527 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
5528 diag::ext_explicit_instantiation_after_specialization)
5529 << PrevDecl;
5530 Diag(PrevDecl->getLocation(),
5531 diag::note_previous_template_specialization);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005532 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00005533 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005534
Douglas Gregor454885e2009-10-15 15:54:05 +00005535 case TSK_ExplicitInstantiationDeclaration:
5536 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005537 // were previously asked to suppress instantiations. That's fine.
Nico Weberff91d242011-12-23 20:58:04 +00005538
5539 // C++0x [temp.explicit]p4:
5540 // For a given set of template parameters, if an explicit instantiation
5541 // of a template appears after a declaration of an explicit
5542 // specialization for that template, the explicit instantiation has no
5543 // effect.
Douglas Gregorf785a7d2012-01-14 15:55:47 +00005544 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberff91d242011-12-23 20:58:04 +00005545 // Is there any previous explicit specialization declaration?
5546 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5547 HasNoEffect = true;
5548 break;
5549 }
5550 }
5551
Douglas Gregor454885e2009-10-15 15:54:05 +00005552 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005553
Douglas Gregor454885e2009-10-15 15:54:05 +00005554 case TSK_ExplicitInstantiationDefinition:
5555 // C++0x [temp.spec]p5:
5556 // For a given template and a given set of template-arguments,
5557 // - an explicit instantiation definition shall appear at most once
5558 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00005559 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00005560 << PrevDecl;
Nico Weberd1d512a2012-01-09 19:52:25 +00005561 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor0d035142009-10-27 18:42:08 +00005562 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005563 HasNoEffect = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005564 return false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005565 }
Douglas Gregor454885e2009-10-15 15:54:05 +00005566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005567
David Blaikieb219cfc2011-09-23 05:06:16 +00005568 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregor454885e2009-10-15 15:54:05 +00005569}
5570
John McCallaf2094e2010-04-08 09:05:18 +00005571/// \brief Perform semantic analysis for the given dependent function
5572/// template specialization. The only possible way to get a dependent
5573/// function template specialization is with a friend declaration,
5574/// like so:
5575///
5576/// template <class T> void foo(T);
5577/// template <class T> class A {
5578/// friend void foo<>(T);
5579/// };
5580///
5581/// There really isn't any useful analysis we can do here, so we
5582/// just store the information.
5583bool
5584Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5585 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5586 LookupResult &Previous) {
5587 // Remove anything from Previous that isn't a function template in
5588 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005589 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00005590 LookupResult::Filter F = Previous.makeFilter();
5591 while (F.hasNext()) {
5592 NamedDecl *D = F.next()->getUnderlyingDecl();
5593 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00005594 !FDLookupContext->InEnclosingNamespaceSetOf(
5595 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00005596 F.erase();
5597 }
5598 F.done();
5599
5600 // Should this be diagnosed here?
5601 if (Previous.empty()) return true;
5602
5603 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5604 ExplicitTemplateArgs);
5605 return false;
5606}
5607
Abramo Bagnarae03db982010-05-20 15:32:11 +00005608/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005609/// specialization.
5610///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005611/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005612/// explicit function template specialization. On successful completion,
5613/// the function declaration \p FD will become a function template
5614/// specialization.
5615///
5616/// \param FD the function declaration, which will be updated to become a
5617/// function template specialization.
5618///
Abramo Bagnarae03db982010-05-20 15:32:11 +00005619/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5620/// if any. Note that this may be valid info even when 0 arguments are
5621/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5622/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005623///
Francois Pichet59e7c562011-07-08 06:21:47 +00005624/// \param Previous the set of declarations that may be specialized by
Abramo Bagnarae03db982010-05-20 15:32:11 +00005625/// this function specialization.
5626bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005627Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
Douglas Gregor67714232011-03-03 02:41:12 +00005628 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00005629 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005630 // The set of function template specializations that could match this
5631 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005632 UnresolvedSet<8> Candidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005633
Sebastian Redl7a126a42010-08-31 00:36:30 +00005634 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00005635 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5636 I != E; ++I) {
5637 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5638 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005639 // Only consider templates found within the same semantic lookup scope as
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005640 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005641 if (!FDLookupContext->InEnclosingNamespaceSetOf(
5642 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005643 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005644
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005645 // C++ [temp.expl.spec]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005646 // A trailing template-argument can be left unspecified in the
5647 // template-id naming an explicit function template specialization
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005648 // provided it can be deduced from the function argument type.
5649 // Perform template argument deduction to determine whether we may be
5650 // specializing this template.
5651 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00005652 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005653 FunctionDecl *Specialization = 0;
5654 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00005655 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005656 FD->getType(),
5657 Specialization,
5658 Info)) {
5659 // FIXME: Template argument deduction failed; record why it failed, so
5660 // that we can provide nifty diagnostics.
5661 (void)TDK;
5662 continue;
5663 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005664
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005665 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00005666 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005667 }
5668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005669
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005670 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00005671 UnresolvedSetIterator Result
5672 = getMostSpecialized(Candidates.begin(), Candidates.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00005673 TPOC_Other, 0, FD->getLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005674 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00005675 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005676 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00005677 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005678 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00005679 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005680 return true;
John McCallc373d482010-01-27 01:50:18 +00005681
5682 // Ignore access information; it doesn't figure into redeclaration checking.
5683 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnaraabfb4052011-03-04 17:20:30 +00005684
5685 FunctionTemplateSpecializationInfo *SpecInfo
5686 = Specialization->getTemplateSpecializationInfo();
5687 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet59e7c562011-07-08 06:21:47 +00005688
5689 // Note: do not overwrite location info if previous template
5690 // specialization kind was explicit.
5691 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smithff234882012-02-20 23:28:05 +00005692 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet59e7c562011-07-08 06:21:47 +00005693 Specialization->setLocation(FD->getLocation());
Richard Smithff234882012-02-20 23:28:05 +00005694 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
5695 // function can differ from the template declaration with respect to
5696 // the constexpr specifier.
5697 Specialization->setConstexpr(FD->isConstexpr());
5698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005699
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005700 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005701 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00005702
5703 // If this is a friend declaration, then we're not really declaring
5704 // an explicit specialization.
5705 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005706
Douglas Gregord5cb8762009-10-07 00:13:32 +00005707 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00005708 if (!isFriend &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005709 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00005710 Specialization->getPrimaryTemplate(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005711 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005712 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00005713 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005714
5715 // C++ [temp.expl.spec]p6:
5716 // If a template, a member template or the member of a class template is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005717 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005718 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005719 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005720 // use occurs; no diagnostic is required.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005721 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00005722 if (!isFriend &&
5723 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00005724 TSK_ExplicitSpecialization,
5725 Specialization,
5726 SpecInfo->getTemplateSpecializationKind(),
5727 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005728 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005729 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00005730
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005731 // Mark the prior declaration as an explicit specialization, so that later
5732 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005733 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00005734 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005735 MarkUnusedFileScopedDecl(Specialization);
5736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005737
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005738 // Turn the given function declaration into a function template
5739 // specialization, with the template arguments from the previous
5740 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00005741 // Take copies of (semantic and syntactic) template argument lists.
5742 const TemplateArgumentList* TemplArgs = new (Context)
5743 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregor838db382010-02-11 01:19:42 +00005744 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00005745 TemplArgs, /*InsertPos=*/0,
5746 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00005747 ExplicitTemplateArgs);
Douglas Gregore885e182011-05-21 18:53:30 +00005748 FD->setStorageClass(Specialization->getStorageClass());
5749
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005750 // The "previous declaration" for this function template specialization is
5751 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00005752 Previous.clear();
5753 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005754 return false;
5755}
5756
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005757/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005758/// specialization.
5759///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005760/// This routine performs all of the semantic analysis required for an
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005761/// explicit member function specialization. On successful completion,
5762/// the function declaration \p FD will become a member function
5763/// specialization.
5764///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005765/// \param Member the member declaration, which will be updated to become a
5766/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005767///
John McCall68263142009-11-18 22:49:29 +00005768/// \param Previous the set of declarations, one of which may be specialized
5769/// by this function specialization; the set will be modified to contain the
5770/// redeclared member.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005771bool
John McCall68263142009-11-18 22:49:29 +00005772Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005773 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00005774
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005775 // Try to find the member we are instantiating.
5776 NamedDecl *Instantiation = 0;
5777 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005778 MemberSpecializationInfo *MSInfo = 0;
5779
John McCall68263142009-11-18 22:49:29 +00005780 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005781 // Nowhere to look anyway.
5782 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005783 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5784 I != E; ++I) {
5785 NamedDecl *D = (*I)->getUnderlyingDecl();
5786 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005787 if (Context.hasSameType(Function->getType(), Method->getType())) {
5788 Instantiation = Method;
5789 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005790 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005791 break;
5792 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005793 }
5794 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005795 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005796 VarDecl *PrevVar;
5797 if (Previous.isSingleResult() &&
5798 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005799 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00005800 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005801 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005802 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005803 }
5804 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005805 CXXRecordDecl *PrevRecord;
5806 if (Previous.isSingleResult() &&
5807 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5808 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005809 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005810 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005811 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005813
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005814 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005815 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005816 // specializations are always out-of-line, the caller will complain about
5817 // this mismatch later.
5818 return false;
5819 }
John McCall77e8b112010-04-13 20:37:33 +00005820
5821 // If this is a friend, just bail out here before we start turning
5822 // things into explicit specializations.
5823 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5824 // Preserve instantiation information.
5825 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5826 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5827 cast<CXXMethodDecl>(InstantiatedFrom),
5828 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5829 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5830 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5831 cast<CXXRecordDecl>(InstantiatedFrom),
5832 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5833 }
5834
5835 Previous.clear();
5836 Previous.addDecl(Instantiation);
5837 return false;
5838 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005839
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005840 // Make sure that this is a specialization of a member.
5841 if (!InstantiatedFrom) {
5842 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5843 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005844 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5845 return true;
5846 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005847
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005848 // C++ [temp.expl.spec]p6:
5849 // If a template, a member template or the member of a class template is
Nico Weberff91d242011-12-23 20:58:04 +00005850 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005851 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005852 // instantiation to take place, in every translation unit in which such a
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005853 // use occurs; no diagnostic is required.
5854 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00005855
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005856 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00005857 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5858 TSK_ExplicitSpecialization,
5859 Instantiation,
5860 MSInfo->getTemplateSpecializationKind(),
5861 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005862 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005863 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005865 // Check the scope of this explicit specialization.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005866 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005867 InstantiatedFrom,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005868 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005869 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005870 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00005871
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005872 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00005873 // the original declaration to note that it is an explicit specialization
5874 // (if it was previously an implicit instantiation). This latter step
5875 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005876 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005877 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5878 if (InstantiationFunction->getTemplateSpecializationKind() ==
5879 TSK_ImplicitInstantiation) {
5880 InstantiationFunction->setTemplateSpecializationKind(
5881 TSK_ExplicitSpecialization);
5882 InstantiationFunction->setLocation(Member->getLocation());
5883 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005884
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005885 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5886 cast<CXXMethodDecl>(InstantiatedFrom),
5887 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005888 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005889 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005890 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5891 if (InstantiationVar->getTemplateSpecializationKind() ==
5892 TSK_ImplicitInstantiation) {
5893 InstantiationVar->setTemplateSpecializationKind(
5894 TSK_ExplicitSpecialization);
5895 InstantiationVar->setLocation(Member->getLocation());
5896 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005897
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005898 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5899 cast<VarDecl>(InstantiatedFrom),
5900 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005901 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005902 } else {
5903 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00005904 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5905 if (InstantiationClass->getTemplateSpecializationKind() ==
5906 TSK_ImplicitInstantiation) {
5907 InstantiationClass->setTemplateSpecializationKind(
5908 TSK_ExplicitSpecialization);
5909 InstantiationClass->setLocation(Member->getLocation());
5910 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005911
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005912 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00005913 cast<CXXRecordDecl>(InstantiatedFrom),
5914 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005915 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005916
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005917 // Save the caller the trouble of having to figure out which declaration
5918 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00005919 Previous.clear();
5920 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005921 return false;
5922}
5923
Douglas Gregor558c0322009-10-14 23:41:34 +00005924/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00005925///
5926/// \returns true if a serious error occurs, false otherwise.
5927static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00005928 SourceLocation InstLoc,
5929 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005930 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5931 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005932
Douglas Gregor669eed82010-07-13 00:10:04 +00005933 if (CurContext->isRecord()) {
5934 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5935 << D;
5936 return true;
5937 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005938
Richard Smith3e2e91e2011-10-18 02:28:33 +00005939 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005940 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith3e2e91e2011-10-18 02:28:33 +00005941 // template. If the name declared in the explicit instantiation is an
5942 // unqualified name, the explicit instantiation shall appear in the
5943 // namespace where its template is declared or, if that namespace is inline
5944 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregor558c0322009-10-14 23:41:34 +00005945 //
5946 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith3e2e91e2011-10-18 02:28:33 +00005947 if (WasQualifiedName) {
5948 if (CurContext->Encloses(OrigContext))
5949 return false;
5950 } else {
5951 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
5952 return false;
5953 }
5954
5955 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
5956 if (WasQualifiedName)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005957 S.Diag(InstLoc,
5958 S.getLangOptions().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00005959 diag::err_explicit_instantiation_out_of_scope :
5960 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005961 << D << NS;
5962 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005963 S.Diag(InstLoc,
Douglas Gregor2166beb2010-05-11 17:39:34 +00005964 S.getLangOptions().CPlusPlus0x?
Richard Smith3e2e91e2011-10-18 02:28:33 +00005965 diag::err_explicit_instantiation_unqualified_wrong_namespace :
5966 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
5967 << D << NS;
5968 } else
5969 S.Diag(InstLoc,
5970 S.getLangOptions().CPlusPlus0x?
5971 diag::err_explicit_instantiation_must_be_global :
5972 diag::warn_explicit_instantiation_must_be_global_0x)
5973 << D;
Douglas Gregor558c0322009-10-14 23:41:34 +00005974 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005975 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005976}
5977
5978/// \brief Determine whether the given scope specifier has a template-id in it.
5979static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5980 if (!SS.isSet())
5981 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005982
Richard Smith3e2e91e2011-10-18 02:28:33 +00005983 // C++11 [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005984 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00005985 // or a static data member of a class template specialization, the name of
5986 // the class template specialization in the qualified-id for the member
5987 // name shall be a simple-template-id.
5988 //
5989 // C++98 has the same restriction, just worded differently.
5990 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5991 NNS; NNS = NNS->getPrefix())
John McCallf4c73712011-01-19 06:33:43 +00005992 if (const Type *T = NNS->getAsType())
Douglas Gregor558c0322009-10-14 23:41:34 +00005993 if (isa<TemplateSpecializationType>(T))
5994 return true;
5995
5996 return false;
5997}
5998
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005999// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00006000DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00006001Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00006002 SourceLocation ExternLoc,
6003 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006004 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006005 SourceLocation KWLoc,
6006 const CXXScopeSpec &SS,
6007 TemplateTy TemplateD,
6008 SourceLocation TemplateNameLoc,
6009 SourceLocation LAngleLoc,
6010 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006011 SourceLocation RAngleLoc,
6012 AttributeList *Attr) {
6013 // Find the class template we're specializing
6014 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00006015 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006016 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
6017
6018 // Check that the specialization uses the same tag kind as the
6019 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006020 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6021 assert(Kind != TTK_Enum &&
6022 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00006023 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieubbf34c02011-06-10 03:11:26 +00006024 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00006025 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006026 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006027 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00006028 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006029 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00006030 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006031 diag::note_previous_use);
6032 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6033 }
6034
Douglas Gregor558c0322009-10-14 23:41:34 +00006035 // C++0x [temp.explicit]p2:
6036 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006037 // definition and an explicit instantiation declaration. An explicit
6038 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00006039 TemplateSpecializationKind TSK
6040 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6041 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006042
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006043 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00006044 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00006045 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006046
6047 // Check that the template argument list is well-formed for this
6048 // template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006049 SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00006050 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6051 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006052 return true;
6053
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006054 // Find the class template specialization declaration that
6055 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006056 void *InsertPos = 0;
6057 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00006058 = ClassTemplate->findSpecialization(Converted.data(),
6059 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006060
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006061 TemplateSpecializationKind PrevDecl_TSK
6062 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
6063
Douglas Gregord5cb8762009-10-07 00:13:32 +00006064 // C++0x [temp.explicit]p2:
6065 // [...] An explicit instantiation shall appear in an enclosing
6066 // namespace of its template. [...]
6067 //
6068 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00006069 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
6070 SS.isSet()))
6071 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006072
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006073 ClassTemplateSpecializationDecl *Specialization = 0;
6074
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006075 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006076 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00006077 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006078 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006079 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006080 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00006081 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006082
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006083 // Even though HasNoEffect == true means that this explicit instantiation
6084 // has no effect on semantics, we go on to put its syntax in the AST.
6085
6086 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
6087 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00006088 // Since the only prior class template specialization with these
6089 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006090 // declaration node as our own, updating the source location
6091 // for the template name to reflect our new declaration.
6092 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00006093 Specialization = PrevDecl;
6094 Specialization->setLocation(TemplateNameLoc);
6095 PrevDecl = 0;
6096 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006097 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006098
Douglas Gregor52604ab2009-09-11 21:19:12 +00006099 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006100 // Create a new class template specialization declaration node for
6101 // this explicit specialization.
6102 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00006103 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006104 ClassTemplate->getDeclContext(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00006105 KWLoc, TemplateNameLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006106 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00006107 Converted.data(),
6108 Converted.size(),
6109 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00006110 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006111
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00006112 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006113 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00006114 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006115 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006116 }
6117
6118 // Build the fully-sugared type for this explicit instantiation as
6119 // the user wrote in the explicit instantiation itself. This means
6120 // that we'll pretty-print the type retrieved from the
6121 // specialization's declaration the way that the user actually wrote
6122 // the explicit instantiation, rather than formatting the name based
6123 // on the "canonical" representation used to store the template
6124 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00006125 TypeSourceInfo *WrittenTy
6126 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6127 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006128 Context.getTypeDeclType(Specialization));
6129 Specialization->setTypeAsWritten(WrittenTy);
6130 TemplateArgsIn.release();
6131
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006132 // Set source locations for keywords.
6133 Specialization->setExternLoc(ExternLoc);
6134 Specialization->setTemplateKeywordLoc(TemplateLoc);
6135
Rafael Espindola0257b7f2012-01-03 06:04:21 +00006136 if (Attr)
6137 ProcessDeclAttributeList(S, Specialization, Attr);
6138
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006139 // Add the explicit instantiation into its lexical context. However,
6140 // since explicit instantiations are never found by name lookup, we
6141 // just put it into the declaration context directly.
6142 Specialization->setLexicalDeclContext(CurContext);
6143 CurContext->addDecl(Specialization);
6144
6145 // Syntax is now OK, so return if it has no other effect on semantics.
6146 if (HasNoEffect) {
6147 // Set the template specialization kind.
6148 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00006149 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00006150 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006151
6152 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006153 // A definition of a class template or class member template
6154 // shall be in scope at the point of the explicit instantiation of
6155 // the class template or class member template.
6156 //
6157 // This check comes when we actually try to perform the
6158 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006159 ClassTemplateSpecializationDecl *Def
6160 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00006161 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006162 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00006163 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006164 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006165 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006166 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
6167 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006168
Douglas Gregor0d035142009-10-27 18:42:08 +00006169 // Instantiate the members of this class template specialization.
6170 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00006171 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006172 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00006173 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
6174
6175 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
6176 // TSK_ExplicitInstantiationDefinition
6177 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
6178 TSK == TSK_ExplicitInstantiationDefinition)
6179 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006180
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006181 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00006182 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006183
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006184 // Set the template specialization kind.
6185 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00006186 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00006187}
6188
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006189// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00006190DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00006191Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00006192 SourceLocation ExternLoc,
6193 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006194 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006195 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006196 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006197 IdentifierInfo *Name,
6198 SourceLocation NameLoc,
6199 AttributeList *Attr) {
6200
Douglas Gregor402abb52009-05-28 23:31:59 +00006201 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00006202 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00006203 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00006204 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregore7612302011-09-09 19:05:14 +00006205 /*ModulePrivateLoc=*/SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +00006206 MultiTemplateParamsArg(*this, 0, 0),
Richard Smithbdad7a22012-01-10 01:33:14 +00006207 Owned, IsDependent, SourceLocation(), false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006208 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00006209 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
6210
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006211 if (!TagD)
6212 return true;
6213
John McCalld226f652010-08-21 09:40:31 +00006214 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006215 if (Tag->isEnum()) {
6216 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
6217 << Context.getTypeDeclType(Tag);
6218 return true;
6219 }
6220
Douglas Gregord0c87372009-05-27 17:30:49 +00006221 if (Tag->isInvalidDecl())
6222 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006223
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006224 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
6225 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
6226 if (!Pattern) {
6227 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
6228 << Context.getTypeDeclType(Record);
6229 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
6230 return true;
6231 }
6232
Douglas Gregor558c0322009-10-14 23:41:34 +00006233 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006234 // If the explicit instantiation is for a class or member class, the
6235 // elaborated-type-specifier in the declaration shall include a
Douglas Gregor558c0322009-10-14 23:41:34 +00006236 // simple-template-id.
6237 //
6238 // C++98 has the same restriction, just worded differently.
6239 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00006240 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006241 << Record << SS.getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006242
Douglas Gregor558c0322009-10-14 23:41:34 +00006243 // C++0x [temp.explicit]p2:
6244 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006245 // definition and an explicit instantiation declaration. An explicit
Douglas Gregor558c0322009-10-14 23:41:34 +00006246 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00006247 TemplateSpecializationKind TSK
6248 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6249 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006250
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006251 // C++0x [temp.explicit]p2:
6252 // [...] An explicit instantiation shall appear in an enclosing
6253 // namespace of its template. [...]
6254 //
6255 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00006256 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006257
Douglas Gregor454885e2009-10-15 15:54:05 +00006258 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006259 CXXRecordDecl *PrevDecl
Douglas Gregoref96ee02012-01-14 16:38:05 +00006260 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor952b0172010-02-11 01:04:33 +00006261 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00006262 PrevDecl = Record;
6263 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00006264 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006265 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00006266 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006267 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00006268 PrevDecl,
6269 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006270 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006271 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006272 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006273 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00006274 return TagD;
6275 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006276
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006277 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00006278 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00006279 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006280 // C++ [temp.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006281 // A definition of a member class of a class template shall be in scope
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006282 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006283 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00006284 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006285 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00006286 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6287 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00006288 Diag(Pattern->getLocation(), diag::note_forward_declaration)
6289 << Pattern;
6290 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00006291 } else {
6292 if (InstantiateClass(NameLoc, Record, Def,
6293 getTemplateInstantiationArgs(Record),
6294 TSK))
6295 return true;
6296
Douglas Gregor952b0172010-02-11 01:04:33 +00006297 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00006298 if (!RecordDef)
6299 return true;
6300 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006301 }
6302
Douglas Gregor0d035142009-10-27 18:42:08 +00006303 // Instantiate all of the members of the class.
6304 InstantiateClassMembers(NameLoc, RecordDef,
6305 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006306
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006307 if (TSK == TSK_ExplicitInstantiationDefinition)
6308 MarkVTableUsed(NameLoc, RecordDef, true);
6309
Mike Stump390b4cc2009-05-16 07:39:55 +00006310 // FIXME: We don't have any representation for explicit instantiations of
6311 // member classes. Such a representation is not needed for compilation, but it
6312 // should be available for clients that want to see all of the declarations in
6313 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00006314 return TagD;
6315}
6316
John McCallf312b1e2010-08-26 23:41:50 +00006317DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6318 SourceLocation ExternLoc,
6319 SourceLocation TemplateLoc,
6320 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006321 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00006322 // TODO: check if/when DNInfo should replace Name.
6323 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6324 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006325 if (!Name) {
6326 if (!D.isInvalidType())
Daniel Dunbar96a00142012-03-09 18:35:03 +00006327 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006328 diag::err_explicit_instantiation_requires_name)
6329 << D.getDeclSpec().getSourceRange()
6330 << D.getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006331
Douglas Gregord5a423b2009-09-25 18:43:00 +00006332 return true;
6333 }
6334
6335 // The scope passed in may not be a decl scope. Zip up the scope tree until
6336 // we find one that is.
6337 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6338 (S->getFlags() & Scope::TemplateParamScope) != 0)
6339 S = S->getParent();
6340
6341 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00006342 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6343 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006344 if (R.isNull())
6345 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006346
Douglas Gregore885e182011-05-21 18:53:30 +00006347 // C++ [dcl.stc]p1:
6348 // A storage-class-specifier shall not be specified in [...] an explicit
6349 // instantiation (14.7.2) directive.
Douglas Gregord5a423b2009-09-25 18:43:00 +00006350 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00006351 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6352 << Name;
6353 return true;
Douglas Gregore885e182011-05-21 18:53:30 +00006354 } else if (D.getDeclSpec().getStorageClassSpec()
6355 != DeclSpec::SCS_unspecified) {
6356 // Complain about then remove the storage class specifier.
6357 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6358 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6359
6360 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006361 }
6362
Douglas Gregor663b5a02009-10-14 20:14:33 +00006363 // C++0x [temp.explicit]p1:
6364 // [...] An explicit instantiation of a function template shall not use the
6365 // inline or constexpr specifiers.
6366 // Presumably, this also applies to member functions of class templates as
6367 // well.
Richard Smith2dc7ece2011-10-18 03:44:03 +00006368 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006369 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2dc7ece2011-10-18 03:44:03 +00006370 getLangOptions().CPlusPlus0x ?
6371 diag::err_explicit_instantiation_inline :
6372 diag::warn_explicit_instantiation_inline_0x)
Richard Smithfe6f6482011-10-14 19:58:02 +00006373 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6374 if (D.getDeclSpec().isConstexprSpecified())
6375 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
6376 // not already specified.
6377 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6378 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006379
Douglas Gregor558c0322009-10-14 23:41:34 +00006380 // C++0x [temp.explicit]p2:
6381 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006382 // definition and an explicit instantiation declaration. An explicit
6383 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00006384 TemplateSpecializationKind TSK
6385 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6386 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006387
Abramo Bagnara25777432010-08-11 22:01:17 +00006388 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00006389 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006390
6391 if (!R->isFunctionType()) {
6392 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006393 // A [...] static data member of a class template can be explicitly
6394 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006395 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00006396 if (Previous.isAmbiguous())
6397 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006398
John McCall1bcee0a2009-12-02 08:25:40 +00006399 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00006400 if (!Prev || !Prev->isStaticDataMember()) {
6401 // We expect to see a data data member here.
6402 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6403 << Name;
6404 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6405 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00006406 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00006407 return true;
6408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006409
Douglas Gregord5a423b2009-09-25 18:43:00 +00006410 if (!Prev->getInstantiatedFromStaticDataMember()) {
6411 // FIXME: Check for explicit specialization?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006412 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006413 diag::err_explicit_instantiation_data_member_not_instantiated)
6414 << Prev;
6415 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6416 // FIXME: Can we provide a note showing where this was declared?
6417 return true;
6418 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006419
Douglas Gregor558c0322009-10-14 23:41:34 +00006420 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006421 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006422 // or a static data member of a class template specialization, the name of
6423 // the class template specialization in the qualified-id for the member
6424 // name shall be a simple-template-id.
6425 //
6426 // C++98 has the same restriction, just worded differently.
6427 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006428 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006429 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006430 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006431
Douglas Gregor558c0322009-10-14 23:41:34 +00006432 // Check the scope of this explicit instantiation.
6433 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006434
Douglas Gregor454885e2009-10-15 15:54:05 +00006435 // Verify that it is okay to explicitly instantiate here.
6436 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6437 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006438 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006439 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00006440 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006441 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006442 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00006443 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006444 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006445 return (Decl*) 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006446
Douglas Gregord5a423b2009-09-25 18:43:00 +00006447 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006448 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006449 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006450 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006451
Douglas Gregord5a423b2009-09-25 18:43:00 +00006452 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00006453 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006454 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006455
6456 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00006457 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00006458 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00006459 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006460 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6461 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00006462 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6463 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00006464 ASTTemplateArgsPtr TemplateArgsPtr(*this,
6465 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00006466 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00006467 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00006468 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00006469 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00006470 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006471
Douglas Gregord5a423b2009-09-25 18:43:00 +00006472 // C++ [temp.explicit]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006473 // A [...] function [...] can be explicitly instantiated from its template.
6474 // A member function [...] of a class template can be explicitly
6475 // instantiated from the member definition associated with its class
Douglas Gregord5a423b2009-09-25 18:43:00 +00006476 // template.
John McCallc373d482010-01-27 01:50:18 +00006477 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006478 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6479 P != PEnd; ++P) {
6480 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00006481 if (!HasExplicitTemplateArgs) {
6482 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6483 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6484 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00006485
John McCallc373d482010-01-27 01:50:18 +00006486 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00006487 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6488 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00006489 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00006490 }
6491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006492
Douglas Gregord5a423b2009-09-25 18:43:00 +00006493 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6494 if (!FunTmpl)
6495 continue;
6496
John McCall5769d612010-02-08 23:07:23 +00006497 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006498 FunctionDecl *Specialization = 0;
6499 if (TemplateDeductionResult TDK
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006500 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00006501 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006502 R, Specialization, Info)) {
6503 // FIXME: Keep track of almost-matches?
6504 (void)TDK;
6505 continue;
6506 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006507
John McCallc373d482010-01-27 01:50:18 +00006508 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00006509 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006510
Douglas Gregord5a423b2009-09-25 18:43:00 +00006511 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00006512 UnresolvedSetIterator Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006513 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006514 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006515 PDiag(diag::err_explicit_instantiation_not_known) << Name,
6516 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6517 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00006518
John McCallc373d482010-01-27 01:50:18 +00006519 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00006520 return true;
John McCallc373d482010-01-27 01:50:18 +00006521
6522 // Ignore access control bits, we don't need them for redeclaration checking.
6523 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006524
Douglas Gregor0a897e32009-10-15 17:21:20 +00006525 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006526 Diag(D.getIdentifierLoc(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00006527 diag::err_explicit_instantiation_member_function_not_instantiated)
6528 << Specialization
6529 << (Specialization->getTemplateSpecializationKind() ==
6530 TSK_ExplicitSpecialization);
6531 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6532 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006533 }
6534
Douglas Gregoref96ee02012-01-14 16:38:05 +00006535 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor583f33b2009-10-15 18:07:02 +00006536 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6537 PrevDecl = Specialization;
6538
Douglas Gregor0a897e32009-10-15 17:21:20 +00006539 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006540 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00006541 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006542 PrevDecl,
6543 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor0a897e32009-10-15 17:21:20 +00006544 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006545 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00006546 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006547
Douglas Gregor0a897e32009-10-15 17:21:20 +00006548 // FIXME: We may still want to build some representation of this
6549 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00006550 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00006551 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00006552 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00006553
6554 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola256fc4d2012-01-04 05:40:59 +00006555 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
6556 if (Attr)
6557 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006558
Douglas Gregor0a897e32009-10-15 17:21:20 +00006559 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00006560 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006561
Douglas Gregor558c0322009-10-14 23:41:34 +00006562 // C++0x [temp.explicit]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006563 // If the explicit instantiation is for a member function, a member class
Douglas Gregor558c0322009-10-14 23:41:34 +00006564 // or a static data member of a class template specialization, the name of
6565 // the class template specialization in the qualified-id for the member
6566 // name shall be a simple-template-id.
6567 //
6568 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00006569 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006570 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006571 D.getCXXScopeSpec().isSet() &&
Douglas Gregor558c0322009-10-14 23:41:34 +00006572 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006573 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00006574 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00006575 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006576
Douglas Gregor558c0322009-10-14 23:41:34 +00006577 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006578 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregor558c0322009-10-14 23:41:34 +00006579 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006580 D.getIdentifierLoc(),
Douglas Gregor558c0322009-10-14 23:41:34 +00006581 D.getCXXScopeSpec().isSet());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006582
Douglas Gregord5a423b2009-09-25 18:43:00 +00006583 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00006584 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00006585}
6586
John McCallf312b1e2010-08-26 23:41:50 +00006587TypeResult
John McCallc4e70192009-09-11 04:59:25 +00006588Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6589 const CXXScopeSpec &SS, IdentifierInfo *Name,
6590 SourceLocation TagLoc, SourceLocation NameLoc) {
6591 // This has to hold, because SS is expected to be defined.
6592 assert(Name && "Expected a name in a dependent tag");
6593
6594 NestedNameSpecifier *NNS
6595 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6596 if (!NNS)
6597 return true;
6598
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006599 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00006600
Douglas Gregor48c89f42010-04-24 16:38:41 +00006601 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6602 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006603 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00006604 return true;
6605 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006606
Douglas Gregor059101f2011-03-02 00:47:37 +00006607 // Create the resulting type.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006608 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor059101f2011-03-02 00:47:37 +00006609 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6610
6611 // Create type-source location information for this type.
6612 TypeLocBuilder TLB;
6613 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara38a42912012-02-06 19:09:27 +00006614 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor059101f2011-03-02 00:47:37 +00006615 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6616 TL.setNameLoc(NameLoc);
6617 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCallc4e70192009-09-11 04:59:25 +00006618}
6619
John McCallf312b1e2010-08-26 23:41:50 +00006620TypeResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006621Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6622 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregor1a15dae2010-06-16 22:31:08 +00006623 SourceLocation IdLoc) {
Douglas Gregore29425b2011-02-28 22:42:13 +00006624 if (SS.isInvalid())
Douglas Gregord57959a2009-03-27 23:10:48 +00006625 return true;
Douglas Gregore29425b2011-02-28 22:42:13 +00006626
Richard Smithebaf0e62011-10-18 20:49:44 +00006627 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6628 Diag(TypenameLoc,
6629 getLangOptions().CPlusPlus0x ?
6630 diag::warn_cxx98_compat_typename_outside_of_template :
6631 diag::ext_typename_outside_of_template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006632 << FixItHint::CreateRemoval(TypenameLoc);
6633
Douglas Gregor2494dd02011-03-01 01:34:45 +00006634 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor9e876872011-03-01 18:12:44 +00006635 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6636 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00006637 if (T.isNull())
6638 return true;
John McCall63b43852010-04-29 23:50:39 +00006639
6640 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6641 if (isa<DependentNameType>(T)) {
6642 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00006643 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00006644 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006645 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006646 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006647 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00006648 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00006649 TL.setQualifierLoc(QualifierLoc);
John McCall4e449832010-05-28 23:32:21 +00006650 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00006651 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006652
John McCallb3d87482010-08-24 05:47:05 +00006653 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00006654}
6655
John McCallf312b1e2010-08-26 23:41:50 +00006656TypeResult
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006657Sema::ActOnTypenameType(Scope *S,
6658 SourceLocation TypenameLoc,
6659 const CXXScopeSpec &SS,
6660 SourceLocation TemplateKWLoc,
Douglas Gregora02411e2011-02-27 22:46:49 +00006661 TemplateTy TemplateIn,
6662 SourceLocation TemplateNameLoc,
6663 SourceLocation LAngleLoc,
6664 ASTTemplateArgsPtr TemplateArgsIn,
6665 SourceLocation RAngleLoc) {
Richard Smithebaf0e62011-10-18 20:49:44 +00006666 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6667 Diag(TypenameLoc,
6668 getLangOptions().CPlusPlus0x ?
6669 diag::warn_cxx98_compat_typename_outside_of_template :
6670 diag::ext_typename_outside_of_template)
6671 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006672
6673 // Translate the parser's template argument list in our AST format.
6674 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6675 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6676
6677 TemplateName Template = TemplateIn.get();
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006678 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6679 // Construct a dependent template specialization type.
6680 assert(DTN && "dependent template has non-dependent name?");
6681 assert(DTN->getQualifier()
6682 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
6683 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
6684 DTN->getQualifier(),
6685 DTN->getIdentifier(),
6686 TemplateArgs);
Douglas Gregora02411e2011-02-27 22:46:49 +00006687
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006688 // Create source-location information for this type.
John McCall4e449832010-05-28 23:32:21 +00006689 TypeLocBuilder Builder;
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006690 DependentTemplateSpecializationTypeLoc SpecTL
6691 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006692 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
6693 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara66581d42012-02-06 22:45:07 +00006694 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006695 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006696 SpecTL.setLAngleLoc(LAngleLoc);
6697 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006698 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6699 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006700 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor6946baf2009-09-02 13:05:45 +00006701 }
Douglas Gregora02411e2011-02-27 22:46:49 +00006702
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006703 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
6704 if (T.isNull())
6705 return true;
Douglas Gregora02411e2011-02-27 22:46:49 +00006706
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006707 // Provide source-location information for the template specialization type.
Douglas Gregora02411e2011-02-27 22:46:49 +00006708 TypeLocBuilder Builder;
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006709 TemplateSpecializationTypeLoc SpecTL
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006710 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara55d23c92012-02-06 14:41:24 +00006711 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
6712 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006713 SpecTL.setLAngleLoc(LAngleLoc);
6714 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregora02411e2011-02-27 22:46:49 +00006715 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6716 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
6717
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006718 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
6719 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +00006720 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00006721 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6722
Douglas Gregoref24c4b2011-03-01 16:44:30 +00006723 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
6724 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00006725}
6726
Douglas Gregora02411e2011-02-27 22:46:49 +00006727
Douglas Gregord57959a2009-03-27 23:10:48 +00006728/// \brief Build the type that describes a C++ typename specifier,
6729/// e.g., "typename T::type".
6730QualType
Douglas Gregore29425b2011-02-28 22:42:13 +00006731Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
6732 SourceLocation KeywordLoc,
6733 NestedNameSpecifierLoc QualifierLoc,
6734 const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006735 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00006736 CXXScopeSpec SS;
Douglas Gregore29425b2011-02-28 22:42:13 +00006737 SS.Adopt(QualifierLoc);
Douglas Gregord57959a2009-03-27 23:10:48 +00006738
John McCall77bb1aa2010-05-01 00:40:08 +00006739 DeclContext *Ctx = computeDeclContext(SS);
6740 if (!Ctx) {
6741 // If the nested-name-specifier is dependent and couldn't be
6742 // resolved to a type, build a typename type.
Douglas Gregore29425b2011-02-28 22:42:13 +00006743 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
6744 return Context.getDependentNameType(Keyword,
6745 QualifierLoc.getNestedNameSpecifier(),
6746 &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00006747 }
Douglas Gregord57959a2009-03-27 23:10:48 +00006748
John McCall77bb1aa2010-05-01 00:40:08 +00006749 // If the nested-name-specifier refers to the current instantiation,
6750 // the "typename" keyword itself is superfluous. In C++03, the
6751 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
6752 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00006753 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00006754
John McCall77bb1aa2010-05-01 00:40:08 +00006755 if (RequireCompleteDeclContext(SS, Ctx))
6756 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00006757
6758 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006759 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00006760 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00006761 unsigned DiagID = 0;
6762 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006763 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00006764 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00006765 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00006766 break;
Douglas Gregord9545042010-12-09 00:06:27 +00006767
6768 case LookupResult::FoundUnresolvedValue: {
6769 // We found a using declaration that is a value. Most likely, the using
6770 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregore29425b2011-02-28 22:42:13 +00006771 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregord9545042010-12-09 00:06:27 +00006772 IILoc);
6773 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
6774 << Name << Ctx << FullRange;
6775 if (UnresolvedUsingValueDecl *Using
6776 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregordc355712011-02-25 00:36:19 +00006777 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregord9545042010-12-09 00:06:27 +00006778 Diag(Loc, diag::note_using_value_decl_missing_typename)
6779 << FixItHint::CreateInsertion(Loc, "typename ");
6780 }
6781 }
6782 // Fall through to create a dependent typename type, from which we can recover
6783 // better.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006784
Douglas Gregor7d3f5762010-01-15 01:44:47 +00006785 case LookupResult::NotFoundInCurrentInstantiation:
6786 // Okay, it's a member of an unknown instantiation.
Douglas Gregore29425b2011-02-28 22:42:13 +00006787 return Context.getDependentNameType(Keyword,
6788 QualifierLoc.getNestedNameSpecifier(),
6789 &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00006790
6791 case LookupResult::Found:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006792 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006793 // We found a type. Build an ElaboratedType, since the
6794 // typename-specifier was just sugar.
Douglas Gregore29425b2011-02-28 22:42:13 +00006795 return Context.getElaboratedType(ETK_Typename,
6796 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006797 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00006798 }
6799
6800 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00006801 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00006802 break;
6803
6804 case LookupResult::FoundOverloaded:
6805 DiagID = diag::err_typename_nested_not_type;
6806 Referenced = *Result.begin();
6807 break;
6808
John McCall6e247262009-10-10 05:48:19 +00006809 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00006810 return QualType();
6811 }
6812
6813 // If we get here, it's because name lookup did not find a
6814 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore29425b2011-02-28 22:42:13 +00006815 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006816 IILoc);
6817 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00006818 if (Referenced)
6819 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6820 << Name;
6821 return QualType();
6822}
Douglas Gregor4a959d82009-08-06 16:20:37 +00006823
6824namespace {
6825 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00006826 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00006827 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00006828 SourceLocation Loc;
6829 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00006830
Douglas Gregor4a959d82009-08-06 16:20:37 +00006831 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00006832 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006833
Mike Stump1eb44332009-09-09 15:08:12 +00006834 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006835 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00006836 DeclarationName Entity)
6837 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00006838 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00006839
6840 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00006841 /// transformed.
6842 ///
6843 /// For the purposes of type reconstruction, a type has already been
6844 /// transformed if it is NULL or if it is not dependent.
6845 bool AlreadyTransformed(QualType T) {
6846 return T.isNull() || !T->isDependentType();
6847 }
Mike Stump1eb44332009-09-09 15:08:12 +00006848
6849 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00006850 /// rebuilt.
6851 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00006852
Douglas Gregor4a959d82009-08-06 16:20:37 +00006853 /// \brief Returns the name of the entity whose type is being rebuilt.
6854 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00006855
Douglas Gregor972e6ce2009-10-27 06:26:26 +00006856 /// \brief Sets the "base" location and entity when that
6857 /// information is known based on another transformation.
6858 void setBase(SourceLocation Loc, DeclarationName Entity) {
6859 this->Loc = Loc;
6860 this->Entity = Entity;
6861 }
Douglas Gregordfca6f52012-02-13 22:00:16 +00006862
6863 ExprResult TransformLambdaExpr(LambdaExpr *E) {
6864 // Lambdas never need to be transformed.
6865 return E;
6866 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00006867 };
6868}
6869
Douglas Gregor4a959d82009-08-06 16:20:37 +00006870/// \brief Rebuilds a type within the context of the current instantiation.
6871///
Mike Stump1eb44332009-09-09 15:08:12 +00006872/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00006873/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00006874/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00006875/// partial specialization thereof). This routine will rebuild that type now
6876/// that we have entered the declarator's scope, which may produce different
6877/// canonical types, e.g.,
6878///
6879/// \code
6880/// template<typename T>
6881/// struct X {
6882/// typedef T* pointer;
6883/// pointer data();
6884/// };
6885///
6886/// template<typename T>
6887/// typename X<T>::pointer X<T>::data() { ... }
6888/// \endcode
6889///
Douglas Gregor4714c122010-03-31 17:34:00 +00006890/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006891/// since we do not know that we can look into X<T> when we parsed the type.
6892/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006893/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00006894/// as the canonical type of T*, allowing the return types of the out-of-line
6895/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00006896TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6897 SourceLocation Loc,
6898 DeclarationName Name) {
6899 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00006900 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00006901
Douglas Gregor4a959d82009-08-06 16:20:37 +00006902 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6903 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00006904}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006905
John McCall60d7b3a2010-08-24 06:29:42 +00006906ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00006907 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6908 DeclarationName());
6909 return Rebuilder.TransformExpr(E);
6910}
6911
John McCall63b43852010-04-29 23:50:39 +00006912bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor7e384942011-02-25 16:07:42 +00006913 if (SS.isInvalid())
6914 return true;
John McCall31f17ec2010-04-27 00:57:59 +00006915
Douglas Gregor7e384942011-02-25 16:07:42 +00006916 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall31f17ec2010-04-27 00:57:59 +00006917 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6918 DeclarationName());
Douglas Gregor7e384942011-02-25 16:07:42 +00006919 NestedNameSpecifierLoc Rebuilt
6920 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
6921 if (!Rebuilt)
6922 return true;
John McCall63b43852010-04-29 23:50:39 +00006923
Douglas Gregor7e384942011-02-25 16:07:42 +00006924 SS.Adopt(Rebuilt);
John McCall63b43852010-04-29 23:50:39 +00006925 return false;
John McCall31f17ec2010-04-27 00:57:59 +00006926}
6927
Douglas Gregor20606502011-10-14 15:31:12 +00006928/// \brief Rebuild the template parameters now that we know we're in a current
6929/// instantiation.
6930bool Sema::RebuildTemplateParamsInCurrentInstantiation(
6931 TemplateParameterList *Params) {
6932 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
6933 Decl *Param = Params->getParam(I);
6934
6935 // There is nothing to rebuild in a type parameter.
6936 if (isa<TemplateTypeParmDecl>(Param))
6937 continue;
6938
6939 // Rebuild the template parameter list of a template template parameter.
6940 if (TemplateTemplateParmDecl *TTP
6941 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
6942 if (RebuildTemplateParamsInCurrentInstantiation(
6943 TTP->getTemplateParameters()))
6944 return true;
6945
6946 continue;
6947 }
6948
6949 // Rebuild the type of a non-type template parameter.
6950 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
6951 TypeSourceInfo *NewTSI
6952 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
6953 NTTP->getLocation(),
6954 NTTP->getDeclName());
6955 if (!NewTSI)
6956 return true;
6957
6958 if (NewTSI != NTTP->getTypeSourceInfo()) {
6959 NTTP->setTypeSourceInfo(NewTSI);
6960 NTTP->setType(NewTSI->getType());
6961 }
6962 }
6963
6964 return false;
6965}
6966
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006967/// \brief Produces a formatted string that describes the binding of
6968/// template parameters to template arguments.
6969std::string
6970Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6971 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00006972 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006973}
6974
6975std::string
6976Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6977 const TemplateArgument *Args,
6978 unsigned NumArgs) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006979 SmallString<128> Str;
Douglas Gregor87dd6972010-12-20 16:52:59 +00006980 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006981
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006982 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006983 return std::string();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006984
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006985 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006986 if (I >= NumArgs)
6987 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006988
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006989 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006990 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006991 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00006992 Out << ", ";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006993
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006994 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006995 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006996 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006997 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006999
Douglas Gregor87dd6972010-12-20 16:52:59 +00007000 Out << " = ";
Douglas Gregor8987b232011-09-27 23:30:47 +00007001 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007002 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00007003
7004 Out << ']';
7005 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00007006}
Francois Pichet8387e2a2011-04-22 22:18:13 +00007007
7008void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
7009 if (!FD)
7010 return;
7011 FD->setLateTemplateParsed(Flag);
7012}
7013
7014bool Sema::IsInsideALocalClassWithinATemplateFunction() {
7015 DeclContext *DC = CurContext;
7016
7017 while (DC) {
7018 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
7019 const FunctionDecl *FD = RD->isLocalClass();
7020 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
7021 } else if (DC->isTranslationUnit() || DC->isNamespace())
7022 return false;
7023
7024 DC = DC->getParent();
7025 }
7026 return false;
7027}