blob: 37eeee2f886764afedb49d0e10fb652be205c401 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregor15acfb92009-08-06 16:20:37 +000012#include "TreeTransform.h"
Larisse Voufo39a1e502013-08-06 01:03:05 +000013#include "clang/AST/ASTConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "clang/AST/ASTContext.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000015#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
John McCalla020a012010-10-20 05:44:58 +000019#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000020#include "clang/AST/TypeVisitor.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000031#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000032#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000033#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000034using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000036
John McCall9b72f892010-11-10 02:40:36 +000037// Exported for use by Parser.
38SourceRange
39clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
40 unsigned N) {
41 if (!N) return SourceRange();
42 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
43}
44
Douglas Gregorb7bfe792009-09-02 22:59:36 +000045/// \brief Determine whether the declaration found is acceptable as the name
46/// of a template and, if so, return that template declaration. Otherwise,
47/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000048static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000049 NamedDecl *Orig,
50 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000051 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000052
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000053 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000055 return nullptr;
56
John McCalle9cccd82010-06-16 08:42:20 +000057 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000058 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
61 // C++ [temp.local]p1:
62 // Like normal (non-template) classes, class templates have an
63 // injected-class-name (Clause 9). The injected-class-name
64 // can be used with or without a template-argument-list. When
65 // it is used without a template-argument-list, it is
66 // equivalent to the injected-class-name followed by the
67 // template-parameters of the class template enclosed in
68 // <>. When it is used with a template-argument-list, it
69 // refers to the specified class template specialization,
70 // which could be the current specialization or another
71 // specialization.
72 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000073 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000074 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
76
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
80 }
Mike Stump11289f42009-09-09 15:08:12 +000081
Craig Topperc3ec1492014-05-26 06:22:03 +000082 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Craig Topperc3ec1492014-05-26 06:22:03 +000085 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000086}
87
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000088void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000090 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000092 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000095 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +000097 if (!Repl)
98 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000099 else if (Repl != Orig) {
100
101 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000103 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // one base class). If all of the injected-class-names that are found
105 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000108 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000110 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 filter.erase();
112 continue;
113 }
John McCallbd8062d2010-08-13 07:02:08 +0000114
115 // FIXME: we promote access to public here as a workaround to
116 // the fact that LookupResult doesn't let us remember that we
117 // found this template through a particular injected class name,
118 // which means we end up doing nasty things to the invariants.
119 // Pretending that access is public is *much* safer.
120 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000121 }
John McCalle66edc12009-11-24 19:00:30 +0000122 }
123 filter.done();
124}
125
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000126bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000130 return true;
131
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000132 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133}
134
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000135TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000136 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000137 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000138 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000139 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000140 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000143 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000144
Douglas Gregor3cf81312009-11-03 23:16:33 +0000145 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000146 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
151 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000152
Douglas Gregor3cf81312009-11-03 23:16:33 +0000153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
156 break;
157
Alexis Hunted0530f2009-11-28 08:58:14 +0000158 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
160 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000161
Douglas Gregor3cf81312009-11-03 23:16:33 +0000162 default:
163 return TNK_Non_template;
164 }
Mike Stump11289f42009-09-09 15:08:12 +0000165
John McCallba7bf592010-08-24 05:47:05 +0000166 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000174 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000175
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000178 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000179 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000180
John McCalld28ae272009-12-02 08:04:21 +0000181 TemplateName Template;
182 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 unsigned ResultCount = R.end() - R.begin();
185 if (ResultCount > 1) {
186 // We assume that we'll preserve the qualifier from a function
187 // template name in other ways.
188 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
189 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000193 } else {
John McCalld28ae272009-12-02 08:04:21 +0000194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
195
196 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000200 } else {
201 Template = TemplateName(TD);
202 }
203
John McCalldcc71402010-08-13 02:23:42 +0000204 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000205 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000206
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
209 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
Larisse Voufo39a1e502013-08-06 01:03:05 +0000211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
212 TemplateKind =
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000214 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateResult = TemplateTy::make(Template);
218 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000219}
220
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000222 SourceLocation IILoc,
223 Scope *S,
224 const CXXScopeSpec *SS,
225 TemplateTy &SuggestedTemplate,
226 TemplateNameKind &SuggestedKind) {
227 // We can't recover unless there's a dependent scope specifier preceding the
228 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000229 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
232 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 // The code is missing a 'template' keyword prior to the dependent template
235 // name.
236 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
237 Diag(IILoc, diag::err_template_kw_missing)
238 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000239 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
243 return true;
244}
245
John McCalle66edc12009-11-24 19:00:30 +0000246void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000247 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000248 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000251 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000252 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000254 bool isDependent = false;
255 if (!ObjectType.isNull()) {
256 // This nested-name-specifier occurs in a member access expression, e.g.,
257 // x->B::f, and we are looking into the type of the object.
258 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
259 LookupCtx = computeDeclContext(ObjectType);
260 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000263 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000264
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
267 Found.clear();
268 return;
269 }
John McCalle66edc12009-11-24 19:00:30 +0000270 } else if (SS.isSet()) {
271 // This nested-name-specifier occurs after another nested-name-specifier,
272 // so long into the context associated with the prior nested-name-specifier.
273 LookupCtx = computeDeclContext(SS, EnteringContext);
274 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275
John McCalle66edc12009-11-24 19:00:30 +0000276 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000278 return;
279 }
280
281 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000282 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000283 if (LookupCtx) {
284 // Perform "qualified" name lookup into the declaration context we
285 // computed, which is either the type of the base of a member access
286 // expression or the declaration context associated with a prior
287 // nested-name-specifier.
288 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000289 if (!ObjectType.isNull() && Found.empty()) {
290 // C++ [basic.lookup.classref]p1:
291 // In a class member access expression (5.2.5), if the . or -> token is
292 // immediately followed by an identifier followed by a <, the
293 // identifier must be looked up to determine whether the < is the
294 // beginning of a template argument list (14.2) or a less-than operator.
295 // The identifier is first looked up in the class of the object
296 // expression. If the identifier is not found, it is then looked up in
297 // the context of the entire postfix-expression and shall name a class
298 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000301 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000302 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000303 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000304 // We cannot look into a dependent object type or nested nme
305 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000306 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000307 return;
308 } else {
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000311
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000314 }
315
Douglas Gregorc119dd52010-01-12 17:06:20 +0000316 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000319 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000332 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000333 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000334 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000337 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
340 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000343 }
John McCalle9cccd82010-06-16 08:42:20 +0000344 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000345 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000346 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000347 }
348 }
349
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000351 if (Found.empty()) {
352 if (isDependent)
353 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000354 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 }
John McCalle66edc12009-11-24 19:00:30 +0000356
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000358 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000359 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
363 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000364 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
366 LookupOrdinaryName);
367 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
John McCalle66edc12009-11-24 19:00:30 +0000370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000378 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000379 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
389 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
392 << ObjectType;
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
395
396 // Recover by taking the template that we found in the object
397 // expression's type.
398 }
399 }
400 }
401}
402
John McCallcd4b4772009-12-02 03:53:29 +0000403/// ActOnDependentIdExpression - Handle a dependent id-expression that
404/// was just parsed. This is only possible with an explicit scope
405/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000406ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000407Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000408 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000409 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000410 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000411 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000412 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
John McCallcd4b4772009-12-02 03:53:29 +0000414 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
John McCalle66edc12009-11-24 19:00:30 +0000419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000421 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000422
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000427 }
428
Abramo Bagnara7945c982012-01-27 09:46:47 +0000429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000430}
431
John McCalldadc5752010-08-24 06:29:42 +0000432ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000433Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000434 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000435 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000436 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
439 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000440}
441
Douglas Gregor5101c242008-12-05 18:15:24 +0000442/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443/// that the template parameter 'PrevDecl' is being shadowed by a new
444/// declaration at location Loc. Returns true to indicate that this is
445/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000446void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000448
449 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000450 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000451 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000452
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000456 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000459 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000460}
461
Douglas Gregor463421d2009-03-03 04:44:36 +0000462/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000463/// the parameter D to reference the templated declaration and return a pointer
464/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000465TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000468 return Temp;
469 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000470 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471}
472
Douglas Gregoreb29d182011-01-05 17:40:24 +0000473ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
481 return Result;
482}
483
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000484static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000489 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000493 return TemplateArgumentLoc(TemplateArgument(T), DI);
494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000495
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000501 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000502 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000505 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000506 else
507 TArg = Template;
508 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000509 Arg.getScopeSpec().getWithLocInContext(
510 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000511 Arg.getLocation(),
512 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000513 }
514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000516 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000517}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000519/// \brief Translates template arguments as provided by the parser
520/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000521void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000524 TemplateArgs.addArgument(translateTemplateArgument(*this,
525 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000526}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Richard Smithb80d5402013-06-25 22:21:36 +0000528static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
529 SourceLocation Loc,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
535}
536
Douglas Gregor5101c242008-12-05 18:15:24 +0000537/// ActOnTypeParameter - Called when a C++ template type parameter
538/// (e.g., "typename T") has been parsed. Typename specifies whether
539/// the keyword "typename" was used to declare the type parameter
540/// (otherwise, "class" was used), and KeyLoc is the location of the
541/// "class" or "typename" keyword. ParamName is the name of the
542/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000543/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000544/// If the type parameter has a default argument, it will be added
545/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000546Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000553 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000556 bool Invalid = false;
557
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000558 SourceLocation Loc = ParamNameLoc;
559 if (!ParamName)
560 Loc = KeyLoc;
561
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000562 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000563 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000565 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000566 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000567 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000568 if (Invalid)
569 Param->setInvalidDecl();
570
571 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
573
Douglas Gregor5101c242008-12-05 18:15:24 +0000574 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000575 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000576 IdResolver.AddDecl(Param);
577 }
578
Douglas Gregorf5500772011-01-05 15:48:55 +0000579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000582 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
585 }
586
Douglas Gregordc13ded2010-07-01 00:00:45 +0000587 // Handle the default argument, if provided.
588 if (DefaultArg) {
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregordc13ded2010-07-01 00:00:45 +0000592 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000594 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000596 UPPC_DefaultArgument))
597 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000602 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
Douglas Gregordc13ded2010-07-01 00:00:45 +0000605 Param->setDefaultArgument(DefaultTInfo, false);
606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
John McCall48871652010-08-21 09:40:31 +0000608 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000609}
610
Douglas Gregor463421d2009-03-03 04:44:36 +0000611/// \brief Check that the type of a non-type template parameter is
612/// well-formed.
613///
614/// \returns the (possibly-promoted) parameter type if valid;
615/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000616QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000617Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000618 // We don't allow variably-modified types as the type of non-type template
619 // parameters.
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
622 << T;
623 return QualType();
624 }
625
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 // C++ [temp.param]p4:
627 //
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
630 //
631 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000632 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000633 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000634 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000635 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000636 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000637 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
647 }
648
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 // C++ [temp.param]p8:
650 //
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor463421d2009-03-03 04:44:36 +0000657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
658 << T;
659
660 return QualType();
661}
662
John McCall48871652010-08-21 09:40:31 +0000663Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
664 unsigned Depth,
665 unsigned Position,
666 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000667 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000670
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000673 bool Invalid = false;
674
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
676 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000677 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000678 Invalid = true;
679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Richard Smithb80d5402013-06-25 22:21:36 +0000681 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000682 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000683 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000685 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000686 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000688 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000689 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000690
Douglas Gregor5101c242008-12-05 18:15:24 +0000691 if (Invalid)
692 Param->setInvalidDecl();
693
Richard Smithb80d5402013-06-25 22:21:36 +0000694 if (ParamName) {
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
696 ParamName);
697
Douglas Gregor5101c242008-12-05 18:15:24 +0000698 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000699 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000700 IdResolver.AddDecl(Param);
701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
Douglas Gregorf5500772011-01-05 15:48:55 +0000703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000708 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 }
710
Douglas Gregordc13ded2010-07-01 00:00:45 +0000711 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000712 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
715 return Param;
716
Douglas Gregordc13ded2010-07-01 00:00:45 +0000717 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000720 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000721 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000722 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000724 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
John McCallb268a282010-08-23 23:25:46 +0000726 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
John McCall48871652010-08-21 09:40:31 +0000729 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000730}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000731
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000732/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000733/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000734/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000735Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000737 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000738 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
741 unsigned Depth,
742 unsigned Position,
743 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000744 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
747
748 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000749 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000750 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000754 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000755 Param->setAccess(AS_public);
756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000758 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000759 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
761
John McCall48871652010-08-21 09:40:31 +0000762 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000763 IdResolver.AddDecl(Param);
764 }
765
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
770 }
771
Douglas Gregorf5500772011-01-05 15:48:55 +0000772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Douglas Gregordc13ded2010-07-01 00:00:45 +0000780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
785 //
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000793 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000796 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
800 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801
Douglas Gregordc13ded2010-07-01 00:00:45 +0000802 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804
John McCall48871652010-08-21 09:40:31 +0000805 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000806}
807
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000808/// ActOnTemplateParameterList - Builds a TemplateParameterList that
809/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000810TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000811Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000813 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000814 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000815 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000818 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000819
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821 (NamedDecl**)Params, NumParams,
Douglas Gregorbe999392009-09-15 16:23:51 +0000822 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000823}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000824
John McCall3e11ebe2010-03-15 10:12:16 +0000825static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
826 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000828}
829
John McCallfaf5fb42010-08-26 23:41:50 +0000830DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000831Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000832 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 IdentifierInfo *Name, SourceLocation NameLoc,
834 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000835 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000837 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000838 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000839 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000840 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000841 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000842 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000843 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000844 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000845
846 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000847 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000848 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849
Abramo Bagnara6150c882010-05-11 21:36:43 +0000850 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
851 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852
853 // There is no such thing as an unnamed class template.
854 if (!Name) {
855 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857 }
858
Richard Smith6483d222012-04-21 01:27:54 +0000859 // Find any previous declaration with this name. For a friend with no
860 // scope explicitly specified, we only look for tag declarations (per
861 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000862 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000863 LookupResult Previous(*this, Name, NameLoc,
864 (SS.isEmpty() && TUK == TUK_Friend)
865 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000866 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000867 if (SS.isNotEmpty() && !SS.isInvalid()) {
868 SemanticContext = computeDeclContext(SS, true);
869 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000870 // FIXME: Horrible, horrible hack! We can't currently represent this
871 // in the AST, and historically we have just ignored such friend
872 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000873 Diag(NameLoc, TUK == TUK_Friend
874 ? diag::warn_template_qualified_friend_ignored
875 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000876 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000877 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000878 }
Mike Stump11289f42009-09-09 15:08:12 +0000879
John McCall0b66eb32010-05-01 00:40:08 +0000880 if (RequireCompleteDeclContext(SS, SemanticContext))
881 return true;
882
Douglas Gregor041b0842011-10-14 15:31:12 +0000883 // If we're adding a template to a dependent context, we may need to
884 // rebuilding some of the types used within the template parameter list,
885 // now that we know what the current instantiation is.
886 if (SemanticContext->isDependentContext()) {
887 ContextRAII SavedContext(*this, SemanticContext);
888 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
889 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000890 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
891 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000892
John McCall27b18f82009-11-17 02:14:36 +0000893 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000894 } else {
895 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000896 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000899 if (Previous.isAmbiguous())
900 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901
Craig Topperc3ec1492014-05-26 06:22:03 +0000902 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000903 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000904 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000905
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000906 // If there is a previous declaration with the same name, check
907 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000908 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000909 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000910
911 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000912 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000913 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000915 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
916 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000917 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000918 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
919 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
920 PrevClassTemplate
921 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
922 ->getSpecializedTemplate();
923 }
924 }
925
John McCalld43784f2009-12-18 11:25:59 +0000926 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000927 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000928 // [...] When looking for a prior declaration of a class or a function
929 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000930 // function is neither a qualified name nor a template-id, scopes outside
931 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000932 if (!SS.isSet()) {
933 DeclContext *OutermostContext = CurContext;
934 while (!OutermostContext->isFileContext())
935 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000936
Richard Smith61e582f2012-04-20 07:12:26 +0000937 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000938 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
939 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
940 SemanticContext = PrevDecl->getDeclContext();
941 } else {
942 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000943 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000944 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000945 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000946 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000947
948 // Check that the chosen semantic context doesn't already contain a
949 // declaration of this name as a non-tag type.
950 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
951 ForRedeclaration);
952 DeclContext *LookupContext = SemanticContext;
953 while (LookupContext->isTransparentContext())
954 LookupContext = LookupContext->getLookupParent();
955 LookupQualifiedName(Previous, LookupContext);
956
957 if (Previous.isAmbiguous())
958 return true;
959
960 if (Previous.begin() != Previous.end())
961 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000962 }
John McCall90d3bb92009-12-17 23:21:11 +0000963 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000964 } else if (PrevDecl &&
965 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000966 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000968 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000969 // Ensure that the template parameter lists are compatible. Skip this check
970 // for a friend in a dependent context: the template parameter list itself
971 // could be dependent.
972 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
973 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000974 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000975 /*Complain=*/true,
976 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000977 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000978
979 // C++ [temp.class]p4:
980 // In a redeclaration, partial specialization, explicit
981 // specialization or explicit instantiation of a class template,
982 // the class-key shall agree in kind with the original class
983 // template declaration (7.1.5.3).
984 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +0000985 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
986 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000987 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000988 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000989 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000990 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000991 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000992 }
993
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000994 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000995 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000996 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +0000997 // If we have a prior definition that is not visible, treat this as
998 // simply making that previous definition visible.
999 NamedDecl *Hidden = nullptr;
1000 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001001 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001002 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1003 assert(Tmpl && "original definition of a class template is not a "
1004 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001005 makeMergedDefinitionVisible(Hidden, KWLoc);
1006 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001007 return Def;
1008 }
1009
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001010 Diag(NameLoc, diag::err_redefinition) << Name;
1011 Diag(Def->getLocation(), diag::note_previous_definition);
1012 // FIXME: Would it make sense to try to "forget" the previous
1013 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001014 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001015 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001016 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1018 // Maybe we will complain about the shadowed template parameter.
1019 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1020 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001021 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001022 } else if (PrevDecl) {
1023 // C++ [temp]p5:
1024 // A class template shall not have the same name as any other
1025 // template, class, function, object, enumeration, enumerator,
1026 // namespace, or type in the same scope (3.3), except as specified
1027 // in (14.5.4).
1028 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1029 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001030 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001031 }
1032
Douglas Gregordba32632009-02-10 19:49:53 +00001033 // Check the template parameter list of this declaration, possibly
1034 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001035 // template declaration. Skip this check for a friend in a dependent
1036 // context, because the template parameter list might be dependent.
1037 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001038 CheckTemplateParameterList(
1039 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001040 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1041 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001042 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1043 SemanticContext->isDependentContext())
1044 ? TPC_ClassTemplateMember
1045 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1046 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001047 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001048
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001049 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001051 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001052 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1053 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001054 : diag::err_member_decl_does_not_match)
1055 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001056 Invalid = true;
1057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058 }
1059
Mike Stump11289f42009-09-09 15:08:12 +00001060 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001061 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001062 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001063 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001064 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001065 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001066 if (NumOuterTemplateParamLists > 0)
1067 NewClass->setTemplateParameterListsInfo(Context,
1068 NumOuterTemplateParamLists,
1069 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001070
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001071 // Add alignment attributes if necessary; these attributes are checked when
1072 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001073 if (TUK == TUK_Definition) {
1074 AddAlignmentAttributesForRecord(NewClass);
1075 AddMsStructLayoutForRecord(NewClass);
1076 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001077
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001078 ClassTemplateDecl *NewTemplate
1079 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1080 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001081 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001082 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001083
Douglas Gregor21823bf2011-12-20 18:11:52 +00001084 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001085 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001086
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001087 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001088 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001089 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001090 assert(T->isDependentType() && "Class template type is not dependent?");
1091 (void)T;
1092
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001094 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001095 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001096 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1097 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
Anders Carlsson137108d2009-03-26 01:24:28 +00001099 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001100 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001101 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001102
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103 // Set the lexical context of these templates
1104 NewClass->setLexicalDeclContext(CurContext);
1105 NewTemplate->setLexicalDeclContext(CurContext);
1106
John McCall9bb74a52009-07-31 02:45:11 +00001107 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001108 NewClass->startDefinition();
1109
1110 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001111 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001112
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001113 if (PrevClassTemplate)
1114 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1115
Rafael Espindola385c0422012-07-13 18:04:45 +00001116 AddPushedVisibilityAttribute(NewClass);
1117
Richard Smith234ff472014-08-23 00:49:01 +00001118 if (TUK != TUK_Friend) {
1119 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1120 Scope *Outer = S;
1121 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1122 Outer = Outer->getParent();
1123 PushOnScopeChains(NewTemplate, Outer);
1124 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001125 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001126 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001127 NewClass->setAccess(PrevClassTemplate->getAccess());
1128 }
John McCall27b5c252009-09-14 21:59:20 +00001129
Richard Smith64017682013-07-17 23:53:16 +00001130 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131
John McCall27b5c252009-09-14 21:59:20 +00001132 // Friend templates are visible in fairly strange ways.
1133 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001134 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001135 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001136 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1137 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001141 FriendDecl *Friend = FriendDecl::Create(
1142 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001143 Friend->setAccess(AS_public);
1144 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001145 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001146
Douglas Gregordba32632009-02-10 19:49:53 +00001147 if (Invalid) {
1148 NewTemplate->setInvalidDecl();
1149 NewClass->setInvalidDecl();
1150 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001151
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001152 ActOnDocumentableDecl(NewTemplate);
1153
John McCall48871652010-08-21 09:40:31 +00001154 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001155}
1156
Douglas Gregored5731f2009-11-25 17:50:39 +00001157/// \brief Diagnose the presence of a default template argument on a
1158/// template parameter, which is ill-formed in certain contexts.
1159///
1160/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001161static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001162 Sema::TemplateParamListContext TPC,
1163 SourceLocation ParamLoc,
1164 SourceRange DefArgRange) {
1165 switch (TPC) {
1166 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001167 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001168 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001169 return false;
1170
1171 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001172 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001173 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001174 // A default template-argument shall not be specified in a
1175 // function template declaration or a function template
1176 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001177 // If a friend function template declaration specifies a default
1178 // template-argument, that declaration shall be a definition and shall be
1179 // the only declaration of the function template in the translation unit.
1180 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001181 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001182 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1183 : diag::ext_template_parameter_default_in_function_template)
1184 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001185 return false;
1186
1187 case Sema::TPC_ClassTemplateMember:
1188 // C++0x [temp.param]p9:
1189 // A default template-argument shall not be specified in the
1190 // template-parameter-lists of the definition of a member of a
1191 // class template that appears outside of the member's class.
1192 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1193 << DefArgRange;
1194 return true;
1195
David Majnemerba8f17a2013-06-25 22:08:55 +00001196 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001197 case Sema::TPC_FriendFunctionTemplate:
1198 // C++ [temp.param]p9:
1199 // A default template-argument shall not be specified in a
1200 // friend template declaration.
1201 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1202 << DefArgRange;
1203 return true;
1204
1205 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1206 // for friend function templates if there is only a single
1207 // declaration (and it is a definition). Strange!
1208 }
1209
David Blaikie8a40f702012-01-17 06:56:22 +00001210 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001211}
1212
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001213/// \brief Check for unexpanded parameter packs within the template parameters
1214/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001215static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1216 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001217 // A template template parameter which is a parameter pack is also a pack
1218 // expansion.
1219 if (TTP->isParameterPack())
1220 return false;
1221
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001222 TemplateParameterList *Params = TTP->getTemplateParameters();
1223 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1224 NamedDecl *P = Params->getParam(I);
1225 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001226 if (!NTTP->isParameterPack() &&
1227 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001228 NTTP->getTypeSourceInfo(),
1229 Sema::UPPC_NonTypeTemplateParameterType))
1230 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001231
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001232 continue;
1233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
1235 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001236 = dyn_cast<TemplateTemplateParmDecl>(P))
1237 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1238 return true;
1239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001241 return false;
1242}
1243
Douglas Gregordba32632009-02-10 19:49:53 +00001244/// \brief Checks the validity of a template parameter list, possibly
1245/// considering the template parameter list from a previous
1246/// declaration.
1247///
1248/// If an "old" template parameter list is provided, it must be
1249/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1250/// template parameter list.
1251///
1252/// \param NewParams Template parameter list for a new template
1253/// declaration. This template parameter list will be updated with any
1254/// default arguments that are carried through from the previous
1255/// template parameter list.
1256///
1257/// \param OldParams If provided, template parameter list from a
1258/// previous declaration of the same template. Default template
1259/// arguments will be merged from the old template parameter list to
1260/// the new template parameter list.
1261///
Douglas Gregored5731f2009-11-25 17:50:39 +00001262/// \param TPC Describes the context in which we are checking the given
1263/// template parameter list.
1264///
Douglas Gregordba32632009-02-10 19:49:53 +00001265/// \returns true if an error occurred, false otherwise.
1266bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001267 TemplateParameterList *OldParams,
1268 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001269 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregordba32632009-02-10 19:49:53 +00001271 // C++ [temp.param]p10:
1272 // The set of default template-arguments available for use with a
1273 // template declaration or definition is obtained by merging the
1274 // default arguments from the definition (if in scope) and all
1275 // declarations in scope in the same way default function
1276 // arguments are (8.3.6).
1277 bool SawDefaultArgument = false;
1278 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001279
Mike Stumpc89c8e32009-02-11 23:03:27 +00001280 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001281 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001282 if (OldParams)
1283 OldParam = OldParams->begin();
1284
Douglas Gregor0693def2011-01-27 01:40:17 +00001285 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001286 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1287 NewParamEnd = NewParams->end();
1288 NewParam != NewParamEnd; ++NewParam) {
1289 // Variables used to diagnose redundant default arguments
1290 bool RedundantDefaultArg = false;
1291 SourceLocation OldDefaultLoc;
1292 SourceLocation NewDefaultLoc;
1293
David Blaikie651c73c2011-10-19 05:19:50 +00001294 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001295 bool MissingDefaultArg = false;
1296
David Blaikie651c73c2011-10-19 05:19:50 +00001297 // Variable used to diagnose non-final parameter packs
1298 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001299
Douglas Gregordba32632009-02-10 19:49:53 +00001300 if (TemplateTypeParmDecl *NewTypeParm
1301 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001302 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303 if (NewTypeParm->hasDefaultArgument() &&
1304 DiagnoseDefaultTemplateArgument(*this, TPC,
1305 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001306 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001307 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001308 NewTypeParm->removeDefaultArgument();
1309
1310 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001311 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001312 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Richard Smithc7d48d12015-05-20 17:50:35 +00001313 // FIXME: There might be a visible declaration of this template parameter.
1314 if (OldTypeParm && !LookupResult::isVisible(*this, OldTypeParm))
1315 OldTypeParm = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Anders Carlsson327865d2009-06-12 23:20:15 +00001317 if (NewTypeParm->isParameterPack()) {
1318 assert(!NewTypeParm->hasDefaultArgument() &&
1319 "Parameter packs can't have a default argument!");
1320 SawParameterPack = true;
Mike Stump11289f42009-09-09 15:08:12 +00001321 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001322 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001323 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1324 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1325 SawDefaultArgument = true;
1326 RedundantDefaultArg = true;
1327 PreviousDefaultArgLoc = NewDefaultLoc;
1328 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1329 // Merge the default argument from the old declaration to the
1330 // new declaration.
John McCall0ad16662009-10-29 08:12:44 +00001331 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001332 true);
1333 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1334 } else if (NewTypeParm->hasDefaultArgument()) {
1335 SawDefaultArgument = true;
1336 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1337 } else if (SawDefaultArgument)
1338 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001339 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001340 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001341 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001342 if (!NewNonTypeParm->isParameterPack() &&
1343 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001345 UPPC_NonTypeTemplateParameterType)) {
1346 Invalid = true;
1347 continue;
1348 }
1349
Douglas Gregored5731f2009-11-25 17:50:39 +00001350 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351 if (NewNonTypeParm->hasDefaultArgument() &&
1352 DiagnoseDefaultTemplateArgument(*this, TPC,
1353 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001354 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001355 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001356 }
1357
Mike Stump12b8ce12009-08-04 21:02:39 +00001358 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001359 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001360 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Richard Smithfd8b64e2015-05-20 18:24:21 +00001361 if (OldNonTypeParm && !LookupResult::isVisible(*this, OldNonTypeParm))
1362 OldNonTypeParm = nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001363 if (NewNonTypeParm->isParameterPack()) {
1364 assert(!NewNonTypeParm->hasDefaultArgument() &&
1365 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001366 if (!NewNonTypeParm->isPackExpansion())
1367 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001368 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Richard Smith35828f12013-07-22 03:31:14 +00001369 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001370 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1371 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1372 SawDefaultArgument = true;
1373 RedundantDefaultArg = true;
1374 PreviousDefaultArgLoc = NewDefaultLoc;
1375 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1376 // Merge the default argument from the old declaration to the
1377 // new declaration.
Douglas Gregordba32632009-02-10 19:49:53 +00001378 // FIXME: We need to create a new kind of "default argument"
Douglas Gregorf5500772011-01-05 15:48:55 +00001379 // expression that points to a previous non-type template
Douglas Gregordba32632009-02-10 19:49:53 +00001380 // parameter.
1381 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001382 OldNonTypeParm->getDefaultArgument(),
1383 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001384 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1385 } else if (NewNonTypeParm->hasDefaultArgument()) {
1386 SawDefaultArgument = true;
1387 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1388 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001389 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001390 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001391 TemplateTemplateParmDecl *NewTemplateParm
1392 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001394 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001395 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001396 Invalid = true;
1397 continue;
1398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399
David Blaikie651c73c2011-10-19 05:19:50 +00001400 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401 if (NewTemplateParm->hasDefaultArgument() &&
1402 DiagnoseDefaultTemplateArgument(*this, TPC,
1403 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001404 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001405 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001406
1407 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001408 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Richard Smithfd8b64e2015-05-20 18:24:21 +00001410 if (OldTemplateParm && !LookupResult::isVisible(*this, OldTemplateParm))
1411 OldTemplateParm = nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001412 if (NewTemplateParm->isParameterPack()) {
1413 assert(!NewTemplateParm->hasDefaultArgument() &&
1414 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001415 if (!NewTemplateParm->isPackExpansion())
1416 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001417 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001418 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001419 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1420 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001421 SawDefaultArgument = true;
1422 RedundantDefaultArg = true;
1423 PreviousDefaultArgLoc = NewDefaultLoc;
1424 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1425 // Merge the default argument from the old declaration to the
1426 // new declaration.
Mike Stump87c57ac2009-05-16 07:39:55 +00001427 // FIXME: We need to create a new kind of "default argument" expression
1428 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001429 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001430 OldTemplateParm->getDefaultArgument(),
1431 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001432 PreviousDefaultArgLoc
1433 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001434 } else if (NewTemplateParm->hasDefaultArgument()) {
1435 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001436 PreviousDefaultArgLoc
1437 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001438 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001439 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001440 }
1441
Richard Smith1fde8ec2012-09-07 02:06:42 +00001442 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001443 // If a template parameter of a primary class template or alias template
1444 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001445 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001446 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1447 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001448 Diag((*NewParam)->getLocation(),
1449 diag::err_template_param_pack_must_be_last_template_parameter);
1450 Invalid = true;
1451 }
1452
Douglas Gregordba32632009-02-10 19:49:53 +00001453 if (RedundantDefaultArg) {
1454 // C++ [temp.param]p12:
1455 // A template-parameter shall not be given default arguments
1456 // by two different declarations in the same scope.
1457 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1458 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1459 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001460 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001461 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462 // If a template-parameter of a class template has a default
1463 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001464 // have a default template-argument supplied or be a template parameter
1465 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001466 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001467 diag::err_template_param_default_arg_missing);
1468 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1469 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001470 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001471 }
1472
1473 // If we have an old template parameter list that we're merging
1474 // in, move on to the next parameter.
1475 if (OldParams)
1476 ++OldParam;
1477 }
1478
Douglas Gregor0693def2011-01-27 01:40:17 +00001479 // We were missing some default arguments at the end of the list, so remove
1480 // all of the default arguments.
1481 if (RemoveDefaultArguments) {
1482 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1483 NewParamEnd = NewParams->end();
1484 NewParam != NewParamEnd; ++NewParam) {
1485 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1486 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001488 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1489 NTTP->removeDefaultArgument();
1490 else
1491 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1492 }
1493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494
Douglas Gregordba32632009-02-10 19:49:53 +00001495 return Invalid;
1496}
Douglas Gregord32e0282009-02-09 23:23:08 +00001497
John McCalla020a012010-10-20 05:44:58 +00001498namespace {
1499
1500/// A class which looks for a use of a certain level of template
1501/// parameter.
1502struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1503 typedef RecursiveASTVisitor<DependencyChecker> super;
1504
1505 unsigned Depth;
1506 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001507 SourceLocation MatchLoc;
1508
1509 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001510
1511 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1512 NamedDecl *ND = Params->getParam(0);
1513 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1514 Depth = PD->getDepth();
1515 } else if (NonTypeTemplateParmDecl *PD =
1516 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1517 Depth = PD->getDepth();
1518 } else {
1519 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1520 }
1521 }
1522
Richard Smith6056d5e2014-02-09 00:54:43 +00001523 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001524 if (ParmDepth >= Depth) {
1525 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001526 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001527 return true;
1528 }
1529 return false;
1530 }
1531
Richard Smith6056d5e2014-02-09 00:54:43 +00001532 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1533 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1534 }
1535
John McCalla020a012010-10-20 05:44:58 +00001536 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1537 return !Matches(T->getDepth());
1538 }
1539
1540 bool TraverseTemplateName(TemplateName N) {
1541 if (TemplateTemplateParmDecl *PD =
1542 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001543 if (Matches(PD->getDepth()))
1544 return false;
John McCalla020a012010-10-20 05:44:58 +00001545 return super::TraverseTemplateName(N);
1546 }
1547
1548 bool VisitDeclRefExpr(DeclRefExpr *E) {
1549 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001550 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1551 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001552 return false;
John McCalla020a012010-10-20 05:44:58 +00001553 return super::VisitDeclRefExpr(E);
1554 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001555
1556 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1557 return TraverseType(T->getReplacementType());
1558 }
1559
1560 bool
1561 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1562 return TraverseTemplateArgument(T->getArgumentPack());
1563 }
1564
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001565 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1566 return TraverseType(T->getInjectedSpecializationType());
1567 }
John McCalla020a012010-10-20 05:44:58 +00001568};
1569}
1570
Douglas Gregor972fe532011-05-10 18:27:06 +00001571/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001572/// list.
1573static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001574DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001575 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001576 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001577 return Checker.Match;
1578}
1579
Douglas Gregor972fe532011-05-10 18:27:06 +00001580// Find the source range corresponding to the named type in the given
1581// nested-name-specifier, if any.
1582static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1583 QualType T,
1584 const CXXScopeSpec &SS) {
1585 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1586 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1587 if (const Type *CurType = NNS->getAsType()) {
1588 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1589 return NNSLoc.getTypeLoc().getSourceRange();
1590 } else
1591 break;
1592
1593 NNSLoc = NNSLoc.getPrefix();
1594 }
1595
1596 return SourceRange();
1597}
1598
Mike Stump11289f42009-09-09 15:08:12 +00001599/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001600/// specifier, returning the template parameter list that applies to the
1601/// name.
1602///
1603/// \param DeclStartLoc the start of the declaration that has a scope
1604/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001605///
Douglas Gregor972fe532011-05-10 18:27:06 +00001606/// \param DeclLoc The location of the declaration itself.
1607///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001608/// \param SS the scope specifier that will be matched to the given template
1609/// parameter lists. This scope specifier precedes a qualified name that is
1610/// being declared.
1611///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001612/// \param TemplateId The template-id following the scope specifier, if there
1613/// is one. Used to check for a missing 'template<>'.
1614///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001615/// \param ParamLists the template parameter lists, from the outermost to the
1616/// innermost template parameter lists.
1617///
John McCalle820e5e2010-04-13 20:37:33 +00001618/// \param IsFriend Whether to apply the slightly different rules for
1619/// matching template parameters to scope specifiers in friend
1620/// declarations.
1621///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001622/// \param IsExplicitSpecialization will be set true if the entity being
1623/// declared is an explicit specialization, false otherwise.
1624///
Mike Stump11289f42009-09-09 15:08:12 +00001625/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001626/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001627/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001628/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001629/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001630/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001631TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1632 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001633 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001634 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1635 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001636 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001637 Invalid = false;
1638
1639 // The sequence of nested types to which we will match up the template
1640 // parameter lists. We first build this list by starting with the type named
1641 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001642 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001643 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001644 if (SS.getScopeRep()) {
1645 if (CXXRecordDecl *Record
1646 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1647 T = Context.getTypeDeclType(Record);
1648 else
1649 T = QualType(SS.getScopeRep()->getAsType(), 0);
1650 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001651
1652 // If we found an explicit specialization that prevents us from needing
1653 // 'template<>' headers, this will be set to the location of that
1654 // explicit specialization.
1655 SourceLocation ExplicitSpecLoc;
1656
1657 while (!T.isNull()) {
1658 NestedTypes.push_back(T);
1659
1660 // Retrieve the parent of a record type.
1661 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1662 // If this type is an explicit specialization, we're done.
1663 if (ClassTemplateSpecializationDecl *Spec
1664 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1665 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1666 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1667 ExplicitSpecLoc = Spec->getLocation();
1668 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001669 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001670 } else if (Record->getTemplateSpecializationKind()
1671 == TSK_ExplicitSpecialization) {
1672 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001673 break;
1674 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001675
1676 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1677 T = Context.getTypeDeclType(Parent);
1678 else
1679 T = QualType();
1680 continue;
1681 }
1682
1683 if (const TemplateSpecializationType *TST
1684 = T->getAs<TemplateSpecializationType>()) {
1685 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1686 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1687 T = Context.getTypeDeclType(Parent);
1688 else
1689 T = QualType();
1690 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001691 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001692 }
1693
1694 // Look one step prior in a dependent template specialization type.
1695 if (const DependentTemplateSpecializationType *DependentTST
1696 = T->getAs<DependentTemplateSpecializationType>()) {
1697 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1698 T = QualType(NNS->getAsType(), 0);
1699 else
1700 T = QualType();
1701 continue;
1702 }
1703
1704 // Look one step prior in a dependent name type.
1705 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1706 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1707 T = QualType(NNS->getAsType(), 0);
1708 else
1709 T = QualType();
1710 continue;
1711 }
1712
1713 // Retrieve the parent of an enumeration type.
1714 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1715 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1716 // check here.
1717 EnumDecl *Enum = EnumT->getDecl();
1718
1719 // Get to the parent type.
1720 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1721 T = Context.getTypeDeclType(Parent);
1722 else
1723 T = QualType();
1724 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726
Douglas Gregor972fe532011-05-10 18:27:06 +00001727 T = QualType();
1728 }
1729 // Reverse the nested types list, since we want to traverse from the outermost
1730 // to the innermost while checking template-parameter-lists.
1731 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001732
Douglas Gregor972fe532011-05-10 18:27:06 +00001733 // C++0x [temp.expl.spec]p17:
1734 // A member or a member template may be nested within many
1735 // enclosing class templates. In an explicit specialization for
1736 // such a member, the member declaration shall be preceded by a
1737 // template<> for each enclosing class template that is
1738 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001739 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001740
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001741 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001742 if (SawNonEmptyTemplateParameterList) {
1743 Diag(DeclLoc, diag::err_specialize_member_of_template)
1744 << !Recovery << Range;
1745 Invalid = true;
1746 IsExplicitSpecialization = false;
1747 return true;
1748 }
1749
1750 return false;
1751 };
1752
1753 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1754 // Check that we can have an explicit specialization here.
1755 if (CheckExplicitSpecialization(Range, true))
1756 return true;
1757
1758 // We don't have a template header, but we should.
1759 SourceLocation ExpectedTemplateLoc;
1760 if (!ParamLists.empty())
1761 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1762 else
1763 ExpectedTemplateLoc = DeclStartLoc;
1764
1765 Diag(DeclLoc, diag::err_template_spec_needs_header)
1766 << Range
1767 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1768 return false;
1769 };
1770
Douglas Gregor972fe532011-05-10 18:27:06 +00001771 unsigned ParamIdx = 0;
1772 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1773 ++TypeIdx) {
1774 T = NestedTypes[TypeIdx];
1775
1776 // Whether we expect a 'template<>' header.
1777 bool NeedEmptyTemplateHeader = false;
1778
1779 // Whether we expect a template header with parameters.
1780 bool NeedNonemptyTemplateHeader = false;
1781
1782 // For a dependent type, the set of template parameters that we
1783 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001784 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001785
Douglas Gregor373af9b2011-05-11 23:26:17 +00001786 // C++0x [temp.expl.spec]p15:
1787 // A member or a member template may be nested within many enclosing
1788 // class templates. In an explicit specialization for such a member, the
1789 // member declaration shall be preceded by a template<> for each
1790 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001791 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1792 if (ClassTemplatePartialSpecializationDecl *Partial
1793 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1794 ExpectedTemplateParams = Partial->getTemplateParameters();
1795 NeedNonemptyTemplateHeader = true;
1796 } else if (Record->isDependentType()) {
1797 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001798 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001799 ->getTemplateParameters();
1800 NeedNonemptyTemplateHeader = true;
1801 }
1802 } else if (ClassTemplateSpecializationDecl *Spec
1803 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1804 // C++0x [temp.expl.spec]p4:
1805 // Members of an explicitly specialized class template are defined
1806 // in the same manner as members of normal classes, and not using
1807 // the template<> syntax.
1808 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1809 NeedEmptyTemplateHeader = true;
1810 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001811 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001812 } else if (Record->getTemplateSpecializationKind()) {
1813 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001814 != TSK_ExplicitSpecialization &&
1815 TypeIdx == NumTypes - 1)
1816 IsExplicitSpecialization = true;
1817
1818 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001819 }
1820 } else if (const TemplateSpecializationType *TST
1821 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001822 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001823 ExpectedTemplateParams = Template->getTemplateParameters();
1824 NeedNonemptyTemplateHeader = true;
1825 }
1826 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1827 // FIXME: We actually could/should check the template arguments here
1828 // against the corresponding template parameter list.
1829 NeedNonemptyTemplateHeader = false;
1830 }
1831
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001832 // C++ [temp.expl.spec]p16:
1833 // In an explicit specialization declaration for a member of a class
1834 // template or a member template that ap- pears in namespace scope, the
1835 // member template and some of its enclosing class templates may remain
1836 // unspecialized, except that the declaration shall not explicitly
1837 // specialize a class member template if its en- closing class templates
1838 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001839 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001840 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001841 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1842 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001843 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001844 } else
1845 SawNonEmptyTemplateParameterList = true;
1846 }
1847
Douglas Gregor972fe532011-05-10 18:27:06 +00001848 if (NeedEmptyTemplateHeader) {
1849 // If we're on the last of the types, and we need a 'template<>' header
1850 // here, then it's an explicit specialization.
1851 if (TypeIdx == NumTypes - 1)
1852 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001853
1854 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001855 if (ParamLists[ParamIdx]->size() > 0) {
1856 // The header has template parameters when it shouldn't. Complain.
1857 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1858 diag::err_template_param_list_matches_nontemplate)
1859 << T
1860 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1861 ParamLists[ParamIdx]->getRAngleLoc())
1862 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1863 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001864 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001865 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001866
Douglas Gregor972fe532011-05-10 18:27:06 +00001867 // Consume this template header.
1868 ++ParamIdx;
1869 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001870 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001871
1872 if (!IsFriend)
1873 if (DiagnoseMissingExplicitSpecialization(
1874 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001875 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001876
Douglas Gregor972fe532011-05-10 18:27:06 +00001877 continue;
1878 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001879
Douglas Gregor972fe532011-05-10 18:27:06 +00001880 if (NeedNonemptyTemplateHeader) {
1881 // In friend declarations we can have template-ids which don't
1882 // depend on the corresponding template parameter lists. But
1883 // assume that empty parameter lists are supposed to match this
1884 // template-id.
1885 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001886 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001887 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001888 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001889 else
1890 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001891 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001892
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001893 if (ParamIdx < ParamLists.size()) {
1894 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001895 if (ExpectedTemplateParams &&
1896 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1897 ExpectedTemplateParams,
1898 true, TPL_TemplateMatch))
1899 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001900
Douglas Gregor972fe532011-05-10 18:27:06 +00001901 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001902 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001903 TPC_ClassTemplateMember))
1904 Invalid = true;
1905
1906 ++ParamIdx;
1907 continue;
1908 }
1909
1910 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1911 << T
1912 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1913 Invalid = true;
1914 continue;
1915 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001916 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001917
Douglas Gregord8d297c2009-07-21 23:53:31 +00001918 // If there were at least as many template-ids as there were template
1919 // parameter lists, then there are no template parameter lists remaining for
1920 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001921 if (ParamIdx >= ParamLists.size()) {
1922 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001923 // We don't have a template header for the declaration itself, but we
1924 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001925 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001926 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1927 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001928
1929 // Fabricate an empty template parameter list for the invented header.
1930 return TemplateParameterList::Create(Context, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001931 SourceLocation(), nullptr, 0,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001932 SourceLocation());
1933 }
1934
Craig Topperc3ec1492014-05-26 06:22:03 +00001935 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
Douglas Gregord8d297c2009-07-21 23:53:31 +00001938 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001939 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001940 bool HasAnyExplicitSpecHeader = false;
1941 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001942 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001943 if (ParamLists[I]->size() == 0)
1944 HasAnyExplicitSpecHeader = true;
1945 else
1946 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001947 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001948
Douglas Gregor972fe532011-05-10 18:27:06 +00001949 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001950 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1951 : diag::err_template_spec_extra_headers)
1952 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1953 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001954
1955 // If there was a specialization somewhere, such that 'template<>' is
1956 // not required, and there were any 'template<>' headers, note where the
1957 // specialization occurred.
1958 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1959 Diag(ExplicitSpecLoc,
1960 diag::note_explicit_template_spec_does_not_need_header)
1961 << NestedTypes.back();
1962
1963 // We have a template parameter list with no corresponding scope, which
1964 // means that the resulting template declaration can't be instantiated
1965 // properly (we'll end up with dependent nodes when we shouldn't).
1966 if (!AllExplicitSpecHeaders)
1967 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001968 }
Mike Stump11289f42009-09-09 15:08:12 +00001969
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001970 // C++ [temp.expl.spec]p16:
1971 // In an explicit specialization declaration for a member of a class
1972 // template or a member template that ap- pears in namespace scope, the
1973 // member template and some of its enclosing class templates may remain
1974 // unspecialized, except that the declaration shall not explicitly
1975 // specialize a class member template if its en- closing class templates
1976 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001977 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001978 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1979 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001980 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001981
Douglas Gregord8d297c2009-07-21 23:53:31 +00001982 // Return the last template parameter list, which corresponds to the
1983 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001984 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001985}
1986
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001987void Sema::NoteAllFoundTemplates(TemplateName Name) {
1988 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1989 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001990 << (isa<FunctionTemplateDecl>(Template)
1991 ? 0
1992 : isa<ClassTemplateDecl>(Template)
1993 ? 1
1994 : isa<VarTemplateDecl>(Template)
1995 ? 2
1996 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1997 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001998 return;
1999 }
2000
2001 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2002 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2003 IEnd = OST->end();
2004 I != IEnd; ++I)
2005 Diag((*I)->getLocation(), diag::note_template_declared_here)
2006 << 0 << (*I)->getDeclName();
2007
2008 return;
2009 }
2010}
2011
Douglas Gregordc572a32009-03-30 22:58:21 +00002012QualType Sema::CheckTemplateIdType(TemplateName Name,
2013 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002014 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002015 DependentTemplateName *DTN
2016 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002017 if (DTN && DTN->isIdentifier())
2018 // When building a template-id where the template-name is dependent,
2019 // assume the template is a type template. Either our assumption is
2020 // correct, or the code is ill-formed and will be diagnosed when the
2021 // dependent name is substituted.
2022 return Context.getDependentTemplateSpecializationType(ETK_None,
2023 DTN->getQualifier(),
2024 DTN->getIdentifier(),
2025 TemplateArgs);
2026
Douglas Gregordc572a32009-03-30 22:58:21 +00002027 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002028 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2029 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002030 // We might have a substituted template template parameter pack. If so,
2031 // build a template specialization type for it.
2032 if (Name.getAsSubstTemplateTemplateParmPack())
2033 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002034
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002035 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2036 << Name;
2037 NoteAllFoundTemplates(Name);
2038 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002039 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002040
Douglas Gregorc40290e2009-03-09 23:48:35 +00002041 // Check that the template argument list is well-formed for this
2042 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002043 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002044 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002045 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002046 return QualType();
2047
Douglas Gregorc40290e2009-03-09 23:48:35 +00002048 QualType CanonType;
2049
Douglas Gregor678d76c2011-07-01 01:22:09 +00002050 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002051 if (TypeAliasTemplateDecl *AliasTemplate =
2052 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002053 // Find the canonical type for this type alias template specialization.
2054 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2055 if (Pattern->isInvalidDecl())
2056 return QualType();
2057
2058 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2059 Converted.data(), Converted.size());
2060
2061 // Only substitute for the innermost template argument list.
2062 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002063 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002064 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2065 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002066 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002067
Richard Smith802c4b72012-08-23 06:16:52 +00002068 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002069 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002070 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002071 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002072
Richard Smith3f1b5d02011-05-05 21:57:07 +00002073 CanonType = SubstType(Pattern->getUnderlyingType(),
2074 TemplateArgLists, AliasTemplate->getLocation(),
2075 AliasTemplate->getDeclName());
2076 if (CanonType.isNull())
2077 return QualType();
2078 } else if (Name.isDependent() ||
2079 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002080 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002081 // This class template specialization is a dependent
2082 // type. Therefore, its canonical type is another class template
2083 // specialization type that contains all of the converted
2084 // arguments in canonical form. This ensures that, e.g., A<T> and
2085 // A<T, T> have identical types when A is declared as:
2086 //
2087 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002088 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002089 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002090 Converted.data(),
2091 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002092
Douglas Gregora8e02e72009-07-28 23:00:59 +00002093 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002094 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002095 // In the future, we need to teach getTemplateSpecializationType to only
2096 // build the canonical type and return that to us.
2097 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002098
2099 // This might work out to be a current instantiation, in which
2100 // case the canonical type needs to be the InjectedClassNameType.
2101 //
2102 // TODO: in theory this could be a simple hashtable lookup; most
2103 // changes to CurContext don't change the set of current
2104 // instantiations.
2105 if (isa<ClassTemplateDecl>(Template)) {
2106 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2107 // If we get out to a namespace, we're done.
2108 if (Ctx->isFileContext()) break;
2109
2110 // If this isn't a record, keep looking.
2111 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2112 if (!Record) continue;
2113
2114 // Look for one of the two cases with InjectedClassNameTypes
2115 // and check whether it's the same template.
2116 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2117 !Record->getDescribedClassTemplate())
2118 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
John McCall2408e322010-04-27 00:57:59 +00002120 // Fetch the injected class name type and check whether its
2121 // injected type is equal to the type we just built.
2122 QualType ICNT = Context.getTypeDeclType(Record);
2123 QualType Injected = cast<InjectedClassNameType>(ICNT)
2124 ->getInjectedSpecializationType();
2125
2126 if (CanonType != Injected->getCanonicalTypeInternal())
2127 continue;
2128
2129 // If so, the canonical type of this TST is the injected
2130 // class name type of the record we just found.
2131 assert(ICNT.isCanonical());
2132 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002133 break;
2134 }
2135 }
Mike Stump11289f42009-09-09 15:08:12 +00002136 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002137 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002138 // Find the class template specialization declaration that
2139 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002140 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002141 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002142 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002143 if (!Decl) {
2144 // This is the first time we have referenced this class template
2145 // specialization. Create the canonical declaration and add it to
2146 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002147 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002148 ClassTemplate->getTemplatedDecl()->getTagKind(),
2149 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002150 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002151 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002152 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002154 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002155 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002156 if (ClassTemplate->isOutOfLine())
2157 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002158 }
2159
Chandler Carruth2acfb222013-09-27 22:14:40 +00002160 // Diagnose uses of this specialization.
2161 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2162
Douglas Gregorc40290e2009-03-09 23:48:35 +00002163 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002164 assert(isa<RecordType>(CanonType) &&
2165 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002166 }
Mike Stump11289f42009-09-09 15:08:12 +00002167
Douglas Gregorc40290e2009-03-09 23:48:35 +00002168 // Build the fully-sugared type for this class template
2169 // specialization, which refers back to the class template
2170 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002171 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002172}
2173
John McCallfaf5fb42010-08-26 23:41:50 +00002174TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002175Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002176 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002177 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002178 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002179 SourceLocation RAngleLoc,
2180 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002181 if (SS.isInvalid())
2182 return true;
2183
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002184 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002185
Douglas Gregorc40290e2009-03-09 23:48:35 +00002186 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002187 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002188 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002189
Douglas Gregor5a064722011-02-28 17:23:35 +00002190 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002191 QualType T
2192 = Context.getDependentTemplateSpecializationType(ETK_None,
2193 DTN->getQualifier(),
2194 DTN->getIdentifier(),
2195 TemplateArgs);
2196 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002197 TypeLocBuilder TLB;
2198 DependentTemplateSpecializationTypeLoc SpecTL
2199 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002200 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2201 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002202 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002203 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002204 SpecTL.setLAngleLoc(LAngleLoc);
2205 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002206 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2207 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2208 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2209 }
2210
John McCall6b51f282009-11-23 01:53:49 +00002211 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002212
2213 if (Result.isNull())
2214 return true;
2215
Douglas Gregore7c20652011-03-02 00:47:37 +00002216 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002217 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002218 TemplateSpecializationTypeLoc SpecTL
2219 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002220 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002221 SpecTL.setTemplateNameLoc(TemplateLoc);
2222 SpecTL.setLAngleLoc(LAngleLoc);
2223 SpecTL.setRAngleLoc(RAngleLoc);
2224 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2225 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002226
Abramo Bagnara4244b432012-01-27 08:46:19 +00002227 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2228 // constructor or destructor name (in such a case, the scope specifier
2229 // will be attached to the enclosing Decl or Expr node).
2230 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002231 // Create an elaborated-type-specifier containing the nested-name-specifier.
2232 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2233 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002234 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002235 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2236 }
2237
2238 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002239}
John McCall06f6fe8d2009-09-04 01:14:41 +00002240
Douglas Gregore7c20652011-03-02 00:47:37 +00002241TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002242 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002243 SourceLocation TagLoc,
2244 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002245 SourceLocation TemplateKWLoc,
2246 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002247 SourceLocation TemplateLoc,
2248 SourceLocation LAngleLoc,
2249 ASTTemplateArgsPtr TemplateArgsIn,
2250 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002251 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002252
2253 // Translate the parser's template argument list in our AST format.
2254 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2255 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2256
2257 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002258 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002259 ElaboratedTypeKeyword Keyword
2260 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002261
Douglas Gregore7c20652011-03-02 00:47:37 +00002262 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2263 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2264 DTN->getQualifier(),
2265 DTN->getIdentifier(),
2266 TemplateArgs);
2267
2268 // Build type-source information.
2269 TypeLocBuilder TLB;
2270 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002271 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2272 SpecTL.setElaboratedKeywordLoc(TagLoc);
2273 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002274 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002275 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002276 SpecTL.setLAngleLoc(LAngleLoc);
2277 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002278 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2279 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2280 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2281 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002282
2283 if (TypeAliasTemplateDecl *TAT =
2284 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2285 // C++0x [dcl.type.elab]p2:
2286 // If the identifier resolves to a typedef-name or the simple-template-id
2287 // resolves to an alias template specialization, the
2288 // elaborated-type-specifier is ill-formed.
2289 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2290 Diag(TAT->getLocation(), diag::note_declared_at);
2291 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002292
2293 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2294 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002295 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002296
2297 // Check the tag kind
2298 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002299 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002300
John McCalld8fe9af2009-09-08 17:47:29 +00002301 IdentifierInfo *Id = D->getIdentifier();
2302 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002303
Richard Trieucaa33d32011-06-10 03:11:26 +00002304 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2305 TagLoc, *Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002306 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002307 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002308 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002309 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002310 }
2311 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002312
Douglas Gregore7c20652011-03-02 00:47:37 +00002313 // Provide source-location information for the template specialization.
2314 TypeLocBuilder TLB;
2315 TemplateSpecializationTypeLoc SpecTL
2316 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002317 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002318 SpecTL.setTemplateNameLoc(TemplateLoc);
2319 SpecTL.setLAngleLoc(LAngleLoc);
2320 SpecTL.setRAngleLoc(RAngleLoc);
2321 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2322 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002323
Douglas Gregore7c20652011-03-02 00:47:37 +00002324 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002325 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002326 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2327 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002328 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002329 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2330 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002331}
2332
Larisse Voufo39a1e502013-08-06 01:03:05 +00002333static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002334 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2335 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002336
2337static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2338 NamedDecl *PrevDecl,
2339 SourceLocation Loc,
2340 bool IsPartialSpecialization);
2341
2342static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002343
Richard Smith300e0c32013-09-24 04:49:23 +00002344static bool isTemplateArgumentTemplateParameter(
2345 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2346 switch (Arg.getKind()) {
2347 case TemplateArgument::Null:
2348 case TemplateArgument::NullPtr:
2349 case TemplateArgument::Integral:
2350 case TemplateArgument::Declaration:
2351 case TemplateArgument::Pack:
2352 case TemplateArgument::TemplateExpansion:
2353 return false;
2354
2355 case TemplateArgument::Type: {
2356 QualType Type = Arg.getAsType();
2357 const TemplateTypeParmType *TPT =
2358 Arg.getAsType()->getAs<TemplateTypeParmType>();
2359 return TPT && !Type.hasQualifiers() &&
2360 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2361 }
2362
2363 case TemplateArgument::Expression: {
2364 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2365 if (!DRE || !DRE->getDecl())
2366 return false;
2367 const NonTypeTemplateParmDecl *NTTP =
2368 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2369 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2370 }
2371
2372 case TemplateArgument::Template:
2373 const TemplateTemplateParmDecl *TTP =
2374 dyn_cast_or_null<TemplateTemplateParmDecl>(
2375 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2376 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2377 }
2378 llvm_unreachable("unexpected kind of template argument");
2379}
2380
2381static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2382 ArrayRef<TemplateArgument> Args) {
2383 if (Params->size() != Args.size())
2384 return false;
2385
2386 unsigned Depth = Params->getDepth();
2387
2388 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2389 TemplateArgument Arg = Args[I];
2390
2391 // If the parameter is a pack expansion, the argument must be a pack
2392 // whose only element is a pack expansion.
2393 if (Params->getParam(I)->isParameterPack()) {
2394 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2395 !Arg.pack_begin()->isPackExpansion())
2396 return false;
2397 Arg = Arg.pack_begin()->getPackExpansionPattern();
2398 }
2399
2400 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2401 return false;
2402 }
2403
2404 return true;
2405}
2406
Richard Smith4b55a9c2014-04-17 03:29:33 +00002407/// Convert the parser's template argument list representation into our form.
2408static TemplateArgumentListInfo
2409makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2410 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2411 TemplateId.RAngleLoc);
2412 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2413 TemplateId.NumArgs);
2414 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2415 return TemplateArgs;
2416}
2417
Larisse Voufo39a1e502013-08-06 01:03:05 +00002418DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002419 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002420 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002421 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002422 // D must be variable template id.
2423 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2424 "Variable template specialization is declared with a template it.");
2425
2426 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002427 TemplateArgumentListInfo TemplateArgs =
2428 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002429 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2430 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2431 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002432
Richard Smithbeef3452014-01-16 23:39:20 +00002433 TemplateName Name = TemplateId->Template.get();
2434
2435 // The template-id must name a variable template.
2436 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002437 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2438 if (!VarTemplate) {
2439 NamedDecl *FnTemplate;
2440 if (auto *OTS = Name.getAsOverloadedTemplate())
2441 FnTemplate = *OTS->begin();
2442 else
2443 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2444 if (FnTemplate)
2445 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2446 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002447 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2448 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002449 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002450
2451 // Check for unexpanded parameter packs in any of the template arguments.
2452 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2453 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2454 UPPC_PartialSpecialization))
2455 return true;
2456
2457 // Check that the template argument list is well-formed for this
2458 // template.
2459 SmallVector<TemplateArgument, 4> Converted;
2460 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2461 false, Converted))
2462 return true;
2463
2464 // Check that the type of this variable template specialization
2465 // matches the expected type.
2466 TypeSourceInfo *ExpectedDI;
2467 {
2468 // Do substitution on the type of the declaration
2469 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2470 Converted.data(), Converted.size());
2471 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002472 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002473 return true;
2474 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2475 ExpectedDI =
2476 SubstType(Templated->getTypeSourceInfo(),
2477 MultiLevelTemplateArgumentList(TemplateArgList),
2478 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2479 }
2480 if (!ExpectedDI)
2481 return true;
2482
Larisse Voufo39a1e502013-08-06 01:03:05 +00002483 // Find the variable template (partial) specialization declaration that
2484 // corresponds to these arguments.
2485 if (IsPartialSpecialization) {
2486 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002487 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2488 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002489 return true;
2490
2491 bool InstantiationDependent;
2492 if (!Name.isDependent() &&
2493 !TemplateSpecializationType::anyDependentTemplateArguments(
2494 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2495 InstantiationDependent)) {
2496 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2497 << VarTemplate->getDeclName();
2498 IsPartialSpecialization = false;
2499 }
Richard Smith300e0c32013-09-24 04:49:23 +00002500
2501 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2502 Converted)) {
2503 // C++ [temp.class.spec]p9b3:
2504 //
2505 // -- The argument list of the specialization shall not be identical
2506 // to the implicit argument list of the primary template.
2507 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2508 << /*variable template*/ 1
2509 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2510 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2511 // FIXME: Recover from this by treating the declaration as a redeclaration
2512 // of the primary template.
2513 return true;
2514 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002515 }
2516
Craig Topperc3ec1492014-05-26 06:22:03 +00002517 void *InsertPos = nullptr;
2518 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002519
2520 if (IsPartialSpecialization)
2521 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002522 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002523 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002524 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002525
Craig Topperc3ec1492014-05-26 06:22:03 +00002526 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002527
2528 // Check whether we can declare a variable template specialization in
2529 // the current scope.
2530 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2531 TemplateNameLoc,
2532 IsPartialSpecialization))
2533 return true;
2534
2535 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2536 // Since the only prior variable template specialization with these
2537 // arguments was referenced but not declared, reuse that
2538 // declaration node as our own, updating its source location and
2539 // the list of outer template parameters to reflect our new declaration.
2540 Specialization = PrevDecl;
2541 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002542 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002543 } else if (IsPartialSpecialization) {
2544 // Create a new class template partial specialization declaration node.
2545 VarTemplatePartialSpecializationDecl *PrevPartial =
2546 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002547 VarTemplatePartialSpecializationDecl *Partial =
2548 VarTemplatePartialSpecializationDecl::Create(
2549 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2550 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002551 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002552
2553 if (!PrevPartial)
2554 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2555 Specialization = Partial;
2556
2557 // If we are providing an explicit specialization of a member variable
2558 // template specialization, make a note of that.
2559 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002560 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002561
2562 // Check that all of the template parameters of the variable template
2563 // partial specialization are deducible from the template
2564 // arguments. If not, this variable template partial specialization
2565 // will never be used.
2566 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2567 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2568 TemplateParams->getDepth(), DeducibleParams);
2569
2570 if (!DeducibleParams.all()) {
2571 unsigned NumNonDeducible =
2572 DeducibleParams.size() - DeducibleParams.count();
2573 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002574 << /*variable template*/ 1 << (NumNonDeducible > 1)
2575 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002576 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2577 if (!DeducibleParams[I]) {
2578 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2579 if (Param->getDeclName())
2580 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2581 << Param->getDeclName();
2582 else
2583 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002584 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002585 }
2586 }
2587 }
2588 } else {
2589 // Create a new class template specialization declaration node for
2590 // this explicit specialization or friend declaration.
2591 Specialization = VarTemplateSpecializationDecl::Create(
2592 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2593 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2594 Specialization->setTemplateArgsInfo(TemplateArgs);
2595
2596 if (!PrevDecl)
2597 VarTemplate->AddSpecialization(Specialization, InsertPos);
2598 }
2599
2600 // C++ [temp.expl.spec]p6:
2601 // If a template, a member template or the member of a class template is
2602 // explicitly specialized then that specialization shall be declared
2603 // before the first use of that specialization that would cause an implicit
2604 // instantiation to take place, in every translation unit in which such a
2605 // use occurs; no diagnostic is required.
2606 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2607 bool Okay = false;
2608 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2609 // Is there any previous explicit specialization declaration?
2610 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2611 Okay = true;
2612 break;
2613 }
2614 }
2615
2616 if (!Okay) {
2617 SourceRange Range(TemplateNameLoc, RAngleLoc);
2618 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2619 << Name << Range;
2620
2621 Diag(PrevDecl->getPointOfInstantiation(),
2622 diag::note_instantiation_required_here)
2623 << (PrevDecl->getTemplateSpecializationKind() !=
2624 TSK_ImplicitInstantiation);
2625 return true;
2626 }
2627 }
2628
2629 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2630 Specialization->setLexicalDeclContext(CurContext);
2631
2632 // Add the specialization into its lexical context, so that it can
2633 // be seen when iterating through the list of declarations in that
2634 // context. However, specializations are not found by name lookup.
2635 CurContext->addDecl(Specialization);
2636
2637 // Note that this is an explicit specialization.
2638 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2639
2640 if (PrevDecl) {
2641 // Check that this isn't a redefinition of this specialization,
2642 // merging with previous declarations.
2643 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2644 ForRedeclaration);
2645 PrevSpec.addDecl(PrevDecl);
2646 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002647 } else if (Specialization->isStaticDataMember() &&
2648 Specialization->isOutOfLine()) {
2649 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002650 }
2651
2652 // Link instantiations of static data members back to the template from
2653 // which they were instantiated.
2654 if (Specialization->isStaticDataMember())
2655 Specialization->setInstantiationOfStaticDataMember(
2656 VarTemplate->getTemplatedDecl(),
2657 Specialization->getSpecializationKind());
2658
2659 return Specialization;
2660}
2661
2662namespace {
2663/// \brief A partial specialization whose template arguments have matched
2664/// a given template-id.
2665struct PartialSpecMatchResult {
2666 VarTemplatePartialSpecializationDecl *Partial;
2667 TemplateArgumentList *Args;
2668};
2669}
2670
2671DeclResult
2672Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2673 SourceLocation TemplateNameLoc,
2674 const TemplateArgumentListInfo &TemplateArgs) {
2675 assert(Template && "A variable template id without template?");
2676
2677 // Check that the template argument list is well-formed for this template.
2678 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002679 if (CheckTemplateArgumentList(
2680 Template, TemplateNameLoc,
2681 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002682 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002683 return true;
2684
2685 // Find the variable template specialization declaration that
2686 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002687 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002688 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002689 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002690 // If we already have a variable template specialization, return it.
2691 return Spec;
2692
2693 // This is the first time we have referenced this variable template
2694 // specialization. Create the canonical declaration and add it to
2695 // the set of specializations, based on the closest partial specialization
2696 // that it represents. That is,
2697 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2698 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2699 Converted.data(), Converted.size());
2700 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2701 bool AmbiguousPartialSpec = false;
2702 typedef PartialSpecMatchResult MatchResult;
2703 SmallVector<MatchResult, 4> Matched;
2704 SourceLocation PointOfInstantiation = TemplateNameLoc;
2705 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2706
2707 // 1. Attempt to find the closest partial specialization that this
2708 // specializes, if any.
2709 // If any of the template arguments is dependent, then this is probably
2710 // a placeholder for an incomplete declarative context; which must be
2711 // complete by instantiation time. Thus, do not search through the partial
2712 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002713 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2714 // Perhaps better after unification of DeduceTemplateArguments() and
2715 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002716 bool InstantiationDependent = false;
2717 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2718 TemplateArgs, InstantiationDependent)) {
2719
2720 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2721 Template->getPartialSpecializations(PartialSpecs);
2722
2723 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2724 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2725 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2726
2727 if (TemplateDeductionResult Result =
2728 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2729 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002730 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002731 FailedCandidates.addCandidate()
2732 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2733 (void)Result;
2734 } else {
2735 Matched.push_back(PartialSpecMatchResult());
2736 Matched.back().Partial = Partial;
2737 Matched.back().Args = Info.take();
2738 }
2739 }
2740
Larisse Voufo39a1e502013-08-06 01:03:05 +00002741 if (Matched.size() >= 1) {
2742 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2743 if (Matched.size() == 1) {
2744 // -- If exactly one matching specialization is found, the
2745 // instantiation is generated from that specialization.
2746 // We don't need to do anything for this.
2747 } else {
2748 // -- If more than one matching specialization is found, the
2749 // partial order rules (14.5.4.2) are used to determine
2750 // whether one of the specializations is more specialized
2751 // than the others. If none of the specializations is more
2752 // specialized than all of the other matching
2753 // specializations, then the use of the variable template is
2754 // ambiguous and the program is ill-formed.
2755 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2756 PEnd = Matched.end();
2757 P != PEnd; ++P) {
2758 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2759 PointOfInstantiation) ==
2760 P->Partial)
2761 Best = P;
2762 }
2763
2764 // Determine if the best partial specialization is more specialized than
2765 // the others.
2766 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2767 PEnd = Matched.end();
2768 P != PEnd; ++P) {
2769 if (P != Best && getMoreSpecializedPartialSpecialization(
2770 P->Partial, Best->Partial,
2771 PointOfInstantiation) != Best->Partial) {
2772 AmbiguousPartialSpec = true;
2773 break;
2774 }
2775 }
2776 }
2777
2778 // Instantiate using the best variable template partial specialization.
2779 InstantiationPattern = Best->Partial;
2780 InstantiationArgs = Best->Args;
2781 } else {
2782 // -- If no match is found, the instantiation is generated
2783 // from the primary template.
2784 // InstantiationPattern = Template->getTemplatedDecl();
2785 }
2786 }
2787
Larisse Voufo39a1e502013-08-06 01:03:05 +00002788 // 2. Create the canonical declaration.
2789 // Note that we do not instantiate the variable just yet, since
2790 // instantiation is handled in DoMarkVarDeclReferenced().
2791 // FIXME: LateAttrs et al.?
2792 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2793 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2794 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2795 if (!Decl)
2796 return true;
2797
2798 if (AmbiguousPartialSpec) {
2799 // Partial ordering did not produce a clear winner. Complain.
2800 Decl->setInvalidDecl();
2801 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2802 << Decl;
2803
2804 // Print the matching partial specializations.
2805 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2806 PEnd = Matched.end();
2807 P != PEnd; ++P)
2808 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2809 << getTemplateArgumentBindingsText(
2810 P->Partial->getTemplateParameters(), *P->Args);
2811 return true;
2812 }
2813
2814 if (VarTemplatePartialSpecializationDecl *D =
2815 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2816 Decl->setInstantiationOf(D, InstantiationArgs);
2817
2818 assert(Decl && "No variable template specialization?");
2819 return Decl;
2820}
2821
2822ExprResult
2823Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2824 const DeclarationNameInfo &NameInfo,
2825 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2826 const TemplateArgumentListInfo *TemplateArgs) {
2827
2828 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2829 *TemplateArgs);
2830 if (Decl.isInvalid())
2831 return ExprError();
2832
2833 VarDecl *Var = cast<VarDecl>(Decl.get());
2834 if (!Var->getTemplateSpecializationKind())
2835 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2836 NameInfo.getLoc());
2837
2838 // Build an ordinary singleton decl ref.
2839 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002840 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002841}
2842
John McCalldadc5752010-08-24 06:29:42 +00002843ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002844 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002845 LookupResult &R,
2846 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002847 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002848 // FIXME: Can we do any checking at this point? I guess we could check the
2849 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002850 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002851 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002852 // foo<int> could identify a single function unambiguously
2853 // This approach does NOT work, since f<int>(1);
2854 // gets resolved prior to resorting to overload resolution
2855 // i.e., template<class T> void f(double);
2856 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002857
2858 // These should be filtered out by our callers.
2859 assert(!R.empty() && "empty lookup results when building templateid");
2860 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2861
Larisse Voufo39a1e502013-08-06 01:03:05 +00002862 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002863 bool InstantiationDependent;
2864 if (R.getAsSingle<VarTemplateDecl>() &&
2865 !TemplateSpecializationType::anyDependentTemplateArguments(
2866 *TemplateArgs, InstantiationDependent)) {
2867 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2868 R.getAsSingle<VarTemplateDecl>(),
2869 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002870 }
2871
John McCall58cc69d2010-01-27 01:50:18 +00002872 // We don't want lookup warnings at this point.
2873 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002874
John McCalle66edc12009-11-24 19:00:30 +00002875 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002876 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002877 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002878 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002879 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002880 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002881 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002882
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002883 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002884}
2885
John McCalle66edc12009-11-24 19:00:30 +00002886// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002887ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002888Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002889 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002890 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002891 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002892
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002893 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002894 DeclContext *DC;
2895 if (!(DC = computeDeclContext(SS, false)) ||
2896 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002897 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002898 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002899
Douglas Gregor786123d2010-05-21 23:18:07 +00002900 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002901 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002902 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002903 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002904
John McCalle66edc12009-11-24 19:00:30 +00002905 if (R.isAmbiguous())
2906 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002907
John McCalle66edc12009-11-24 19:00:30 +00002908 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002909 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2910 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002911 return ExprError();
2912 }
2913
2914 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002915 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002916 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002917 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002918 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2919 return ExprError();
2920 }
2921
Abramo Bagnara7945c982012-01-27 09:46:47 +00002922 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002923}
2924
Douglas Gregorb67535d2009-03-31 00:43:58 +00002925/// \brief Form a dependent template name.
2926///
2927/// This action forms a dependent template name given the template
2928/// name and its (presumably dependent) scope specifier. For
2929/// example, given "MetaFun::template apply", the scope specifier \p
2930/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2931/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002932TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002933 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002934 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002935 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002936 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002937 bool EnteringContext,
2938 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002939 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2940 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002941 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002942 diag::warn_cxx98_compat_template_outside_of_template :
2943 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944 << FixItHint::CreateRemoval(TemplateKWLoc);
2945
Craig Topperc3ec1492014-05-26 06:22:03 +00002946 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002947 if (SS.isSet())
2948 LookupCtx = computeDeclContext(SS, EnteringContext);
2949 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002950 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002951 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002952 // C++0x [temp.names]p5:
2953 // If a name prefixed by the keyword template is not the name of
2954 // a template, the program is ill-formed. [Note: the keyword
2955 // template may not be applied to non-template members of class
2956 // templates. -end note ] [ Note: as is the case with the
2957 // typename prefix, the template prefix is allowed in cases
2958 // where it is not strictly necessary; i.e., when the
2959 // nested-name-specifier or the expression on the left of the ->
2960 // or . is not dependent on a template-parameter, or the use
2961 // does not appear in the scope of a template. -end note]
2962 //
2963 // Note: C++03 was more strict here, because it banned the use of
2964 // the "template" keyword prior to a template-name that was not a
2965 // dependent name. C++ DR468 relaxed this requirement (the
2966 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00002967 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00002968 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00002969 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002970 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00002971 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00002972 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2973 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00002974 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2975 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00002976 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00002977 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002978 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002979 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002980 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002981 << Name.getSourceRange()
2982 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002983 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00002984 } else {
2985 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00002986 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002987 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00002988 }
2989
Aaron Ballman4a979672014-01-03 13:56:08 +00002990 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002991
Douglas Gregor3cf81312009-11-03 23:16:33 +00002992 switch (Name.getKind()) {
2993 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00002995 Name.Identifier));
2996 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997
Douglas Gregor71395fa2009-11-04 00:56:37 +00002998 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00002999 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003000 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003001 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003002
3003 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003004 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003005
Douglas Gregor3cf81312009-11-03 23:16:33 +00003006 default:
3007 break;
3008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003010 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003011 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003012 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003013 << Name.getSourceRange()
3014 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003015 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003016}
3017
Mike Stump11289f42009-09-09 15:08:12 +00003018bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003019 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003020 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003021 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003022 QualType ArgType;
3023 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003024
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003025 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003026 switch(Arg.getKind()) {
3027 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003028 // C++ [temp.arg.type]p1:
3029 // A template-argument for a template-parameter which is a
3030 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003031 ArgType = Arg.getAsType();
3032 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003033 break;
3034 case TemplateArgument::Template: {
3035 // We have a template type parameter but the template argument
3036 // is a template without any arguments.
3037 SourceRange SR = AL.getSourceRange();
3038 TemplateName Name = Arg.getAsTemplate();
3039 Diag(SR.getBegin(), diag::err_template_missing_args)
3040 << Name << SR;
3041 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3042 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003043
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003044 return true;
3045 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003046 case TemplateArgument::Expression: {
3047 // We have a template type parameter but the template argument is an
3048 // expression; see if maybe it is missing the "typename" keyword.
3049 CXXScopeSpec SS;
3050 DeclarationNameInfo NameInfo;
3051
3052 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3053 SS.Adopt(ArgExpr->getQualifierLoc());
3054 NameInfo = ArgExpr->getNameInfo();
3055 } else if (DependentScopeDeclRefExpr *ArgExpr =
3056 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3057 SS.Adopt(ArgExpr->getQualifierLoc());
3058 NameInfo = ArgExpr->getNameInfo();
3059 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3060 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003061 if (ArgExpr->isImplicitAccess()) {
3062 SS.Adopt(ArgExpr->getQualifierLoc());
3063 NameInfo = ArgExpr->getMemberNameInfo();
3064 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003065 }
3066
Reid Kleckner377c1592014-06-10 23:29:48 +00003067 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003068 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3069 LookupParsedName(Result, CurScope, &SS);
3070
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003071 if (Result.getAsSingle<TypeDecl>() ||
3072 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003073 LookupResult::NotFoundInCurrentInstantiation) {
3074 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003075 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003076 Diag(Loc, getLangOpts().MSVCCompat
3077 ? diag::ext_ms_template_type_arg_missing_typename
3078 : diag::err_template_arg_must_be_type_suggest)
3079 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003080 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003081
3082 // Recover by synthesizing a type using the location information that we
3083 // already have.
3084 ArgType =
3085 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3086 TypeLocBuilder TLB;
3087 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3088 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3089 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3090 TL.setNameLoc(NameInfo.getLoc());
3091 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3092
3093 // Overwrite our input TemplateArgumentLoc so that we can recover
3094 // properly.
3095 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3096 TemplateArgumentLocInfo(TSI));
3097
3098 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003099 }
3100 }
3101 // fallthrough
3102 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003103 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003104 // We have a template type parameter but the template argument
3105 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003106 SourceRange SR = AL.getSourceRange();
3107 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003108 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003109
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003110 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003111 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003112 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003113
Reid Kleckner377c1592014-06-10 23:29:48 +00003114 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003115 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003116
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003117 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003118 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003119
3120 // Objective-C ARC:
3121 // If an explicitly-specified template argument type is a lifetime type
3122 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003123 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003124 ArgType->isObjCLifetimeType() &&
3125 !ArgType.getObjCLifetime()) {
3126 Qualifiers Qs;
3127 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3128 ArgType = Context.getQualifiedType(ArgType, Qs);
3129 }
3130
3131 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003132 return false;
3133}
3134
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003135/// \brief Substitute template arguments into the default template argument for
3136/// the given template type parameter.
3137///
3138/// \param SemaRef the semantic analysis object for which we are performing
3139/// the substitution.
3140///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003142/// for.
3143///
3144/// \param TemplateLoc the location of the template name that started the
3145/// template-id we are checking.
3146///
3147/// \param RAngleLoc the location of the right angle bracket ('>') that
3148/// terminates the template-id.
3149///
3150/// \param Param the template template parameter whose default we are
3151/// substituting into.
3152///
3153/// \param Converted the list of template arguments provided for template
3154/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003155/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003156static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003157SubstDefaultTemplateArgument(Sema &SemaRef,
3158 TemplateDecl *Template,
3159 SourceLocation TemplateLoc,
3160 SourceLocation RAngleLoc,
3161 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003162 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003163 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003164
3165 // If the argument type is dependent, instantiate it now based
3166 // on the previously-computed template arguments.
3167 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003168 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003169 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003170 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003171 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003172 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
David Majnemer89189202013-08-28 23:48:32 +00003174 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3175 Converted.data(), Converted.size());
3176
3177 // Only substitute for the innermost template argument list.
3178 MultiLevelTemplateArgumentList TemplateArgLists;
3179 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3180 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3181 TemplateArgLists.addOuterTemplateArguments(None);
3182
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003183 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003184 ArgType =
3185 SemaRef.SubstType(ArgType, TemplateArgLists,
3186 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003187 }
3188
3189 return ArgType;
3190}
3191
3192/// \brief Substitute template arguments into the default template argument for
3193/// the given non-type template parameter.
3194///
3195/// \param SemaRef the semantic analysis object for which we are performing
3196/// the substitution.
3197///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003199/// for.
3200///
3201/// \param TemplateLoc the location of the template name that started the
3202/// template-id we are checking.
3203///
3204/// \param RAngleLoc the location of the right angle bracket ('>') that
3205/// terminates the template-id.
3206///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003207/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003208/// substituting into.
3209///
3210/// \param Converted the list of template arguments provided for template
3211/// parameters that precede \p Param in the template parameter list.
3212///
3213/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003214static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003215SubstDefaultTemplateArgument(Sema &SemaRef,
3216 TemplateDecl *Template,
3217 SourceLocation TemplateLoc,
3218 SourceLocation RAngleLoc,
3219 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003220 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003221 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003222 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003223 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003224 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003225 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003226
David Majnemer89189202013-08-28 23:48:32 +00003227 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3228 Converted.data(), Converted.size());
3229
3230 // Only substitute for the innermost template argument list.
3231 MultiLevelTemplateArgumentList TemplateArgLists;
3232 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3233 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3234 TemplateArgLists.addOuterTemplateArguments(None);
3235
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003236 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003237 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003238 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003239}
3240
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003241/// \brief Substitute template arguments into the default template argument for
3242/// the given template template parameter.
3243///
3244/// \param SemaRef the semantic analysis object for which we are performing
3245/// the substitution.
3246///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003247/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003248/// for.
3249///
3250/// \param TemplateLoc the location of the template name that started the
3251/// template-id we are checking.
3252///
3253/// \param RAngleLoc the location of the right angle bracket ('>') that
3254/// terminates the template-id.
3255///
3256/// \param Param the template template parameter whose default we are
3257/// substituting into.
3258///
3259/// \param Converted the list of template arguments provided for template
3260/// parameters that precede \p Param in the template parameter list.
3261///
Douglas Gregordf846d12011-03-02 18:46:51 +00003262/// \param QualifierLoc Will be set to the nested-name-specifier (with
3263/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003264///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003265/// \returns the substituted template argument, or NULL if an error occurred.
3266static TemplateName
3267SubstDefaultTemplateArgument(Sema &SemaRef,
3268 TemplateDecl *Template,
3269 SourceLocation TemplateLoc,
3270 SourceLocation RAngleLoc,
3271 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003272 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003273 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003274 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003275 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003276 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003277 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278
David Majnemer89189202013-08-28 23:48:32 +00003279 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3280 Converted.data(), Converted.size());
3281
3282 // Only substitute for the innermost template argument list.
3283 MultiLevelTemplateArgumentList TemplateArgLists;
3284 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3285 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3286 TemplateArgLists.addOuterTemplateArguments(None);
3287
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003288 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003289 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003290 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003291 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003292 QualifierLoc =
3293 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003294 if (!QualifierLoc)
3295 return TemplateName();
3296 }
David Majnemer89189202013-08-28 23:48:32 +00003297
3298 return SemaRef.SubstTemplateName(
3299 QualifierLoc,
3300 Param->getDefaultArgument().getArgument().getAsTemplate(),
3301 Param->getDefaultArgument().getTemplateNameLoc(),
3302 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003303}
3304
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003305/// \brief If the given template parameter has a default template
3306/// argument, substitute into that default template argument and
3307/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003309Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3310 SourceLocation TemplateLoc,
3311 SourceLocation RAngleLoc,
3312 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003313 SmallVectorImpl<TemplateArgument>
3314 &Converted,
3315 bool &HasDefaultArg) {
3316 HasDefaultArg = false;
3317
3318 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003319 if (!TypeParm->hasDefaultArgument())
3320 return TemplateArgumentLoc();
3321
Richard Smithc87b9382013-07-04 01:01:24 +00003322 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003323 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003324 TemplateLoc,
3325 RAngleLoc,
3326 TypeParm,
3327 Converted);
3328 if (DI)
3329 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3330
3331 return TemplateArgumentLoc();
3332 }
3333
3334 if (NonTypeTemplateParmDecl *NonTypeParm
3335 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3336 if (!NonTypeParm->hasDefaultArgument())
3337 return TemplateArgumentLoc();
3338
Richard Smithc87b9382013-07-04 01:01:24 +00003339 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003340 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003341 TemplateLoc,
3342 RAngleLoc,
3343 NonTypeParm,
3344 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003345 if (Arg.isInvalid())
3346 return TemplateArgumentLoc();
3347
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003348 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003349 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3350 }
3351
3352 TemplateTemplateParmDecl *TempTempParm
3353 = cast<TemplateTemplateParmDecl>(Param);
3354 if (!TempTempParm->hasDefaultArgument())
3355 return TemplateArgumentLoc();
3356
Richard Smithc87b9382013-07-04 01:01:24 +00003357 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003358 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003359 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003361 RAngleLoc,
3362 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003363 Converted,
3364 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003365 if (TName.isNull())
3366 return TemplateArgumentLoc();
3367
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003369 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003370 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3371}
3372
Douglas Gregorda0fb532009-11-11 19:31:23 +00003373/// \brief Check that the given template argument corresponds to the given
3374/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003375///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003377/// checked.
3378///
Richard Trieu15b66532015-01-24 02:48:32 +00003379/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003380///
3381/// \param Template The template in which the template argument resides.
3382///
3383/// \param TemplateLoc The location of the template name for the template
3384/// whose argument list we're matching.
3385///
3386/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3387/// the template argument list.
3388///
3389/// \param ArgumentPackIndex The index into the argument pack where this
3390/// argument will be placed. Only valid if the parameter is a parameter pack.
3391///
3392/// \param Converted The checked, converted argument will be added to the
3393/// end of this small vector.
3394///
3395/// \param CTAK Describes how we arrived at this particular template argument:
3396/// explicitly written, deduced, etc.
3397///
3398/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003399bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003400 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003401 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003402 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003403 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003404 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003405 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003406 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003407 // Check template type parameters.
3408 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003409 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410
Douglas Gregoreebed722009-11-11 19:41:09 +00003411 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003413 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003414 // with the template arguments we've seen thus far. But if the
3415 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003416 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003417 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3418 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Peter Collingbourne01687632010-12-10 17:08:53 +00003420 if (NTTPType->isDependentType() &&
3421 !isa<TemplateTemplateParmDecl>(Template) &&
3422 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003423 // Do substitution on the type of the non-type template parameter.
3424 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003425 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003426 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003427 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003428 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003429
3430 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003431 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003432 NTTPType = SubstType(NTTPType,
3433 MultiLevelTemplateArgumentList(TemplateArgs),
3434 NTTP->getLocation(),
3435 NTTP->getDeclName());
3436 // If that worked, check the non-type template parameter type
3437 // for validity.
3438 if (!NTTPType.isNull())
3439 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3440 NTTP->getLocation());
3441 if (NTTPType.isNull())
3442 return true;
3443 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregorda0fb532009-11-11 19:31:23 +00003445 switch (Arg.getArgument().getKind()) {
3446 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003447 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448
Douglas Gregorda0fb532009-11-11 19:31:23 +00003449 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003450 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003451 ExprResult Res =
3452 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3453 Result, CTAK);
3454 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003455 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Richard Trieu15b66532015-01-24 02:48:32 +00003457 // If the resulting expression is new, then use it in place of the
3458 // old expression in the template argument.
3459 if (Res.get() != Arg.getArgument().getAsExpr()) {
3460 TemplateArgument TA(Res.get());
3461 Arg = TemplateArgumentLoc(TA, Res.get());
3462 }
3463
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003464 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003465 break;
3466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
Douglas Gregorda0fb532009-11-11 19:31:23 +00003468 case TemplateArgument::Declaration:
3469 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003470 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003471 // We've already checked this template argument, so just copy
3472 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003473 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003474 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregorda0fb532009-11-11 19:31:23 +00003476 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003477 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003478 // We were given a template template argument. It may not be ill-formed;
3479 // see below.
3480 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003481 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3482 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003483 // We have a template argument such as \c T::template X, which we
3484 // parsed as a template template argument. However, since we now
3485 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003486 // template name into an expression.
3487
3488 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3489 Arg.getTemplateNameLoc());
3490
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003491 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003492 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003493 // FIXME: the template-template arg was a DependentTemplateName,
3494 // so it was provided with a template keyword. However, its source
3495 // location is not stored in the template argument structure.
3496 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003497 ExprResult E = DependentScopeDeclRefExpr::Create(
3498 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3499 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003501 // If we parsed the template argument as a pack expansion, create a
3502 // pack expansion expression.
3503 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003504 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003505 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003506 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508
Douglas Gregorda0fb532009-11-11 19:31:23 +00003509 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003510 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003511 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003512 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003514 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003515 break;
3516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
Douglas Gregorda0fb532009-11-11 19:31:23 +00003518 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003519 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003520 // therefore cannot be a non-type template argument.
3521 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3522 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523
Douglas Gregorda0fb532009-11-11 19:31:23 +00003524 Diag(Param->getLocation(), diag::note_template_param_here);
3525 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003526
Douglas Gregorda0fb532009-11-11 19:31:23 +00003527 case TemplateArgument::Type: {
3528 // We have a non-type template parameter but the template
3529 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530
Douglas Gregorda0fb532009-11-11 19:31:23 +00003531 // C++ [temp.arg]p2:
3532 // In a template-argument, an ambiguity between a type-id and
3533 // an expression is resolved to a type-id, regardless of the
3534 // form of the corresponding template-parameter.
3535 //
3536 // We warn specifically about this case, since it can be rather
3537 // confusing for users.
3538 QualType T = Arg.getArgument().getAsType();
3539 SourceRange SR = Arg.getSourceRange();
3540 if (T->isFunctionType())
3541 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3542 else
3543 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3544 Diag(Param->getLocation(), diag::note_template_param_here);
3545 return true;
3546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547
Douglas Gregorda0fb532009-11-11 19:31:23 +00003548 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003549 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregorda0fb532009-11-11 19:31:23 +00003552 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553 }
3554
3555
Douglas Gregorda0fb532009-11-11 19:31:23 +00003556 // Check template template parameters.
3557 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Douglas Gregorda0fb532009-11-11 19:31:23 +00003559 // Substitute into the template parameter list of the template
3560 // template parameter, since previously-supplied template arguments
3561 // may appear within the template template parameter.
3562 {
3563 // Set up a template instantiation context.
3564 LocalInstantiationScope Scope(*this);
3565 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003566 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003567 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003568 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003569 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003570
3571 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003572 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003573 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003575 MultiLevelTemplateArgumentList(TemplateArgs)));
3576 if (!TempParm)
3577 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579
Douglas Gregorda0fb532009-11-11 19:31:23 +00003580 switch (Arg.getArgument().getKind()) {
3581 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003582 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregorda0fb532009-11-11 19:31:23 +00003584 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003585 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003586 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003587 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003589 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591
Douglas Gregorda0fb532009-11-11 19:31:23 +00003592 case TemplateArgument::Expression:
3593 case TemplateArgument::Type:
3594 // We have a template template parameter but the template
3595 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003596 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003597 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003598 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregorda0fb532009-11-11 19:31:23 +00003600 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003601 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003602 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003603 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003604 case TemplateArgument::NullPtr:
3605 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606
Douglas Gregorda0fb532009-11-11 19:31:23 +00003607 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003608 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610
Douglas Gregorda0fb532009-11-11 19:31:23 +00003611 return false;
3612}
3613
Douglas Gregor8e072612012-02-03 07:34:46 +00003614/// \brief Diagnose an arity mismatch in the
3615static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3616 SourceLocation TemplateLoc,
3617 TemplateArgumentListInfo &TemplateArgs) {
3618 TemplateParameterList *Params = Template->getTemplateParameters();
3619 unsigned NumParams = Params->size();
3620 unsigned NumArgs = TemplateArgs.size();
3621
3622 SourceRange Range;
3623 if (NumArgs > NumParams)
3624 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3625 TemplateArgs.getRAngleLoc());
3626 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3627 << (NumArgs > NumParams)
3628 << (isa<ClassTemplateDecl>(Template)? 0 :
3629 isa<FunctionTemplateDecl>(Template)? 1 :
3630 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3631 << Template << Range;
3632 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3633 << Params->getSourceRange();
3634 return true;
3635}
3636
Richard Smith1fde8ec2012-09-07 02:06:42 +00003637/// \brief Check whether the template parameter is a pack expansion, and if so,
3638/// determine the number of parameters produced by that expansion. For instance:
3639///
3640/// \code
3641/// template<typename ...Ts> struct A {
3642/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3643/// };
3644/// \endcode
3645///
3646/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3647/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003648static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003649 if (NonTypeTemplateParmDecl *NTTP
3650 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3651 if (NTTP->isExpandedParameterPack())
3652 return NTTP->getNumExpansionTypes();
3653 }
3654
3655 if (TemplateTemplateParmDecl *TTP
3656 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3657 if (TTP->isExpandedParameterPack())
3658 return TTP->getNumExpansionTemplateParameters();
3659 }
3660
David Blaikie7a30dc52013-02-21 01:47:18 +00003661 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003662}
3663
Douglas Gregord32e0282009-02-09 23:23:08 +00003664/// \brief Check that the given template argument list is well-formed
3665/// for specializing the given template.
3666bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3667 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003668 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003669 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003670 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003671 // Make a copy of the template arguments for processing. Only make the
3672 // changes at the end when successful in matching the arguments to the
3673 // template.
3674 TemplateArgumentListInfo NewArgs = TemplateArgs;
3675
Douglas Gregord32e0282009-02-09 23:23:08 +00003676 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003677
Richard Trieu15b66532015-01-24 02:48:32 +00003678 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003679
Mike Stump11289f42009-09-09 15:08:12 +00003680 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003681 // [...] The type and form of each template-argument specified in
3682 // a template-id shall match the type and form specified for the
3683 // corresponding parameter declared by the template in its
3684 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003685 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003686 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003687 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003688 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003689 for (TemplateParameterList::iterator Param = Params->begin(),
3690 ParamEnd = Params->end();
3691 Param != ParamEnd; /* increment in loop */) {
3692 // If we have an expanded parameter pack, make sure we don't have too
3693 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003694 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003695 if (*Expansions == ArgumentPack.size()) {
3696 // We're done with this parameter pack. Pack up its arguments and add
3697 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003698 Converted.push_back(
3699 TemplateArgument::CreatePackCopy(Context,
3700 ArgumentPack.data(),
3701 ArgumentPack.size()));
3702 ArgumentPack.clear();
3703
Richard Smith1fde8ec2012-09-07 02:06:42 +00003704 // This argument is assigned to the next parameter.
3705 ++Param;
3706 continue;
3707 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3708 // Not enough arguments for this parameter pack.
3709 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3710 << false
3711 << (isa<ClassTemplateDecl>(Template)? 0 :
3712 isa<FunctionTemplateDecl>(Template)? 1 :
3713 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3714 << Template;
3715 Diag(Template->getLocation(), diag::note_template_decl_here)
3716 << Params->getSourceRange();
3717 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003718 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720
Richard Smith1fde8ec2012-09-07 02:06:42 +00003721 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003722 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003723 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003725 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003726 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
Richard Smith96d71c32014-11-12 23:38:38 +00003728 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003729 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003730 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3731 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003732 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003733 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003734 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003735 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003736 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003737 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003738 Diag((*Param)->getLocation(), diag::note_template_param_here);
3739 return true;
3740 }
3741
Richard Smith1fde8ec2012-09-07 02:06:42 +00003742 // We're now done with this argument.
3743 ++ArgIdx;
3744
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003745 if ((*Param)->isTemplateParameterPack()) {
3746 // The template parameter was a template parameter pack, so take the
3747 // deduced argument and place it on the argument pack. Note that we
3748 // stay on the same template parameter so that we can deduce more
3749 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003750 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003751 } else {
3752 // Move to the next template parameter.
3753 ++Param;
3754 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003755
Richard Smith96d71c32014-11-12 23:38:38 +00003756 // If we just saw a pack expansion into a non-pack, then directly convert
3757 // the remaining arguments, because we don't know what parameters they'll
3758 // match up with.
3759 if (PackExpansionIntoNonPack) {
3760 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003761 // If we were part way through filling in an expanded parameter pack,
3762 // fall back to just producing individual arguments.
3763 Converted.insert(Converted.end(),
3764 ArgumentPack.begin(), ArgumentPack.end());
3765 ArgumentPack.clear();
3766 }
3767
3768 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003769 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003770 ++ArgIdx;
3771 }
3772
Richard Smith1fde8ec2012-09-07 02:06:42 +00003773 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003774 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003775
Douglas Gregor84d49a22009-11-11 21:54:23 +00003776 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778
Douglas Gregor2f157c92011-06-03 02:59:40 +00003779 // If we're checking a partial template argument list, we're done.
3780 if (PartialTemplateArgs) {
3781 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3782 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3783 ArgumentPack.data(),
3784 ArgumentPack.size()));
3785
Richard Smith1fde8ec2012-09-07 02:06:42 +00003786 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003787 }
3788
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003790 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003791 if ((*Param)->isTemplateParameterPack()) {
3792 assert(!getExpandedPackSize(*Param) &&
3793 "Should have dealt with this already");
3794
3795 // A non-expanded parameter pack before the end of the parameter list
3796 // only occurs for an ill-formed template parameter list, unless we've
3797 // got a partial argument list for a function template, so just bail out.
3798 if (Param + 1 != ParamEnd)
3799 return true;
3800
Eli Friedmanb826a002012-09-26 02:36:12 +00003801 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3802 ArgumentPack.data(),
3803 ArgumentPack.size()));
3804 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003805
3806 ++Param;
3807 continue;
3808 }
3809
Douglas Gregor8e072612012-02-03 07:34:46 +00003810 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003811 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812
Douglas Gregor84d49a22009-11-11 21:54:23 +00003813 // Retrieve the default template argument from the template
3814 // parameter. For each kind of template parameter, we substitute the
3815 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003817 // the default argument.
3818 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003819 if (!TTP->hasDefaultArgument())
Richard Trieu15b66532015-01-24 02:48:32 +00003820 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003821
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003823 Template,
3824 TemplateLoc,
3825 RAngleLoc,
3826 TTP,
3827 Converted);
3828 if (!ArgType)
3829 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003830
Douglas Gregor84d49a22009-11-11 21:54:23 +00003831 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3832 ArgType);
3833 } else if (NonTypeTemplateParmDecl *NTTP
3834 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003835 if (!NTTP->hasDefaultArgument())
Richard Trieu15b66532015-01-24 02:48:32 +00003836 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003837
John McCalldadc5752010-08-24 06:29:42 +00003838 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839 TemplateLoc,
3840 RAngleLoc,
3841 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003842 Converted);
3843 if (E.isInvalid())
3844 return true;
3845
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003846 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003847 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3848 } else {
3849 TemplateTemplateParmDecl *TempParm
3850 = cast<TemplateTemplateParmDecl>(*Param);
3851
Douglas Gregor8e072612012-02-03 07:34:46 +00003852 if (!TempParm->hasDefaultArgument())
Richard Trieu15b66532015-01-24 02:48:32 +00003853 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003854
Douglas Gregordf846d12011-03-02 18:46:51 +00003855 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003856 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003857 TemplateLoc,
3858 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003859 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003860 Converted,
3861 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003862 if (Name.isNull())
3863 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864
Douglas Gregor9d802122011-03-02 17:09:35 +00003865 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3866 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003868
Douglas Gregor84d49a22009-11-11 21:54:23 +00003869 // Introduce an instantiation record that describes where we are using
3870 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003871 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3872 SourceRange(TemplateLoc, RAngleLoc));
3873 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003874 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875
Douglas Gregor84d49a22009-11-11 21:54:23 +00003876 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003877 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003878 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003879 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880
Richard Trieu15b66532015-01-24 02:48:32 +00003881 // Core issue 150 (assumed resolution): if this is a template template
3882 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003883 // template definition.
3884 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003885 NewArgs.addArgument(Arg);
3886
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003887 // Move to the next template parameter and argument.
3888 ++Param;
3889 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891
Richard Smith07f79912014-06-06 16:00:50 +00003892 // If we're performing a partial argument substitution, allow any trailing
3893 // pack expansions; they might be empty. This can happen even if
3894 // PartialTemplateArgs is false (the list of arguments is complete but
3895 // still dependent).
3896 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3897 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003898 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3899 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003900 }
3901
Douglas Gregor8e072612012-02-03 07:34:46 +00003902 // If we have any leftover arguments, then there were too many arguments.
3903 // Complain and fail.
3904 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003905 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3906
3907 // No problems found with the new argument list, propagate changes back
3908 // to caller.
3909 TemplateArgs = NewArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
Richard Smith1fde8ec2012-09-07 02:06:42 +00003911 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003912}
3913
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003914namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915 class UnnamedLocalNoLinkageFinder
3916 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003917 {
3918 Sema &S;
3919 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003920
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003921 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003923 public:
3924 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3925
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926 bool Visit(QualType T) {
3927 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003930#define TYPE(Class, Parent) \
3931 bool Visit##Class##Type(const Class##Type *);
3932#define ABSTRACT_TYPE(Class, Parent) \
3933 bool Visit##Class##Type(const Class##Type *) { return false; }
3934#define NON_CANONICAL_TYPE(Class, Parent) \
3935 bool Visit##Class##Type(const Class##Type *) { return false; }
3936#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003938 bool VisitTagDecl(const TagDecl *Tag);
3939 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3940 };
3941}
3942
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003944 return false;
3945}
3946
3947bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3948 return Visit(T->getElementType());
3949}
3950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003952 return Visit(T->getPointeeType());
3953}
3954
3955bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003957 return Visit(T->getPointeeType());
3958}
3959
3960bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003962 return Visit(T->getPointeeType());
3963}
3964
3965bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003967 return Visit(T->getPointeeType());
3968}
3969
3970bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003972 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3973}
3974
3975bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003977 return Visit(T->getElementType());
3978}
3979
3980bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003982 return Visit(T->getElementType());
3983}
3984
3985bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003987 return Visit(T->getElementType());
3988}
3989
3990bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003992 return Visit(T->getElementType());
3993}
3994
3995bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003996 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003997 return Visit(T->getElementType());
3998}
3999
4000bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4001 return Visit(T->getElementType());
4002}
4003
4004bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4005 return Visit(T->getElementType());
4006}
4007
4008bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4009 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004010 for (const auto &A : T->param_types()) {
4011 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004012 return true;
4013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Alp Toker314cc812014-01-25 16:55:45 +00004015 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004016}
4017
4018bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4019 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004020 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004021}
4022
4023bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4024 const UnresolvedUsingType*) {
4025 return false;
4026}
4027
4028bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4029 return false;
4030}
4031
4032bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4033 return Visit(T->getUnderlyingType());
4034}
4035
4036bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4037 return false;
4038}
4039
Alexis Hunte852b102011-05-24 22:41:36 +00004040bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4041 const UnaryTransformType*) {
4042 return false;
4043}
4044
Richard Smith30482bc2011-02-20 03:19:35 +00004045bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4046 return Visit(T->getDeducedType());
4047}
4048
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004049bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4050 return VisitTagDecl(T->getDecl());
4051}
4052
4053bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4054 return VisitTagDecl(T->getDecl());
4055}
4056
4057bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4058 const TemplateTypeParmType*) {
4059 return false;
4060}
4061
Douglas Gregorada4b792011-01-14 02:55:32 +00004062bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4063 const SubstTemplateTypeParmPackType *) {
4064 return false;
4065}
4066
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004067bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4068 const TemplateSpecializationType*) {
4069 return false;
4070}
4071
4072bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4073 const InjectedClassNameType* T) {
4074 return VisitTagDecl(T->getDecl());
4075}
4076
4077bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4078 const DependentNameType* T) {
4079 return VisitNestedNameSpecifier(T->getQualifier());
4080}
4081
4082bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4083 const DependentTemplateSpecializationType* T) {
4084 return VisitNestedNameSpecifier(T->getQualifier());
4085}
4086
Douglas Gregord2fa7662010-12-20 02:24:11 +00004087bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4088 const PackExpansionType* T) {
4089 return Visit(T->getPattern());
4090}
4091
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004092bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4093 return false;
4094}
4095
4096bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4097 const ObjCInterfaceType *) {
4098 return false;
4099}
4100
4101bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4102 const ObjCObjectPointerType *) {
4103 return false;
4104}
4105
Eli Friedman0dfb8892011-10-06 23:00:33 +00004106bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4107 return Visit(T->getValueType());
4108}
4109
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004110bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4111 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004112 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004113 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004114 diag::warn_cxx98_compat_template_arg_local_type :
4115 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004116 << S.Context.getTypeDeclType(Tag) << SR;
4117 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004118 }
4119
John McCall5ea95772013-03-09 00:54:27 +00004120 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004121 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004122 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004123 diag::warn_cxx98_compat_template_arg_unnamed_type :
4124 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004125 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4126 return true;
4127 }
4128
4129 return false;
4130}
4131
4132bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4133 NestedNameSpecifier *NNS) {
4134 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4135 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004137 switch (NNS->getKind()) {
4138 case NestedNameSpecifier::Identifier:
4139 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004140 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004141 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004142 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004143 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004145 case NestedNameSpecifier::TypeSpec:
4146 case NestedNameSpecifier::TypeSpecWithTemplate:
4147 return Visit(QualType(NNS->getAsType(), 0));
4148 }
David Blaikie8a40f702012-01-17 06:56:22 +00004149 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004150}
4151
4152
Douglas Gregord32e0282009-02-09 23:23:08 +00004153/// \brief Check a template argument against its corresponding
4154/// template type parameter.
4155///
4156/// This routine implements the semantics of C++ [temp.arg.type]. It
4157/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004158bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004159 TypeSourceInfo *ArgInfo) {
4160 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004161 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004162 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004163
4164 if (Arg->isVariablyModifiedType()) {
4165 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004166 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004167 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004168 }
4169
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004170 // C++03 [temp.arg.type]p2:
4171 // A local type, a type with no linkage, an unnamed type or a type
4172 // compounded from any of these types shall not be used as a
4173 // template-argument for a template type-parameter.
4174 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004175 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004176 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004177 bool NeedsCheck;
4178 if (LangOpts.CPlusPlus11)
4179 NeedsCheck =
4180 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4181 SR.getBegin()) ||
4182 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4183 SR.getBegin());
4184 else
4185 NeedsCheck = Arg->hasUnnamedOrLocalType();
4186
4187 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004188 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4189 (void)Finder.Visit(Context.getCanonicalType(Arg));
4190 }
4191
Douglas Gregord32e0282009-02-09 23:23:08 +00004192 return false;
4193}
4194
Douglas Gregor20fdef32012-04-10 17:08:25 +00004195enum NullPointerValueKind {
4196 NPV_NotNullPointer,
4197 NPV_NullPointer,
4198 NPV_Error
4199};
4200
4201/// \brief Determine whether the given template argument is a null pointer
4202/// value of the appropriate type.
4203static NullPointerValueKind
4204isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4205 QualType ParamType, Expr *Arg) {
4206 if (Arg->isValueDependent() || Arg->isTypeDependent())
4207 return NPV_NotNullPointer;
4208
David Majnemer5c734ad2014-08-14 00:49:23 +00004209 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004210 return NPV_NotNullPointer;
4211
4212 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004213 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4214 if (ArgRV.isInvalid())
4215 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004216 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004217
Douglas Gregor20fdef32012-04-10 17:08:25 +00004218 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004219 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004220 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004221 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004222 EvalResult.HasSideEffects) {
4223 SourceLocation DiagLoc = Arg->getExprLoc();
4224
4225 // If our only note is the usual "invalid subexpression" note, just point
4226 // the caret at its location rather than producing an essentially
4227 // redundant note.
4228 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4229 diag::note_invalid_subexpr_in_const_expr) {
4230 DiagLoc = Notes[0].first;
4231 Notes.clear();
4232 }
4233
4234 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4235 << Arg->getType() << Arg->getSourceRange();
4236 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4237 S.Diag(Notes[I].first, Notes[I].second);
4238
4239 S.Diag(Param->getLocation(), diag::note_template_param_here);
4240 return NPV_Error;
4241 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004242
4243 // C++11 [temp.arg.nontype]p1:
4244 // - an address constant expression of type std::nullptr_t
4245 if (Arg->getType()->isNullPtrType())
4246 return NPV_NullPointer;
4247
4248 // - a constant expression that evaluates to a null pointer value (4.10); or
4249 // - a constant expression that evaluates to a null member pointer value
4250 // (4.11); or
4251 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4252 (EvalResult.Val.isMemberPointer() &&
4253 !EvalResult.Val.getMemberPointerDecl())) {
4254 // If our expression has an appropriate type, we've succeeded.
4255 bool ObjCLifetimeConversion;
4256 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4257 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4258 ObjCLifetimeConversion))
4259 return NPV_NullPointer;
4260
4261 // The types didn't match, but we know we got a null pointer; complain,
4262 // then recover as if the types were correct.
4263 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4264 << Arg->getType() << ParamType << Arg->getSourceRange();
4265 S.Diag(Param->getLocation(), diag::note_template_param_here);
4266 return NPV_NullPointer;
4267 }
4268
4269 // If we don't have a null pointer value, but we do have a NULL pointer
4270 // constant, suggest a cast to the appropriate type.
4271 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4272 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4273 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004274 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4275 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4276 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004277 S.Diag(Param->getLocation(), diag::note_template_param_here);
4278 return NPV_NullPointer;
4279 }
4280
4281 // FIXME: If we ever want to support general, address-constant expressions
4282 // as non-type template arguments, we should return the ExprResult here to
4283 // be interpreted by the caller.
4284 return NPV_NotNullPointer;
4285}
4286
David Majnemer61c39a12013-08-23 05:39:39 +00004287/// \brief Checks whether the given template argument is compatible with its
4288/// template parameter.
4289static bool CheckTemplateArgumentIsCompatibleWithParameter(
4290 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4291 Expr *Arg, QualType ArgType) {
4292 bool ObjCLifetimeConversion;
4293 if (ParamType->isPointerType() &&
4294 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4295 S.IsQualificationConversion(ArgType, ParamType, false,
4296 ObjCLifetimeConversion)) {
4297 // For pointer-to-object types, qualification conversions are
4298 // permitted.
4299 } else {
4300 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4301 if (!ParamRef->getPointeeType()->isFunctionType()) {
4302 // C++ [temp.arg.nontype]p5b3:
4303 // For a non-type template-parameter of type reference to
4304 // object, no conversions apply. The type referred to by the
4305 // reference may be more cv-qualified than the (otherwise
4306 // identical) type of the template- argument. The
4307 // template-parameter is bound directly to the
4308 // template-argument, which shall be an lvalue.
4309
4310 // FIXME: Other qualifiers?
4311 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4312 unsigned ArgQuals = ArgType.getCVRQualifiers();
4313
4314 if ((ParamQuals | ArgQuals) != ParamQuals) {
4315 S.Diag(Arg->getLocStart(),
4316 diag::err_template_arg_ref_bind_ignores_quals)
4317 << ParamType << Arg->getType() << Arg->getSourceRange();
4318 S.Diag(Param->getLocation(), diag::note_template_param_here);
4319 return true;
4320 }
4321 }
4322 }
4323
4324 // At this point, the template argument refers to an object or
4325 // function with external linkage. We now need to check whether the
4326 // argument and parameter types are compatible.
4327 if (!S.Context.hasSameUnqualifiedType(ArgType,
4328 ParamType.getNonReferenceType())) {
4329 // We can't perform this conversion or binding.
4330 if (ParamType->isReferenceType())
4331 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4332 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4333 else
4334 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4335 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4336 S.Diag(Param->getLocation(), diag::note_template_param_here);
4337 return true;
4338 }
4339 }
4340
4341 return false;
4342}
4343
Douglas Gregorccb07762009-02-11 19:52:55 +00004344/// \brief Checks whether the given template argument is the address
4345/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004347CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4348 NonTypeTemplateParmDecl *Param,
4349 QualType ParamType,
4350 Expr *ArgIn,
4351 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004352 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004353 Expr *Arg = ArgIn;
4354 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004355
Douglas Gregorb242683d2010-04-01 18:32:35 +00004356 bool AddressTaken = false;
4357 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004358 if (S.getLangOpts().MicrosoftExt) {
4359 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4360 // dereference and address-of operators.
4361 Arg = Arg->IgnoreParenCasts();
4362
4363 bool ExtWarnMSTemplateArg = false;
4364 UnaryOperatorKind FirstOpKind;
4365 SourceLocation FirstOpLoc;
4366 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4367 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4368 if (UnOpKind == UO_Deref)
4369 ExtWarnMSTemplateArg = true;
4370 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4371 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4372 if (!AddrOpLoc.isValid()) {
4373 FirstOpKind = UnOpKind;
4374 FirstOpLoc = UnOp->getOperatorLoc();
4375 }
4376 } else
4377 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004378 }
David Majnemer61c39a12013-08-23 05:39:39 +00004379 if (FirstOpLoc.isValid()) {
4380 if (ExtWarnMSTemplateArg)
4381 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4382 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004383
David Majnemer61c39a12013-08-23 05:39:39 +00004384 if (FirstOpKind == UO_AddrOf)
4385 AddressTaken = true;
4386 else if (Arg->getType()->isPointerType()) {
4387 // We cannot let pointers get dereferenced here, that is obviously not a
4388 // constant expression.
4389 assert(FirstOpKind == UO_Deref);
4390 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4391 << Arg->getSourceRange();
4392 }
4393 }
4394 } else {
4395 // See through any implicit casts we added to fix the type.
4396 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004397
David Majnemer61c39a12013-08-23 05:39:39 +00004398 // C++ [temp.arg.nontype]p1:
4399 //
4400 // A template-argument for a non-type, non-template
4401 // template-parameter shall be one of: [...]
4402 //
4403 // -- the address of an object or function with external
4404 // linkage, including function templates and function
4405 // template-ids but excluding non-static class members,
4406 // expressed as & id-expression where the & is optional if
4407 // the name refers to a function or array, or if the
4408 // corresponding template-parameter is a reference; or
4409
4410 // In C++98/03 mode, give an extension warning on any extra parentheses.
4411 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4412 bool ExtraParens = false;
4413 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4414 if (!Invalid && !ExtraParens) {
4415 S.Diag(Arg->getLocStart(),
4416 S.getLangOpts().CPlusPlus11
4417 ? diag::warn_cxx98_compat_template_arg_extra_parens
4418 : diag::ext_template_arg_extra_parens)
4419 << Arg->getSourceRange();
4420 ExtraParens = true;
4421 }
4422
4423 Arg = Parens->getSubExpr();
4424 }
4425
4426 while (SubstNonTypeTemplateParmExpr *subst =
4427 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4428 Arg = subst->getReplacement()->IgnoreImpCasts();
4429
4430 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4431 if (UnOp->getOpcode() == UO_AddrOf) {
4432 Arg = UnOp->getSubExpr();
4433 AddressTaken = true;
4434 AddrOpLoc = UnOp->getOperatorLoc();
4435 }
4436 }
4437
4438 while (SubstNonTypeTemplateParmExpr *subst =
4439 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4440 Arg = subst->getReplacement()->IgnoreImpCasts();
4441 }
John McCall7c454bb2011-07-15 05:09:51 +00004442
David Majnemer07910d62014-06-26 07:48:46 +00004443 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4444 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4445
4446 // If our parameter has pointer type, check for a null template value.
4447 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4448 NullPointerValueKind NPV;
4449 // dllimport'd entities aren't constant but are available inside of template
4450 // arguments.
4451 if (Entity && Entity->hasAttr<DLLImportAttr>())
4452 NPV = NPV_NotNullPointer;
4453 else
4454 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4455 switch (NPV) {
4456 case NPV_NullPointer:
4457 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004458 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4459 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004460 return false;
4461
4462 case NPV_Error:
4463 return true;
4464
4465 case NPV_NotNullPointer:
4466 break;
4467 }
4468 }
4469
Chandler Carruth724a8a12010-01-31 10:01:20 +00004470 // Stop checking the precise nature of the argument if it is value dependent,
4471 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004472 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004473 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004474 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004475 }
David Majnemer61c39a12013-08-23 05:39:39 +00004476
4477 if (isa<CXXUuidofExpr>(Arg)) {
4478 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4479 ArgIn, Arg, ArgType))
4480 return true;
4481
4482 Converted = TemplateArgument(ArgIn);
4483 return false;
4484 }
4485
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004486 if (!DRE) {
4487 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4488 << Arg->getSourceRange();
4489 S.Diag(Param->getLocation(), diag::note_template_param_here);
4490 return true;
4491 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004492
Douglas Gregorccb07762009-02-11 19:52:55 +00004493 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004494 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004495 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004496 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004497 S.Diag(Param->getLocation(), diag::note_template_param_here);
4498 return true;
4499 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004500
4501 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004503 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004504 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004505 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004506 S.Diag(Param->getLocation(), diag::note_template_param_here);
4507 return true;
4508 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004509 }
Mike Stump11289f42009-09-09 15:08:12 +00004510
Richard Smith9380e0e2012-04-04 21:11:30 +00004511 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4512 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004513
Richard Smith9380e0e2012-04-04 21:11:30 +00004514 // A non-type template argument must refer to an object or function.
4515 if (!Func && !Var) {
4516 // We found something, but we don't know specifically what it is.
4517 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4518 << Arg->getSourceRange();
4519 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4520 return true;
4521 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004522
Richard Smith9380e0e2012-04-04 21:11:30 +00004523 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004524 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004525 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004526 diag::warn_cxx98_compat_template_arg_object_internal :
4527 diag::ext_template_arg_object_internal)
4528 << !Func << Entity << Arg->getSourceRange();
4529 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4530 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004531 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004532 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4533 << !Func << Entity << Arg->getSourceRange();
4534 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4535 << !Func;
4536 return true;
4537 }
4538
4539 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004540 // If the template parameter has pointer type, the function decays.
4541 if (ParamType->isPointerType() && !AddressTaken)
4542 ArgType = S.Context.getPointerType(Func->getType());
4543 else if (AddressTaken && ParamType->isReferenceType()) {
4544 // If we originally had an address-of operator, but the
4545 // parameter has reference type, complain and (if things look
4546 // like they will work) drop the address-of operator.
4547 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4548 ParamType.getNonReferenceType())) {
4549 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4550 << ParamType;
4551 S.Diag(Param->getLocation(), diag::note_template_param_here);
4552 return true;
4553 }
4554
4555 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4556 << ParamType
4557 << FixItHint::CreateRemoval(AddrOpLoc);
4558 S.Diag(Param->getLocation(), diag::note_template_param_here);
4559
4560 ArgType = Func->getType();
4561 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004562 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004563 // A value of reference type is not an object.
4564 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004565 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004566 diag::err_template_arg_reference_var)
4567 << Var->getType() << Arg->getSourceRange();
4568 S.Diag(Param->getLocation(), diag::note_template_param_here);
4569 return true;
4570 }
4571
Richard Smith9380e0e2012-04-04 21:11:30 +00004572 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004573 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004574 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4575 << Arg->getSourceRange();
4576 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4577 return true;
4578 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004579
4580 // If the template parameter has pointer type, we must have taken
4581 // the address of this object.
4582 if (ParamType->isReferenceType()) {
4583 if (AddressTaken) {
4584 // If we originally had an address-of operator, but the
4585 // parameter has reference type, complain and (if things look
4586 // like they will work) drop the address-of operator.
4587 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4588 ParamType.getNonReferenceType())) {
4589 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4590 << ParamType;
4591 S.Diag(Param->getLocation(), diag::note_template_param_here);
4592 return true;
4593 }
4594
4595 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4596 << ParamType
4597 << FixItHint::CreateRemoval(AddrOpLoc);
4598 S.Diag(Param->getLocation(), diag::note_template_param_here);
4599
4600 ArgType = Var->getType();
4601 }
4602 } else if (!AddressTaken && ParamType->isPointerType()) {
4603 if (Var->getType()->isArrayType()) {
4604 // Array-to-pointer decay.
4605 ArgType = S.Context.getArrayDecayedType(Var->getType());
4606 } else {
4607 // If the template parameter has pointer type but the address of
4608 // this object was not taken, complain and (possibly) recover by
4609 // taking the address of the entity.
4610 ArgType = S.Context.getPointerType(Var->getType());
4611 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4612 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4613 << ParamType;
4614 S.Diag(Param->getLocation(), diag::note_template_param_here);
4615 return true;
4616 }
4617
4618 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4619 << ParamType
4620 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4621
4622 S.Diag(Param->getLocation(), diag::note_template_param_here);
4623 }
4624 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004625 }
Mike Stump11289f42009-09-09 15:08:12 +00004626
David Majnemer61c39a12013-08-23 05:39:39 +00004627 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4628 Arg, ArgType))
4629 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004630
4631 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004632 Converted =
4633 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004634 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004635 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004636}
4637
4638/// \brief Checks whether the given template argument is a pointer to
4639/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004640static bool CheckTemplateArgumentPointerToMember(Sema &S,
4641 NonTypeTemplateParmDecl *Param,
4642 QualType ParamType,
4643 Expr *&ResultArg,
4644 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004645 bool Invalid = false;
4646
Douglas Gregor20fdef32012-04-10 17:08:25 +00004647 // Check for a null pointer value.
4648 Expr *Arg = ResultArg;
4649 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4650 case NPV_Error:
4651 return true;
4652 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004653 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004654 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4655 /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004656 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4657 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004658 return false;
4659 case NPV_NotNullPointer:
4660 break;
4661 }
4662
4663 bool ObjCLifetimeConversion;
4664 if (S.IsQualificationConversion(Arg->getType(),
4665 ParamType.getNonReferenceType(),
4666 false, ObjCLifetimeConversion)) {
4667 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004668 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004669 ResultArg = Arg;
4670 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4671 ParamType.getNonReferenceType())) {
4672 // We can't perform this conversion.
4673 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4674 << Arg->getType() << ParamType << Arg->getSourceRange();
4675 S.Diag(Param->getLocation(), diag::note_template_param_here);
4676 return true;
4677 }
4678
Douglas Gregorccb07762009-02-11 19:52:55 +00004679 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004680 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004681 Arg = Cast->getSubExpr();
4682
4683 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004684 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004685 // A template-argument for a non-type, non-template
4686 // template-parameter shall be one of: [...]
4687 //
4688 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004689 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004690
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004691 // In C++98/03 mode, give an extension warning on any extra parentheses.
4692 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4693 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004694 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004695 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004696 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004697 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004698 diag::warn_cxx98_compat_template_arg_extra_parens :
4699 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004700 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004701 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004702 }
4703
4704 Arg = Parens->getSubExpr();
4705 }
4706
John McCall7c454bb2011-07-15 05:09:51 +00004707 while (SubstNonTypeTemplateParmExpr *subst =
4708 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4709 Arg = subst->getReplacement()->IgnoreImpCasts();
4710
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004711 // A pointer-to-member constant written &Class::member.
4712 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004713 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004714 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4715 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004716 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004718 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004719 // A constant of pointer-to-member type.
4720 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4721 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4722 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004723 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004724 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004725 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004726 } else {
4727 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004728 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004729 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004730 return Invalid;
4731 }
4732 }
4733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734
Craig Topperc3ec1492014-05-26 06:22:03 +00004735 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
Douglas Gregorccb07762009-02-11 19:52:55 +00004738 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004739 return S.Diag(Arg->getLocStart(),
4740 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004741 << Arg->getSourceRange();
4742
David Majnemer3ac84e62013-10-22 21:56:38 +00004743 if (isa<FieldDecl>(DRE->getDecl()) ||
4744 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4745 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004746 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004747 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004748 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4749 "Only non-static member pointers can make it here");
4750
4751 // Okay: this is the address of a non-static member, and therefore
4752 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004753 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004754 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004755 } else {
4756 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004757 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004758 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004759 return Invalid;
4760 }
4761
4762 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004763 S.Diag(Arg->getLocStart(),
4764 diag::err_template_arg_not_pointer_to_member_form)
4765 << Arg->getSourceRange();
4766 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004767 return true;
4768}
4769
Douglas Gregord32e0282009-02-09 23:23:08 +00004770/// \brief Check a template argument against its corresponding
4771/// non-type template parameter.
4772///
Douglas Gregor463421d2009-03-03 04:44:36 +00004773/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004774/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004775/// returns the converted template argument. \p ParamType is the
4776/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004777ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004778 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004779 TemplateArgument &Converted,
4780 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004781 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004782
Douglas Gregor86560402009-02-10 23:36:10 +00004783 // If either the parameter has a dependent type or the argument is
4784 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004785 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004786 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004787 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004788 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004789 }
Douglas Gregor86560402009-02-10 23:36:10 +00004790
Richard Smithd663fdd2014-12-17 20:42:37 +00004791 // We should have already dropped all cv-qualifiers by now.
4792 assert(!ParamType.hasQualifiers() &&
4793 "non-type template parameter type cannot be qualified");
4794
4795 if (CTAK == CTAK_Deduced &&
4796 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4797 // C++ [temp.deduct.type]p17:
4798 // If, in the declaration of a function template with a non-type
4799 // template-parameter, the non-type template-parameter is used
4800 // in an expression in the function parameter-list and, if the
4801 // corresponding template-argument is deduced, the
4802 // template-argument type shall match the type of the
4803 // template-parameter exactly, except that a template-argument
4804 // deduced from an array bound may be of any integral type.
4805 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4806 << Arg->getType().getUnqualifiedType()
4807 << ParamType.getUnqualifiedType();
4808 Diag(Param->getLocation(), diag::note_template_param_here);
4809 return ExprError();
4810 }
4811
Richard Smith410cc892014-11-26 03:26:53 +00004812 if (getLangOpts().CPlusPlus1z) {
4813 // FIXME: We can do some limited checking for a value-dependent but not
4814 // type-dependent argument.
4815 if (Arg->isValueDependent()) {
4816 Converted = TemplateArgument(Arg);
4817 return Arg;
4818 }
4819
4820 // C++1z [temp.arg.nontype]p1:
4821 // A template-argument for a non-type template parameter shall be
4822 // a converted constant expression of the type of the template-parameter.
4823 APValue Value;
4824 ExprResult ArgResult = CheckConvertedConstantExpression(
4825 Arg, ParamType, Value, CCEK_TemplateArg);
4826 if (ArgResult.isInvalid())
4827 return ExprError();
4828
Richard Smithd663fdd2014-12-17 20:42:37 +00004829 QualType CanonParamType = Context.getCanonicalType(ParamType);
4830
Richard Smith410cc892014-11-26 03:26:53 +00004831 // Convert the APValue to a TemplateArgument.
4832 switch (Value.getKind()) {
4833 case APValue::Uninitialized:
4834 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004835 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004836 break;
4837 case APValue::Int:
4838 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004839 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004840 break;
4841 case APValue::MemberPointer: {
4842 assert(ParamType->isMemberPointerType());
4843
4844 // FIXME: We need TemplateArgument representation and mangling for these.
4845 if (!Value.getMemberPointerPath().empty()) {
4846 Diag(Arg->getLocStart(),
4847 diag::err_template_arg_member_ptr_base_derived_not_supported)
4848 << Value.getMemberPointerDecl() << ParamType
4849 << Arg->getSourceRange();
4850 return ExprError();
4851 }
4852
4853 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004854 Converted = VD ? TemplateArgument(VD, CanonParamType)
4855 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004856 break;
4857 }
4858 case APValue::LValue: {
4859 // For a non-type template-parameter of pointer or reference type,
4860 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004861 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4862 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004863 // -- a temporary object
4864 // -- a string literal
4865 // -- the result of a typeid expression, or
4866 // -- a predefind __func__ variable
4867 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4868 if (isa<CXXUuidofExpr>(E)) {
4869 Converted = TemplateArgument(const_cast<Expr*>(E));
4870 break;
4871 }
4872 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4873 << Arg->getSourceRange();
4874 return ExprError();
4875 }
4876 auto *VD = const_cast<ValueDecl *>(
4877 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4878 // -- a subobject
4879 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4880 VD && VD->getType()->isArrayType() &&
4881 Value.getLValuePath()[0].ArrayIndex == 0 &&
4882 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4883 // Per defect report (no number yet):
4884 // ... other than a pointer to the first element of a complete array
4885 // object.
4886 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4887 Value.isLValueOnePastTheEnd()) {
4888 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4889 << Value.getAsString(Context, ParamType);
4890 return ExprError();
4891 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004892 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004893 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004894 assert((!VD || !ParamType->isNullPtrType()) &&
4895 "non-null value of type nullptr_t?");
4896 Converted = VD ? TemplateArgument(VD, CanonParamType)
4897 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004898 break;
4899 }
4900 case APValue::AddrLabelDiff:
4901 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4902 case APValue::Float:
4903 case APValue::ComplexInt:
4904 case APValue::ComplexFloat:
4905 case APValue::Vector:
4906 case APValue::Array:
4907 case APValue::Struct:
4908 case APValue::Union:
4909 llvm_unreachable("invalid kind for template argument");
4910 }
4911
4912 return ArgResult.get();
4913 }
4914
Douglas Gregor86560402009-02-10 23:36:10 +00004915 // C++ [temp.arg.nontype]p5:
4916 // The following conversions are performed on each expression used
4917 // as a non-type template-argument. If a non-type
4918 // template-argument cannot be converted to the type of the
4919 // corresponding template-parameter then the program is
4920 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00004921 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004922 // C++11:
4923 // -- for a non-type template-parameter of integral or
4924 // enumeration type, conversions permitted in a converted
4925 // constant expression are applied.
4926 //
4927 // C++98:
4928 // -- for a non-type template-parameter of integral or
4929 // enumeration type, integral promotions (4.5) and integral
4930 // conversions (4.7) are applied.
4931
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004932 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004933 // We can't check arbitrary value-dependent arguments.
4934 // FIXME: If there's no viable conversion to the template parameter type,
4935 // we should be able to diagnose that prior to instantiation.
4936 if (Arg->isValueDependent()) {
4937 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004938 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00004939 }
4940
4941 // C++ [temp.arg.nontype]p1:
4942 // A template-argument for a non-type, non-template template-parameter
4943 // shall be one of:
4944 //
4945 // -- for a non-type template-parameter of integral or enumeration
4946 // type, a converted constant expression of the type of the
4947 // template-parameter; or
4948 llvm::APSInt Value;
4949 ExprResult ArgResult =
4950 CheckConvertedConstantExpression(Arg, ParamType, Value,
4951 CCEK_TemplateArg);
4952 if (ArgResult.isInvalid())
4953 return ExprError();
4954
4955 // Widen the argument value to sizeof(parameter type). This is almost
4956 // always a no-op, except when the parameter type is bool. In
4957 // that case, this may extend the argument from 1 bit to 8 bits.
4958 QualType IntegerType = ParamType;
4959 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4960 IntegerType = Enum->getDecl()->getIntegerType();
4961 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4962
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004963 Converted = TemplateArgument(Context, Value,
4964 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00004965 return ArgResult;
4966 }
4967
Richard Smith08b12f12011-10-27 22:11:44 +00004968 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4969 if (ArgResult.isInvalid())
4970 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004971 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00004972
4973 QualType ArgType = Arg->getType();
4974
Douglas Gregor86560402009-02-10 23:36:10 +00004975 // C++ [temp.arg.nontype]p1:
4976 // A template-argument for a non-type, non-template
4977 // template-parameter shall be one of:
4978 //
4979 // -- an integral constant-expression of integral or enumeration
4980 // type; or
4981 // -- the name of a non-type template-parameter; or
4982 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004983 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00004984 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004985 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004986 diag::err_template_arg_not_integral_or_enumeral)
4987 << ArgType << Arg->getSourceRange();
4988 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004989 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00004990 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00004991 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4992 QualType T;
4993
4994 public:
4995 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00004996
4997 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4998 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00004999 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5000 }
5001 } Diagnoser(ArgType);
5002
5003 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005004 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005005 if (!Arg)
5006 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005007 }
5008
Richard Smithd663fdd2014-12-17 20:42:37 +00005009 // From here on out, all we care about is the unqualified form
5010 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005011 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005012
5013 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005014 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005015 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005016 } else if (ParamType->isBooleanType()) {
5017 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005018 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005019 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5020 !ParamType->isEnumeralType()) {
5021 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005022 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005023 } else {
5024 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005025 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005026 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005027 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005028 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005029 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005030 }
5031
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005032 // Add the value of this argument to the list of converted
5033 // arguments. We use the bitwidth and signedness of the template
5034 // parameter.
5035 if (Arg->isValueDependent()) {
5036 // The argument is value-dependent. Create a new
5037 // TemplateArgument with the converted expression.
5038 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005039 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005040 }
5041
Douglas Gregor52aba872009-03-14 00:20:21 +00005042 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005043 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005044 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005045
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005046 if (ParamType->isBooleanType()) {
5047 // Value must be zero or one.
5048 Value = Value != 0;
5049 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5050 if (Value.getBitWidth() != AllowedBits)
5051 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005052 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005053 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005054 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005055
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005057 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005058 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005059 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005060 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005061 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005062
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005063 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005064 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005065 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005066 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005067 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5068 << Arg->getSourceRange();
5069 Diag(Param->getLocation(), diag::note_template_param_here);
5070 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005071
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005072 // Complain if we overflowed the template parameter's type.
5073 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005074 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005075 RequiredBits = OldValue.getActiveBits();
5076 else if (OldValue.isUnsigned())
5077 RequiredBits = OldValue.getActiveBits() + 1;
5078 else
5079 RequiredBits = OldValue.getMinSignedBits();
5080 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005081 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005082 diag::warn_template_arg_too_large)
5083 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5084 << Arg->getSourceRange();
5085 Diag(Param->getLocation(), diag::note_template_param_here);
5086 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005087 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005088
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005089 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005090 ParamType->isEnumeralType()
5091 ? Context.getCanonicalType(ParamType)
5092 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005093 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005094 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005095
Richard Smith08b12f12011-10-27 22:11:44 +00005096 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005097 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5098
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005099 // Handle pointer-to-function, reference-to-function, and
5100 // pointer-to-member-function all in (roughly) the same way.
5101 if (// -- For a non-type template-parameter of type pointer to
5102 // function, only the function-to-pointer conversion (4.3) is
5103 // applied. If the template-argument represents a set of
5104 // overloaded functions (or a pointer to such), the matching
5105 // function is selected from the set (13.4).
5106 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005107 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005108 // -- For a non-type template-parameter of type reference to
5109 // function, no conversions apply. If the template-argument
5110 // represents a set of overloaded functions, the matching
5111 // function is selected from the set (13.4).
5112 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005113 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005114 // -- For a non-type template-parameter of type pointer to
5115 // member function, no conversions apply. If the
5116 // template-argument represents a set of overloaded member
5117 // functions, the matching member function is selected from
5118 // the set (13.4).
5119 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005120 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005121 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005122
Douglas Gregor064fdb22010-04-14 23:11:21 +00005123 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005124 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005125 true,
5126 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005127 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005128 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005129
5130 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5131 ArgType = Arg->getType();
5132 } else
John Wiegley01296292011-04-08 18:41:53 +00005133 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005135
John Wiegley01296292011-04-08 18:41:53 +00005136 if (!ParamType->isMemberPointerType()) {
5137 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5138 ParamType,
5139 Arg, Converted))
5140 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005141 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005142 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005143
Douglas Gregor20fdef32012-04-10 17:08:25 +00005144 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5145 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005146 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005147 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005148 }
5149
Chris Lattner696197c2009-02-20 21:37:53 +00005150 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005151 // -- for a non-type template-parameter of type pointer to
5152 // object, qualification conversions (4.4) and the
5153 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005154 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005155 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005156 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005157
John Wiegley01296292011-04-08 18:41:53 +00005158 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5159 ParamType,
5160 Arg, Converted))
5161 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005162 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005163 }
Mike Stump11289f42009-09-09 15:08:12 +00005164
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005165 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005166 // -- For a non-type template-parameter of type reference to
5167 // object, no conversions apply. The type referred to by the
5168 // reference may be more cv-qualified than the (otherwise
5169 // identical) type of the template-argument. The
5170 // template-parameter is bound directly to the
5171 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005172 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005173 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005174
Douglas Gregor064fdb22010-04-14 23:11:21 +00005175 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005176 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5177 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005178 true,
5179 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005180 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005181 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005182
5183 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5184 ArgType = Arg->getType();
5185 } else
John Wiegley01296292011-04-08 18:41:53 +00005186 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005188
John Wiegley01296292011-04-08 18:41:53 +00005189 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5190 ParamType,
5191 Arg, Converted))
5192 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005193 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005194 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005195
Douglas Gregor20fdef32012-04-10 17:08:25 +00005196 // Deal with parameters of type std::nullptr_t.
5197 if (ParamType->isNullPtrType()) {
5198 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5199 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005200 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005201 }
5202
5203 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5204 case NPV_NotNullPointer:
5205 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5206 << Arg->getType() << ParamType;
5207 Diag(Param->getLocation(), diag::note_template_param_here);
5208 return ExprError();
5209
5210 case NPV_Error:
5211 return ExprError();
5212
5213 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005214 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005215 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5216 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005217 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005218 }
5219 }
5220
Douglas Gregor0e558532009-02-11 16:16:59 +00005221 // -- For a non-type template-parameter of type pointer to data
5222 // member, qualification conversions (4.4) are applied.
5223 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5224
Douglas Gregor20fdef32012-04-10 17:08:25 +00005225 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5226 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005227 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005228 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005229}
5230
5231/// \brief Check a template argument against its corresponding
5232/// template template parameter.
5233///
5234/// This routine implements the semantics of C++ [temp.arg.template].
5235/// It returns true if an error occurred, and false otherwise.
5236bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005237 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005238 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005239 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005240 TemplateDecl *Template = Name.getAsTemplateDecl();
5241 if (!Template) {
5242 // Any dependent template name is fine.
5243 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5244 return false;
5245 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005246
Richard Smith3f1b5d02011-05-05 21:57:07 +00005247 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005248 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005249 // the name of a class template or an alias template, expressed as an
5250 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005251 // primary class templates are considered when matching the
5252 // template template argument with the corresponding parameter;
5253 // partial specializations are not considered even if their
5254 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005255 //
5256 // Note that we also allow template template parameters here, which
5257 // will happen when we are dealing with, e.g., class template
5258 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005259 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005260 !isa<TemplateTemplateParmDecl>(Template) &&
5261 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005262 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005263 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005264 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005265 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005266 << Template;
5267 }
5268
Richard Smith1fde8ec2012-09-07 02:06:42 +00005269 TemplateParameterList *Params = Param->getTemplateParameters();
5270 if (Param->isExpandedParameterPack())
5271 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5272
Douglas Gregor85e0f662009-02-10 00:24:35 +00005273 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005274 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005275 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005276 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005277 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005278}
5279
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005280/// \brief Given a non-type template argument that refers to a
5281/// declaration and the type of its corresponding non-type template
5282/// parameter, produce an expression that properly refers to that
5283/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005284ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005285Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5286 QualType ParamType,
5287 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005288 // C++ [temp.param]p8:
5289 //
5290 // A non-type template-parameter of type "array of T" or
5291 // "function returning T" is adjusted to be of type "pointer to
5292 // T" or "pointer to function returning T", respectively.
5293 if (ParamType->isArrayType())
5294 ParamType = Context.getArrayDecayedType(ParamType);
5295 else if (ParamType->isFunctionType())
5296 ParamType = Context.getPointerType(ParamType);
5297
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005298 // For a NULL non-type template argument, return nullptr casted to the
5299 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005300 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005301 return ImpCastExprToType(
5302 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5303 ParamType,
5304 ParamType->getAs<MemberPointerType>()
5305 ? CK_NullToMemberPointer
5306 : CK_NullToPointer);
5307 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005308 assert(Arg.getKind() == TemplateArgument::Declaration &&
5309 "Only declaration template arguments permitted here");
5310
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005311 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5312
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005313 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005314 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5315 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005316 // If the value is a class member, we might have a pointer-to-member.
5317 // Determine whether the non-type template template parameter is of
5318 // pointer-to-member type. If so, we need to build an appropriate
5319 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5320 // would refer to the member itself.
5321 if (ParamType->isMemberPointerType()) {
5322 QualType ClassType
5323 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5324 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005325 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005326 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005327 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005328 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005329
5330 // The actual value-ness of this is unimportant, but for
5331 // internal consistency's sake, references to instance methods
5332 // are r-values.
5333 ExprValueKind VK = VK_LValue;
5334 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5335 VK = VK_RValue;
5336
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005337 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005338 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005339 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005340 Loc,
5341 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005342 if (RefExpr.isInvalid())
5343 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344
John McCalle3027922010-08-25 11:45:40 +00005345 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005347 // We might need to perform a trailing qualification conversion, since
5348 // the element type on the parameter could be more qualified than the
5349 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005350 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005351 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005352 ParamType.getUnqualifiedType(), false,
5353 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005354 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005355
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005356 assert(!RefExpr.isInvalid() &&
5357 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005358 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005359 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005360 }
5361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005362
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005363 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005364
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005365 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005366 // When the non-type template parameter is a pointer, take the
5367 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005368 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005369 if (RefExpr.isInvalid())
5370 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005371
5372 if (T->isFunctionType() || T->isArrayType()) {
5373 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005374 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005375 if (RefExpr.isInvalid())
5376 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005377
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005378 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380
Douglas Gregorb242683d2010-04-01 18:32:35 +00005381 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005382 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005383 }
5384
John McCall7decc9e2010-11-18 06:31:45 +00005385 ExprValueKind VK = VK_RValue;
5386
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005387 // If the non-type template parameter has reference type, qualify the
5388 // resulting declaration reference with the extra qualifiers on the
5389 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005390 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5391 VK = VK_LValue;
5392 T = Context.getQualifiedType(T,
5393 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005394 } else if (isa<FunctionDecl>(VD)) {
5395 // References to functions are always lvalues.
5396 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
John McCall7decc9e2010-11-18 06:31:45 +00005399 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005400}
5401
5402/// \brief Construct a new expression that refers to the given
5403/// integral template argument with the given source-location
5404/// information.
5405///
5406/// This routine takes care of the mapping from an integral template
5407/// argument (which may have any integral type) to the appropriate
5408/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005409ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005410Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5411 SourceLocation Loc) {
5412 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005413 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005414 QualType OrigT = Arg.getIntegralType();
5415
5416 // If this is an enum type that we're instantiating, we need to use an integer
5417 // type the same size as the enumerator. We don't want to build an
5418 // IntegerLiteral with enum type. The integer type of an enum type can be of
5419 // any integral type with C++11 enum classes, make sure we create the right
5420 // type of literal for it.
5421 QualType T = OrigT;
5422 if (const EnumType *ET = OrigT->getAs<EnumType>())
5423 T = ET->getDecl()->getIntegerType();
5424
5425 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005426 if (T->isAnyCharacterType()) {
5427 CharacterLiteral::CharacterKind Kind;
5428 if (T->isWideCharType())
5429 Kind = CharacterLiteral::Wide;
5430 else if (T->isChar16Type())
5431 Kind = CharacterLiteral::UTF16;
5432 else if (T->isChar32Type())
5433 Kind = CharacterLiteral::UTF32;
5434 else
5435 Kind = CharacterLiteral::Ascii;
5436
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005437 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5438 Kind, T, Loc);
5439 } else if (T->isBooleanType()) {
5440 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5441 T, Loc);
5442 } else if (T->isNullPtrType()) {
5443 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5444 } else {
5445 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005446 }
5447
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005448 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005449 // FIXME: This is a hack. We need a better way to handle substituted
5450 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005451 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5452 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005453 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005454 Loc, Loc);
5455 }
5456
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005457 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005458}
5459
Douglas Gregor641040a2011-01-12 23:45:44 +00005460/// \brief Match two template parameters within template parameter lists.
5461static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5462 bool Complain,
5463 Sema::TemplateParameterListEqualKind Kind,
5464 SourceLocation TemplateArgLoc) {
5465 // Check the actual kind (type, non-type, template).
5466 if (Old->getKind() != New->getKind()) {
5467 if (Complain) {
5468 unsigned NextDiag = diag::err_template_param_different_kind;
5469 if (TemplateArgLoc.isValid()) {
5470 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5471 NextDiag = diag::note_template_param_different_kind;
5472 }
5473 S.Diag(New->getLocation(), NextDiag)
5474 << (Kind != Sema::TPL_TemplateMatch);
5475 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5476 << (Kind != Sema::TPL_TemplateMatch);
5477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478
Douglas Gregor641040a2011-01-12 23:45:44 +00005479 return false;
5480 }
5481
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005482 // Check that both are parameter packs are neither are parameter packs.
5483 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005484 // template template parameter, the template template parameter can have
5485 // a parameter pack where the template template argument does not.
5486 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5487 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5488 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005489 if (Complain) {
5490 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5491 if (TemplateArgLoc.isValid()) {
5492 S.Diag(TemplateArgLoc,
5493 diag::err_template_arg_template_params_mismatch);
5494 NextDiag = diag::note_template_parameter_pack_non_pack;
5495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005496
Douglas Gregor641040a2011-01-12 23:45:44 +00005497 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5498 : isa<NonTypeTemplateParmDecl>(New)? 1
5499 : 2;
5500 S.Diag(New->getLocation(), NextDiag)
5501 << ParamKind << New->isParameterPack();
5502 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5503 << ParamKind << Old->isParameterPack();
5504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Douglas Gregor641040a2011-01-12 23:45:44 +00005506 return false;
5507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508
Douglas Gregor641040a2011-01-12 23:45:44 +00005509 // For non-type template parameters, check the type of the parameter.
5510 if (NonTypeTemplateParmDecl *OldNTTP
5511 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5512 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513
Douglas Gregor641040a2011-01-12 23:45:44 +00005514 // If we are matching a template template argument to a template
5515 // template parameter and one of the non-type template parameter types
5516 // is dependent, then we must wait until template instantiation time
5517 // to actually compare the arguments.
5518 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5519 (OldNTTP->getType()->isDependentType() ||
5520 NewNTTP->getType()->isDependentType()))
5521 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522
Douglas Gregor641040a2011-01-12 23:45:44 +00005523 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5524 if (Complain) {
5525 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5526 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005527 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005528 diag::err_template_arg_template_params_mismatch);
5529 NextDiag = diag::note_template_nontype_parm_different_type;
5530 }
5531 S.Diag(NewNTTP->getLocation(), NextDiag)
5532 << NewNTTP->getType()
5533 << (Kind != Sema::TPL_TemplateMatch);
5534 S.Diag(OldNTTP->getLocation(),
5535 diag::note_template_nontype_parm_prev_declaration)
5536 << OldNTTP->getType();
5537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005538
Douglas Gregor641040a2011-01-12 23:45:44 +00005539 return false;
5540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005541
Douglas Gregor641040a2011-01-12 23:45:44 +00005542 return true;
5543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Douglas Gregor641040a2011-01-12 23:45:44 +00005545 // For template template parameters, check the template parameter types.
5546 // The template parameter lists of template template
5547 // parameters must agree.
5548 if (TemplateTemplateParmDecl *OldTTP
5549 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005550 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005551 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5552 OldTTP->getTemplateParameters(),
5553 Complain,
5554 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005556 : Kind),
5557 TemplateArgLoc);
5558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005559
Douglas Gregor641040a2011-01-12 23:45:44 +00005560 return true;
5561}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005562
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005563/// \brief Diagnose a known arity mismatch when comparing template argument
5564/// lists.
5565static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005567 TemplateParameterList *New,
5568 TemplateParameterList *Old,
5569 Sema::TemplateParameterListEqualKind Kind,
5570 SourceLocation TemplateArgLoc) {
5571 unsigned NextDiag = diag::err_template_param_list_different_arity;
5572 if (TemplateArgLoc.isValid()) {
5573 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5574 NextDiag = diag::note_template_param_list_different_arity;
5575 }
5576 S.Diag(New->getTemplateLoc(), NextDiag)
5577 << (New->size() > Old->size())
5578 << (Kind != Sema::TPL_TemplateMatch)
5579 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5580 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5581 << (Kind != Sema::TPL_TemplateMatch)
5582 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5583}
5584
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005585/// \brief Determine whether the given template parameter lists are
5586/// equivalent.
5587///
Mike Stump11289f42009-09-09 15:08:12 +00005588/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005589/// source code as part of a new template declaration.
5590///
5591/// \param Old The old template parameter list, typically found via
5592/// name lookup of the template declared with this template parameter
5593/// list.
5594///
5595/// \param Complain If true, this routine will produce a diagnostic if
5596/// the template parameter lists are not equivalent.
5597///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005598/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005599///
5600/// \param TemplateArgLoc If this source location is valid, then we
5601/// are actually checking the template parameter list of a template
5602/// argument (New) against the template parameter list of its
5603/// corresponding template template parameter (Old). We produce
5604/// slightly different diagnostics in this scenario.
5605///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005606/// \returns True if the template parameter lists are equal, false
5607/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005608bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005609Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5610 TemplateParameterList *Old,
5611 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005612 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005613 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005614 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5615 if (Complain)
5616 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5617 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005618
5619 return false;
5620 }
5621
Douglas Gregor641040a2011-01-12 23:45:44 +00005622 // C++0x [temp.arg.template]p3:
5623 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005624 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005625 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005626 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005627 // template-parameter-list of P. [...]
5628 TemplateParameterList::iterator NewParm = New->begin();
5629 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005630 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005631 OldParmEnd = Old->end();
5632 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005633 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5634 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005635 if (NewParm == NewParmEnd) {
5636 if (Complain)
5637 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5638 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005640 return false;
5641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005642
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005643 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5644 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005645 return false;
5646
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005647 ++NewParm;
5648 continue;
5649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005650
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005651 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005652 // [...] When P's template- parameter-list contains a template parameter
5653 // pack (14.5.3), the template parameter pack will match zero or more
5654 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005655 // template-parameter-list of A with the same type and form as the
5656 // template parameter pack in P (ignoring whether those template
5657 // parameters are template parameter packs).
5658 for (; NewParm != NewParmEnd; ++NewParm) {
5659 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5660 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005662 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005665 // Make sure we exhausted all of the arguments.
5666 if (NewParm != NewParmEnd) {
5667 if (Complain)
5668 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5669 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005671 return false;
5672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005674 return true;
5675}
5676
5677/// \brief Check whether a template can be declared within this scope.
5678///
5679/// If the template declaration is valid in this scope, returns
5680/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005681bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005682Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005683 if (!S)
5684 return false;
5685
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005686 // Find the nearest enclosing declaration scope.
5687 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5688 (S->getFlags() & Scope::TemplateParamScope) != 0)
5689 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005690
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005691 // C++ [temp]p4:
5692 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005693 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005694 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005695 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005696 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005697
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005698 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005699 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005700
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005701 // C++ [temp]p2:
5702 // A template-declaration can appear only as a namespace scope or
5703 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005704 if (Ctx) {
5705 if (Ctx->isFileContext())
5706 return false;
5707 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5708 // C++ [temp.mem]p2:
5709 // A local class shall not have member templates.
5710 if (RD->isLocalClass())
5711 return Diag(TemplateParams->getTemplateLoc(),
5712 diag::err_template_inside_local_class)
5713 << TemplateParams->getSourceRange();
5714 else
5715 return false;
5716 }
5717 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005718
Mike Stump11289f42009-09-09 15:08:12 +00005719 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005720 diag::err_template_outside_namespace_or_class_scope)
5721 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005722}
Douglas Gregor67a65642009-02-17 23:15:12 +00005723
Douglas Gregor54888652009-10-07 00:13:32 +00005724/// \brief Determine what kind of template specialization the given declaration
5725/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005726static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005727 if (!D)
5728 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005729
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005730 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5731 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005732 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5733 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005734 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5735 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Douglas Gregor54888652009-10-07 00:13:32 +00005737 return TSK_Undeclared;
5738}
5739
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005741/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005742///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005743/// This routine determines whether a template specialization can be declared
5744/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005745///
5746/// \param S the semantic analysis object for which this check is being
5747/// performed.
5748///
5749/// \param Specialized the entity being specialized or instantiated, which
5750/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005752/// member class).
5753///
5754/// \param PrevDecl the previous declaration of this entity, if any.
5755///
5756/// \param Loc the location of the explicit specialization or instantiation of
5757/// this entity.
5758///
5759/// \param IsPartialSpecialization whether this is a partial specialization of
5760/// a class template.
5761///
Douglas Gregor54888652009-10-07 00:13:32 +00005762/// \returns true if there was an error that we cannot recover from, false
5763/// otherwise.
5764static bool CheckTemplateSpecializationScope(Sema &S,
5765 NamedDecl *Specialized,
5766 NamedDecl *PrevDecl,
5767 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005768 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005769 // Keep these "kind" numbers in sync with the %select statements in the
5770 // various diagnostics emitted by this routine.
5771 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005772 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005773 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005774 else if (isa<VarTemplateDecl>(Specialized))
5775 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005776 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005777 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005778 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005779 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005780 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005781 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005782 else if (isa<RecordDecl>(Specialized))
5783 EntityKind = 7;
5784 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5785 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005786 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005787 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005788 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005789 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005790 return true;
5791 }
5792
Douglas Gregorf47b9112009-02-25 22:02:03 +00005793 // C++ [temp.expl.spec]p2:
5794 // An explicit specialization shall be declared in the namespace
5795 // of which the template is a member, or, for member templates, in
5796 // the namespace of which the enclosing class or enclosing class
5797 // template is a member. An explicit specialization of a member
5798 // function, member class or static data member of a class
5799 // template shall be declared in the namespace of which the class
5800 // template is a member. Such a declaration may also be a
5801 // definition. If the declaration is not a definition, the
5802 // specialization may be defined later in the name- space in which
5803 // the explicit specialization was declared, or in a namespace
5804 // that encloses the one in which the explicit specialization was
5805 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005806 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005807 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005808 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005809 return true;
5810 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005811
Douglas Gregor40fb7442009-10-07 17:30:37 +00005812 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005813 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005814 // Do not warn for class scope explicit specialization during
5815 // instantiation, warning was already emitted during pattern
5816 // semantic analysis.
5817 if (!S.ActiveTemplateInstantiations.size())
5818 S.Diag(Loc, diag::ext_function_specialization_in_class)
5819 << Specialized;
5820 } else {
5821 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5822 << Specialized;
5823 return true;
5824 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005826
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005827 if (S.CurContext->isRecord() &&
5828 !S.CurContext->Equals(Specialized->getDeclContext())) {
5829 // Make sure that we're specializing in the right record context.
5830 // Otherwise, things can go horribly wrong.
5831 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5832 << Specialized;
5833 return true;
5834 }
5835
Douglas Gregore4b05162009-10-07 17:21:34 +00005836 // C++ [temp.class.spec]p6:
5837 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005838 // in any namespace scope in which its definition may be defined (14.5.1
5839 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005840 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005841 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005842 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005843
5844 // Make sure that this redeclaration (or definition) occurs in an enclosing
5845 // namespace.
5846 // Note that HandleDeclarator() performs this check for explicit
5847 // specializations of function templates, static data members, and member
5848 // functions, so we skip the check here for those kinds of entities.
5849 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5850 // Should we refactor that check, so that it occurs later?
5851 if (!DC->Encloses(SpecializedContext) &&
5852 !(isa<FunctionTemplateDecl>(Specialized) ||
5853 isa<FunctionDecl>(Specialized) ||
5854 isa<VarTemplateDecl>(Specialized) ||
5855 isa<VarDecl>(Specialized))) {
5856 if (isa<TranslationUnitDecl>(SpecializedContext))
5857 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5858 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005859 else if (isa<NamespaceDecl>(SpecializedContext)) {
5860 int Diag = diag::err_template_spec_redecl_out_of_scope;
5861 if (S.getLangOpts().MicrosoftExt)
5862 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5863 S.Diag(Loc, Diag) << EntityKind << Specialized
5864 << cast<NamedDecl>(SpecializedContext);
5865 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005866 llvm_unreachable("unexpected namespace context for specialization");
5867
5868 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5869 } else if ((!PrevDecl ||
5870 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5871 getTemplateSpecializationKind(PrevDecl) ==
5872 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005873 // C++ [temp.exp.spec]p2:
5874 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005875 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005876 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005877 // An explicit specialization of a member function, member class or
5878 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005879 // namespace of which the class template is a member.
5880 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005881 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005882 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005883 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005884 // C++11 [temp.explicit]p3:
5885 // An explicit instantiation shall appear in an enclosing namespace of its
5886 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005887 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005888 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005889 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005890 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005891 "DC encloses TU but isn't in enclosing namespace set");
5892 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005893 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005894 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5895 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005896 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005897 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005898 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005899 Diag = diag::ext_template_spec_decl_out_of_scope;
5900 else
5901 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5902 S.Diag(Loc, Diag)
5903 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005905
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005906 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005907 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005909
Douglas Gregorf47b9112009-02-25 22:02:03 +00005910 return false;
5911}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912
Richard Smith6056d5e2014-02-09 00:54:43 +00005913static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5914 if (!E->isInstantiationDependent())
5915 return SourceLocation();
5916 DependencyChecker Checker(Depth);
5917 Checker.TraverseStmt(E);
5918 if (Checker.Match && Checker.MatchLoc.isInvalid())
5919 return E->getSourceRange();
5920 return Checker.MatchLoc;
5921}
5922
5923static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5924 if (!TL.getType()->isDependentType())
5925 return SourceLocation();
5926 DependencyChecker Checker(Depth);
5927 Checker.TraverseTypeLoc(TL);
5928 if (Checker.Match && Checker.MatchLoc.isInvalid())
5929 return TL.getSourceRange();
5930 return Checker.MatchLoc;
5931}
5932
Larisse Voufo39a1e502013-08-06 01:03:05 +00005933/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005934/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005935static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005936 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5937 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005938 for (unsigned I = 0; I != NumArgs; ++I) {
5939 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005940 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005941 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5942 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005943 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005944
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005945 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005947
Eli Friedmanb826a002012-09-26 02:36:12 +00005948 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005949 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005950
5951 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005952
Douglas Gregor98318c22011-01-03 21:37:45 +00005953 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005954 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5955 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005956
5957 // Strip off any implicit casts we added as part of type checking.
5958 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5959 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005960
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005961 // C++ [temp.class.spec]p8:
5962 // A non-type argument is non-specialized if it is the name of a
5963 // non-type parameter. All other non-type arguments are
5964 // specialized.
5965 //
5966 // Below, we check the two conditions that only apply to
5967 // specialized non-type arguments, so skip any non-specialized
5968 // arguments.
5969 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00005970 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005971 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005972
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005973 // C++ [temp.class.spec]p9:
5974 // Within the argument list of a class template partial
5975 // specialization, the following restrictions apply:
5976 // -- A partially specialized non-type argument expression
5977 // shall not involve a template parameter of the partial
5978 // specialization except when the argument expression is a
5979 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00005980 SourceRange ParamUseRange =
5981 findTemplateParameter(Param->getDepth(), ArgExpr);
5982 if (ParamUseRange.isValid()) {
5983 if (IsDefaultArgument) {
5984 S.Diag(TemplateNameLoc,
5985 diag::err_dependent_non_type_arg_in_partial_spec);
5986 S.Diag(ParamUseRange.getBegin(),
5987 diag::note_dependent_non_type_default_arg_in_partial_spec)
5988 << ParamUseRange;
5989 } else {
5990 S.Diag(ParamUseRange.getBegin(),
5991 diag::err_dependent_non_type_arg_in_partial_spec)
5992 << ParamUseRange;
5993 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005994 return true;
5995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005996
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005997 // -- The type of a template parameter corresponding to a
5998 // specialized non-type argument shall not be dependent on a
5999 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006000 //
6001 // FIXME: We need to delay this check until instantiation in some cases:
6002 //
6003 // template<template<typename> class X> struct A {
6004 // template<typename T, X<T> N> struct B;
6005 // template<typename T> struct B<T, 0>;
6006 // };
6007 // template<typename> using X = int;
6008 // A<X>::B<int, 0> b;
6009 ParamUseRange = findTemplateParameter(
6010 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6011 if (ParamUseRange.isValid()) {
6012 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6013 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6014 << Param->getType() << ParamUseRange;
6015 S.Diag(Param->getLocation(), diag::note_template_param_here)
6016 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006017 return true;
6018 }
6019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006020
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006021 return false;
6022}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006023
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006024/// \brief Check the non-type template arguments of a class template
6025/// partial specialization according to C++ [temp.class.spec]p9.
6026///
Richard Smith6056d5e2014-02-09 00:54:43 +00006027/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006028/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006029/// template.
6030/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006031/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006032/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006033///
Richard Smith6056d5e2014-02-09 00:54:43 +00006034/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006035static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006036 Sema &S, SourceLocation TemplateNameLoc,
6037 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006038 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006039 const TemplateArgument *ArgList = TemplateArgs.data();
6040
6041 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6042 NonTypeTemplateParmDecl *Param
6043 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6044 if (!Param)
6045 continue;
6046
Richard Smith6056d5e2014-02-09 00:54:43 +00006047 if (CheckNonTypeTemplatePartialSpecializationArgs(
6048 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006049 return true;
6050 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006051
6052 return false;
6053}
6054
John McCall48871652010-08-21 09:40:31 +00006055DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006056Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6057 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006058 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006059 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006060 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006061 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006062 MultiTemplateParamsArg
6063 TemplateParameterLists,
6064 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006065 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006066
Richard Smith4b55a9c2014-04-17 03:29:33 +00006067 CXXScopeSpec &SS = TemplateId.SS;
6068
Abramo Bagnara60804e12011-03-18 15:16:37 +00006069 // NOTE: KWLoc is the location of the tag keyword. This will instead
6070 // store the location of the outermost template keyword in the declaration.
6071 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006072 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6073 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6074 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6075 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006076
Douglas Gregor67a65642009-02-17 23:15:12 +00006077 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006078 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006079 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006080 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6081
6082 if (!ClassTemplate) {
6083 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006084 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006085 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6086 return true;
6087 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006088
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006089 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006090 bool isPartialSpecialization = false;
6091
Douglas Gregorf47b9112009-02-25 22:02:03 +00006092 // Check the validity of the template headers that introduce this
6093 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006094 // FIXME: We probably shouldn't complain about these headers for
6095 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006096 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006097 TemplateParameterList *TemplateParams =
6098 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006099 KWLoc, TemplateNameLoc, SS, &TemplateId,
6100 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6101 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006102 if (Invalid)
6103 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006104
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006105 if (TemplateParams && TemplateParams->size() > 0) {
6106 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006107
Douglas Gregorec9518b2010-12-21 08:14:57 +00006108 if (TUK == TUK_Friend) {
6109 Diag(KWLoc, diag::err_partial_specialization_friend)
6110 << SourceRange(LAngleLoc, RAngleLoc);
6111 return true;
6112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006113
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006114 // C++ [temp.class.spec]p10:
6115 // The template parameter list of a specialization shall not
6116 // contain default template argument values.
6117 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6118 Decl *Param = TemplateParams->getParam(I);
6119 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6120 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006121 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006122 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006123 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006124 }
6125 } else if (NonTypeTemplateParmDecl *NTTP
6126 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6127 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006128 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006129 diag::err_default_arg_in_partial_spec)
6130 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006131 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006132 }
6133 } else {
6134 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006135 if (TTP->hasDefaultArgument()) {
6136 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006137 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006138 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006139 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006140 }
6141 }
6142 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006143 } else if (TemplateParams) {
6144 if (TUK == TUK_Friend)
6145 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006146 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006147 SourceRange(TemplateParams->getTemplateLoc(),
6148 TemplateParams->getRAngleLoc()))
6149 << SourceRange(LAngleLoc, RAngleLoc);
6150 else
6151 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006152 } else {
6153 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006154 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006155
Douglas Gregor67a65642009-02-17 23:15:12 +00006156 // Check that the specialization uses the same tag kind as the
6157 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006158 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6159 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006160 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006161 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00006162 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006163 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006164 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006165 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006166 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006167 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006168 diag::note_previous_use);
6169 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6170 }
6171
Douglas Gregorc40290e2009-03-09 23:48:35 +00006172 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006173 TemplateArgumentListInfo TemplateArgs =
6174 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006175
Douglas Gregor14406932011-01-03 20:35:03 +00006176 // Check for unexpanded parameter packs in any of the template arguments.
6177 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006178 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006179 UPPC_PartialSpecialization))
6180 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006181
Douglas Gregor67a65642009-02-17 23:15:12 +00006182 // Check that the template argument list is well-formed for this
6183 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006184 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006185 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6186 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006187 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006188
Douglas Gregor2373c592009-05-31 09:31:02 +00006189 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006190 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006191 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006192 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006193 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6194 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006195 return true;
6196
Douglas Gregor678d76c2011-07-01 01:22:09 +00006197 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006198 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006199 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006201 TemplateArgs.size(),
6202 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006203 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6204 << ClassTemplate->getDeclName();
6205 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006206 }
6207 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006208
Craig Topperc3ec1492014-05-26 06:22:03 +00006209 void *InsertPos = nullptr;
6210 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006211
6212 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006213 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006214 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006215 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006216 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006217
Craig Topperc3ec1492014-05-26 06:22:03 +00006218 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006219
Douglas Gregorf47b9112009-02-25 22:02:03 +00006220 // Check whether we can declare a class template specialization in
6221 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006222 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006223 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6224 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006225 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006226 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006227
Douglas Gregor15301382009-07-30 17:40:51 +00006228 // The canonical type
6229 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006230 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006231 // Build the canonical type that describes the converted template
6232 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006233 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6234 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006235 Converted.data(),
6236 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006237
6238 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006239 ClassTemplate->getInjectedClassNameSpecialization())) {
6240 // C++ [temp.class.spec]p9b3:
6241 //
6242 // -- The argument list of the specialization shall not be identical
6243 // to the implicit argument list of the primary template.
6244 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006245 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006246 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006247 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6248 ClassTemplate->getIdentifier(),
6249 TemplateNameLoc,
6250 Attr,
6251 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006252 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006253 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006254 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006255 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006256 }
Douglas Gregor15301382009-07-30 17:40:51 +00006257
Douglas Gregor2373c592009-05-31 09:31:02 +00006258 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006259 ClassTemplatePartialSpecializationDecl *PrevPartial
6260 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006261 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006262 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006263 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006264 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006265 TemplateParams,
6266 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006267 Converted.data(),
6268 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006269 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006270 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006271 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006272 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006273 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006274 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006275 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006276 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006277 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006278
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006279 if (!PrevPartial)
6280 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006281 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006282
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006283 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006284 // template specialization, make a note of that.
6285 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6286 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006287
Douglas Gregor91772d12009-06-13 00:26:55 +00006288 // Check that all of the template parameters of the class template
6289 // partial specialization are deducible from the template
6290 // arguments. If not, this class template partial specialization
6291 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006292 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006293 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006294 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006295 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006296
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006297 if (!DeducibleParams.all()) {
6298 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006299 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006300 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006301 << SourceRange(TemplateNameLoc, RAngleLoc);
6302 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6303 if (!DeducibleParams[I]) {
6304 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6305 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006306 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006307 diag::note_partial_spec_unused_parameter)
6308 << Param->getDeclName();
6309 else
Mike Stump11289f42009-09-09 15:08:12 +00006310 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006311 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006312 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006313 }
6314 }
6315 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006316 } else {
6317 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006318 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006319 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006320 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006321 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006322 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006323 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006324 Converted.data(),
6325 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006326 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006327 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006328 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006329 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006330 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006331 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006332 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006333
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006334 if (!PrevDecl)
6335 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006336
6337 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006338 }
6339
Douglas Gregor06db9f52009-10-12 20:18:28 +00006340 // C++ [temp.expl.spec]p6:
6341 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006342 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006343 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006344 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006345 // use occurs; no diagnostic is required.
6346 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006347 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006348 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006349 // Is there any previous explicit specialization declaration?
6350 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6351 Okay = true;
6352 break;
6353 }
6354 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006355
Douglas Gregorc854c662010-02-26 06:03:23 +00006356 if (!Okay) {
6357 SourceRange Range(TemplateNameLoc, RAngleLoc);
6358 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6359 << Context.getTypeDeclType(Specialization) << Range;
6360
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006361 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006362 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006363 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006364 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006365 return true;
6366 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006368
Douglas Gregor2208a292009-09-26 20:57:03 +00006369 // If this is not a friend, note that this is an explicit specialization.
6370 if (TUK != TUK_Friend)
6371 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006372
6373 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006374 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006375 RecordDecl *Def = Specialization->getDefinition();
6376 NamedDecl *Hidden = nullptr;
6377 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6378 SkipBody->ShouldSkip = true;
6379 makeMergedDefinitionVisible(Hidden, KWLoc);
6380 // From here on out, treat this as just a redeclaration.
6381 TUK = TUK_Declaration;
6382 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006383 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006384 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006385 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006386 Diag(Def->getLocation(), diag::note_previous_definition);
6387 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006388 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006389 }
6390 }
6391
John McCall659a3372010-12-18 03:30:47 +00006392 if (Attr)
6393 ProcessDeclAttributeList(S, Specialization, Attr);
6394
Richard Smith034b94a2012-08-17 03:20:55 +00006395 // Add alignment attributes if necessary; these attributes are checked when
6396 // the ASTContext lays out the structure.
6397 if (TUK == TUK_Definition) {
6398 AddAlignmentAttributesForRecord(Specialization);
6399 AddMsStructLayoutForRecord(Specialization);
6400 }
6401
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006402 if (ModulePrivateLoc.isValid())
6403 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6404 << (isPartialSpecialization? 1 : 0)
6405 << FixItHint::CreateRemoval(ModulePrivateLoc);
6406
Douglas Gregord56a91e2009-02-26 22:19:44 +00006407 // Build the fully-sugared type for this class template
6408 // specialization as the user wrote in the specialization
6409 // itself. This means that we'll pretty-print the type retrieved
6410 // from the specialization's declaration the way that the user
6411 // actually wrote the specialization, rather than formatting the
6412 // name based on the "canonical" representation used to store the
6413 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006414 TypeSourceInfo *WrittenTy
6415 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6416 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006417 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006418 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006419 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006420 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006421
Douglas Gregor1e249f82009-02-25 22:18:32 +00006422 // C++ [temp.expl.spec]p9:
6423 // A template explicit specialization is in the scope of the
6424 // namespace in which the template was defined.
6425 //
6426 // We actually implement this paragraph where we set the semantic
6427 // context (in the creation of the ClassTemplateSpecializationDecl),
6428 // but we also maintain the lexical context where the actual
6429 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006430 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006431
Douglas Gregor67a65642009-02-17 23:15:12 +00006432 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006433 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006434 Specialization->startDefinition();
6435
Douglas Gregor2208a292009-09-26 20:57:03 +00006436 if (TUK == TUK_Friend) {
6437 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6438 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006439 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006440 /*FIXME:*/KWLoc);
6441 Friend->setAccess(AS_public);
6442 CurContext->addDecl(Friend);
6443 } else {
6444 // Add the specialization into its lexical context, so that it can
6445 // be seen when iterating through the list of declarations in that
6446 // context. However, specializations are not found by name lookup.
6447 CurContext->addDecl(Specialization);
6448 }
John McCall48871652010-08-21 09:40:31 +00006449 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006450}
Douglas Gregor333489b2009-03-27 23:10:48 +00006451
John McCall48871652010-08-21 09:40:31 +00006452Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006453 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006454 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006455 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006456 ActOnDocumentableDecl(NewDecl);
6457 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006458}
6459
John McCall48871652010-08-21 09:40:31 +00006460Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006461 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006462 Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006463 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006464 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006465
Douglas Gregor17a7c122009-06-24 00:54:41 +00006466 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006467 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006468 }
Mike Stump11289f42009-09-09 15:08:12 +00006469
Douglas Gregor17a7c122009-06-24 00:54:41 +00006470 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006471
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006472 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006473 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006474 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006475 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006476}
6477
John McCall4f7ced62010-02-11 01:33:53 +00006478/// \brief Strips various properties off an implicit instantiation
6479/// that has just been explicitly specialized.
6480static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006481 D->dropAttr<DLLImportAttr>();
6482 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006483
Nico Webere4974382014-12-19 23:52:45 +00006484 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006485 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006486}
6487
Nico Webera8f80b32012-01-09 19:52:25 +00006488/// \brief Compute the diagnostic location for an explicit instantiation
6489// declaration or definition.
6490static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006491 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006492 // Explicit instantiations following a specialization have no effect and
6493 // hence no PointOfInstantiation. In that case, walk decl backwards
6494 // until a valid name loc is found.
6495 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006496 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6497 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006498 PrevDiagLoc = Prev->getLocation();
6499 }
6500 assert(PrevDiagLoc.isValid() &&
6501 "Explicit instantiation without point of instantiation?");
6502 return PrevDiagLoc;
6503}
6504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006505/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006506/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006507/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006508/// new specialization/instantiation will have any effect.
6509///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006510/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006511/// instantiation.
6512///
6513/// \param NewTSK the kind of the new explicit specialization or instantiation.
6514///
6515/// \param PrevDecl the previous declaration of the entity.
6516///
6517/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6518///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006520/// declaration was instantiated (either implicitly or explicitly).
6521///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006522/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006523/// specialization or instantiation has no effect and should be ignored.
6524///
6525/// \returns true if there was an error that should prevent the introduction of
6526/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006527bool
6528Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6529 TemplateSpecializationKind NewTSK,
6530 NamedDecl *PrevDecl,
6531 TemplateSpecializationKind PrevTSK,
6532 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006533 bool &HasNoEffect) {
6534 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006536 switch (NewTSK) {
6537 case TSK_Undeclared:
6538 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006539 assert(
6540 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6541 "previous declaration must be implicit!");
6542 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006544 case TSK_ExplicitSpecialization:
6545 switch (PrevTSK) {
6546 case TSK_Undeclared:
6547 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006548 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006549 // explicitly specialized or has merely been mentioned without any
6550 // instantiation.
6551 return false;
6552
6553 case TSK_ImplicitInstantiation:
6554 if (PrevPointOfInstantiation.isInvalid()) {
6555 // The declaration itself has not actually been instantiated, so it is
6556 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006557 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006558 return false;
6559 }
6560 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006562 case TSK_ExplicitInstantiationDeclaration:
6563 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564 assert((PrevTSK == TSK_ImplicitInstantiation ||
6565 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006566 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006567
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006568 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006570 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006571 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006572 // implicit instantiation to take place, in every translation unit in
6573 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006574 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006575 // Is there any previous explicit specialization declaration?
6576 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6577 return false;
6578 }
6579
Douglas Gregor1d957a32009-10-27 18:42:08 +00006580 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006581 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006582 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006583 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006585 return true;
6586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006587
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006588 case TSK_ExplicitInstantiationDeclaration:
6589 switch (PrevTSK) {
6590 case TSK_ExplicitInstantiationDeclaration:
6591 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006592 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006593 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006595 case TSK_Undeclared:
6596 case TSK_ImplicitInstantiation:
6597 // We're explicitly instantiating something that may have already been
6598 // implicitly instantiated; that's fine.
6599 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006600
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006601 case TSK_ExplicitSpecialization:
6602 // C++0x [temp.explicit]p4:
6603 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006605 // specialization for that template, the explicit instantiation has no
6606 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006607 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006608 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006610 case TSK_ExplicitInstantiationDefinition:
6611 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612 // If an entity is the subject of both an explicit instantiation
6613 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006614 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006615 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006616 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006617
6618 // Explicit instantiations following a specialization have no effect and
6619 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6620 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006621 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6622 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006623 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006624 return false;
6625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006626
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006627 case TSK_ExplicitInstantiationDefinition:
6628 switch (PrevTSK) {
6629 case TSK_Undeclared:
6630 case TSK_ImplicitInstantiation:
6631 // We're explicitly instantiating something that may have already been
6632 // implicitly instantiated; that's fine.
6633 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006635 case TSK_ExplicitSpecialization:
6636 // C++ DR 259, C++0x [temp.explicit]p4:
6637 // For a given set of template parameters, if an explicit
6638 // instantiation of a template appears after a declaration of
6639 // an explicit specialization for that template, the explicit
6640 // instantiation has no effect.
6641 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006642 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006643 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006644 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006645 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006646 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6647 diag::ext_explicit_instantiation_after_specialization)
6648 << PrevDecl;
6649 Diag(PrevDecl->getLocation(),
6650 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006651 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006652 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006653
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006654 case TSK_ExplicitInstantiationDeclaration:
6655 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006657
6658 // C++0x [temp.explicit]p4:
6659 // For a given set of template parameters, if an explicit instantiation
6660 // of a template appears after a declaration of an explicit
6661 // specialization for that template, the explicit instantiation has no
6662 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006663 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006664 // Is there any previous explicit specialization declaration?
6665 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6666 HasNoEffect = true;
6667 break;
6668 }
6669 }
6670
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006671 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006672
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006673 case TSK_ExplicitInstantiationDefinition:
6674 // C++0x [temp.spec]p5:
6675 // For a given template and a given set of template-arguments,
6676 // - an explicit instantiation definition shall appear at most once
6677 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006678
6679 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6680 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006681 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006682 : diag::err_explicit_instantiation_duplicate)
6683 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006684 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006685 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006686 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006687 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006688 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
David Blaikie83d382b2011-09-23 05:06:16 +00006691 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006692}
6693
John McCallb9c78482010-04-08 09:05:18 +00006694/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006695/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006696///
James Dennettf14a6e52012-06-15 22:23:43 +00006697/// The only possible way to get a dependent function template specialization
6698/// is with a friend declaration, like so:
6699///
6700/// \code
6701/// template \<class T> void foo(T);
6702/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006703/// friend void foo<>(T);
6704/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006705/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006706///
6707/// There really isn't any useful analysis we can do here, so we
6708/// just store the information.
6709bool
6710Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6711 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6712 LookupResult &Previous) {
6713 // Remove anything from Previous that isn't a function template in
6714 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006715 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006716 LookupResult::Filter F = Previous.makeFilter();
6717 while (F.hasNext()) {
6718 NamedDecl *D = F.next()->getUnderlyingDecl();
6719 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006720 !FDLookupContext->InEnclosingNamespaceSetOf(
6721 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006722 F.erase();
6723 }
6724 F.done();
6725
6726 // Should this be diagnosed here?
6727 if (Previous.empty()) return true;
6728
6729 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6730 ExplicitTemplateArgs);
6731 return false;
6732}
6733
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006734/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006735/// specialization.
6736///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006737/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006738/// explicit function template specialization. On successful completion,
6739/// the function declaration \p FD will become a function template
6740/// specialization.
6741///
6742/// \param FD the function declaration, which will be updated to become a
6743/// function template specialization.
6744///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006745/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6746/// if any. Note that this may be valid info even when 0 arguments are
6747/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6748/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006749///
Francois Pichet3a44e432011-07-08 06:21:47 +00006750/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006751/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006752bool Sema::CheckFunctionTemplateSpecialization(
6753 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6754 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006755 // The set of function template specializations that could match this
6756 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006757 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006758 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006759
Sebastian Redl50c68252010-08-31 00:36:30 +00006760 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006761 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6762 I != E; ++I) {
6763 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6764 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006766 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006767 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6768 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006769 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Richard Smith574f4f62013-01-14 05:37:29 +00006771 // When matching a constexpr member function template specialization
6772 // against the primary template, we don't yet know whether the
6773 // specialization has an implicit 'const' (because we don't know whether
6774 // it will be a static member function until we know which template it
6775 // specializes), so adjust it now assuming it specializes this template.
6776 QualType FT = FD->getType();
6777 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006778 CXXMethodDecl *OldMD =
6779 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006780 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006781 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006782 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6783 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006784 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006785 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006786 }
6787 }
6788
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006789 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006790 // A trailing template-argument can be left unspecified in the
6791 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006792 // provided it can be deduced from the function argument type.
6793 // Perform template argument deduction to determine whether we may be
6794 // specializing this template.
6795 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006796 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006797 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006798 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6799 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6800 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006801 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006802 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006803 FailedCandidates.addCandidate()
6804 .set(FunTmpl->getTemplatedDecl(),
6805 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006806 (void)TDK;
6807 continue;
6808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006809
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006810 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006811 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006812 }
6813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814
Douglas Gregor5de279c2009-09-26 03:41:46 +00006815 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006816 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006817 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006818 FD->getLocation(),
6819 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6820 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006821 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006822 PDiag(diag::note_function_template_spec_matched));
6823
John McCall58cc69d2010-01-27 01:50:18 +00006824 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006825 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006826
6827 // Ignore access information; it doesn't figure into redeclaration checking.
6828 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006829
6830 FunctionTemplateSpecializationInfo *SpecInfo
6831 = Specialization->getTemplateSpecializationInfo();
6832 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006833
6834 // Note: do not overwrite location info if previous template
6835 // specialization kind was explicit.
6836 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006837 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006838 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006839 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6840 // function can differ from the template declaration with respect to
6841 // the constexpr specifier.
6842 Specialization->setConstexpr(FD->isConstexpr());
6843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006845 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006846 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006847
6848 // If this is a friend declaration, then we're not really declaring
6849 // an explicit specialization.
6850 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006851
Douglas Gregor54888652009-10-07 00:13:32 +00006852 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006853 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006855 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006856 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006857 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006858 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006859
6860 // C++ [temp.expl.spec]p6:
6861 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006863 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006864 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006865 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006866 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006867 if (!isFriend &&
6868 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006869 TSK_ExplicitSpecialization,
6870 Specialization,
6871 SpecInfo->getTemplateSpecializationKind(),
6872 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006873 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006874 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006875
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006876 // Mark the prior declaration as an explicit specialization, so that later
6877 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006878 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006879 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006880 MarkUnusedFileScopedDecl(Specialization);
6881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006882
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006883 // Turn the given function declaration into a function template
6884 // specialization, with the template arguments from the previous
6885 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006886 // Take copies of (semantic and syntactic) template argument lists.
6887 const TemplateArgumentList* TemplArgs = new (Context)
6888 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006889 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006890 TemplArgs, /*InsertPos=*/nullptr,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006891 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006892 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006893
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006894 // The "previous declaration" for this function template specialization is
6895 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006896 Previous.clear();
6897 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006898 return false;
6899}
6900
Douglas Gregor86d142a2009-10-08 07:24:58 +00006901/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006902/// specialization.
6903///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006904/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006905/// explicit member function specialization. On successful completion,
6906/// the function declaration \p FD will become a member function
6907/// specialization.
6908///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006909/// \param Member the member declaration, which will be updated to become a
6910/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006911///
John McCall1f82f242009-11-18 22:49:29 +00006912/// \param Previous the set of declarations, one of which may be specialized
6913/// by this function specialization; the set will be modified to contain the
6914/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006915bool
John McCall1f82f242009-11-18 22:49:29 +00006916Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006917 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006918
Douglas Gregor86d142a2009-10-08 07:24:58 +00006919 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00006920 NamedDecl *Instantiation = nullptr;
6921 NamedDecl *InstantiatedFrom = nullptr;
6922 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006923
John McCall1f82f242009-11-18 22:49:29 +00006924 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006925 // Nowhere to look anyway.
6926 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006927 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6928 I != E; ++I) {
6929 NamedDecl *D = (*I)->getUnderlyingDecl();
6930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006931 QualType Adjusted = Function->getType();
6932 if (!hasExplicitCallingConv(Adjusted))
6933 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6934 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006935 Instantiation = Method;
6936 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006937 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006938 break;
6939 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006940 }
6941 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006942 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006943 VarDecl *PrevVar;
6944 if (Previous.isSingleResult() &&
6945 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006946 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006947 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006948 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006949 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006950 }
6951 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006952 CXXRecordDecl *PrevRecord;
6953 if (Previous.isSingleResult() &&
6954 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6955 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006956 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006957 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006958 }
Richard Smith7d137e32012-03-23 03:33:32 +00006959 } else if (isa<EnumDecl>(Member)) {
6960 EnumDecl *PrevEnum;
6961 if (Previous.isSingleResult() &&
6962 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6963 Instantiation = PrevEnum;
6964 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6965 MSInfo = PrevEnum->getMemberSpecializationInfo();
6966 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006969 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006970 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006971 // specializations are always out-of-line, the caller will complain about
6972 // this mismatch later.
6973 return false;
6974 }
John McCalle820e5e2010-04-13 20:37:33 +00006975
6976 // If this is a friend, just bail out here before we start turning
6977 // things into explicit specializations.
6978 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6979 // Preserve instantiation information.
6980 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6981 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6982 cast<CXXMethodDecl>(InstantiatedFrom),
6983 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6984 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6985 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6986 cast<CXXRecordDecl>(InstantiatedFrom),
6987 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6988 }
6989
6990 Previous.clear();
6991 Previous.addDecl(Instantiation);
6992 return false;
6993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006994
Douglas Gregor86d142a2009-10-08 07:24:58 +00006995 // Make sure that this is a specialization of a member.
6996 if (!InstantiatedFrom) {
6997 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6998 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006999 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7000 return true;
7001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002
Douglas Gregor06db9f52009-10-12 20:18:28 +00007003 // C++ [temp.expl.spec]p6:
7004 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007005 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007006 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007007 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007008 // use occurs; no diagnostic is required.
7009 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007010
Abramo Bagnara8075c852010-06-12 07:44:57 +00007011 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007012 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7013 TSK_ExplicitSpecialization,
7014 Instantiation,
7015 MSInfo->getTemplateSpecializationKind(),
7016 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007017 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007018 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007020 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007021 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007022 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007023 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007024 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007025 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007026
Douglas Gregor86d142a2009-10-08 07:24:58 +00007027 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007028 // the original declaration to note that it is an explicit specialization
7029 // (if it was previously an implicit instantiation). This latter step
7030 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007031 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007032 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7033 if (InstantiationFunction->getTemplateSpecializationKind() ==
7034 TSK_ImplicitInstantiation) {
7035 InstantiationFunction->setTemplateSpecializationKind(
7036 TSK_ExplicitSpecialization);
7037 InstantiationFunction->setLocation(Member->getLocation());
7038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007039
Douglas Gregor86d142a2009-10-08 07:24:58 +00007040 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7041 cast<CXXMethodDecl>(InstantiatedFrom),
7042 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007043 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007044 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007045 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7046 if (InstantiationVar->getTemplateSpecializationKind() ==
7047 TSK_ImplicitInstantiation) {
7048 InstantiationVar->setTemplateSpecializationKind(
7049 TSK_ExplicitSpecialization);
7050 InstantiationVar->setLocation(Member->getLocation());
7051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007052
Larisse Voufo39a1e502013-08-06 01:03:05 +00007053 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7054 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007055 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007056 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007057 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7058 if (InstantiationClass->getTemplateSpecializationKind() ==
7059 TSK_ImplicitInstantiation) {
7060 InstantiationClass->setTemplateSpecializationKind(
7061 TSK_ExplicitSpecialization);
7062 InstantiationClass->setLocation(Member->getLocation());
7063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007064
Douglas Gregor86d142a2009-10-08 07:24:58 +00007065 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007066 cast<CXXRecordDecl>(InstantiatedFrom),
7067 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007068 } else {
7069 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7070 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7071 if (InstantiationEnum->getTemplateSpecializationKind() ==
7072 TSK_ImplicitInstantiation) {
7073 InstantiationEnum->setTemplateSpecializationKind(
7074 TSK_ExplicitSpecialization);
7075 InstantiationEnum->setLocation(Member->getLocation());
7076 }
7077
7078 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7079 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007081
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007082 // Save the caller the trouble of having to figure out which declaration
7083 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007084 Previous.clear();
7085 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007086 return false;
7087}
7088
Douglas Gregore47f5a72009-10-14 23:41:34 +00007089/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007090///
7091/// \returns true if a serious error occurs, false otherwise.
7092static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007093 SourceLocation InstLoc,
7094 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007095 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7096 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007097
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007098 if (CurContext->isRecord()) {
7099 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7100 << D;
7101 return true;
7102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103
Richard Smith050d2612011-10-18 02:28:33 +00007104 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007105 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007106 // template. If the name declared in the explicit instantiation is an
7107 // unqualified name, the explicit instantiation shall appear in the
7108 // namespace where its template is declared or, if that namespace is inline
7109 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007110 //
7111 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007112 if (WasQualifiedName) {
7113 if (CurContext->Encloses(OrigContext))
7114 return false;
7115 } else {
7116 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7117 return false;
7118 }
7119
7120 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7121 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007122 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007123 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007124 diag::err_explicit_instantiation_out_of_scope :
7125 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007126 << D << NS;
7127 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007129 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007130 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7131 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7132 << D << NS;
7133 } else
7134 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007135 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007136 diag::err_explicit_instantiation_must_be_global :
7137 diag::warn_explicit_instantiation_must_be_global_0x)
7138 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007139 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007140 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007141}
7142
7143/// \brief Determine whether the given scope specifier has a template-id in it.
7144static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7145 if (!SS.isSet())
7146 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007147
Richard Smith050d2612011-10-18 02:28:33 +00007148 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007149 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007150 // or a static data member of a class template specialization, the name of
7151 // the class template specialization in the qualified-id for the member
7152 // name shall be a simple-template-id.
7153 //
7154 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007155 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7156 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007157 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007158 if (isa<TemplateSpecializationType>(T))
7159 return true;
7160
7161 return false;
7162}
7163
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007164// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007165DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007166Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007167 SourceLocation ExternLoc,
7168 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007169 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007170 SourceLocation KWLoc,
7171 const CXXScopeSpec &SS,
7172 TemplateTy TemplateD,
7173 SourceLocation TemplateNameLoc,
7174 SourceLocation LAngleLoc,
7175 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007176 SourceLocation RAngleLoc,
7177 AttributeList *Attr) {
7178 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007179 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007180 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007181 // Check that the specialization uses the same tag kind as the
7182 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007183 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7184 assert(Kind != TTK_Enum &&
7185 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007186
7187 if (isa<TypeAliasTemplateDecl>(TD)) {
7188 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7189 Diag(TD->getTemplatedDecl()->getLocation(),
7190 diag::note_previous_use);
7191 return true;
7192 }
7193
7194 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7195
Douglas Gregord9034f02009-05-14 16:41:31 +00007196 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007197 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00007198 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007199 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007200 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007201 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007202 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007203 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007204 diag::note_previous_use);
7205 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7206 }
7207
Douglas Gregore47f5a72009-10-14 23:41:34 +00007208 // C++0x [temp.explicit]p2:
7209 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007210 // definition and an explicit instantiation declaration. An explicit
7211 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007212 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7213 ? TSK_ExplicitInstantiationDefinition
7214 : TSK_ExplicitInstantiationDeclaration;
7215
7216 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7217 // Check for dllexport class template instantiation declarations.
7218 for (AttributeList *A = Attr; A; A = A->getNext()) {
7219 if (A->getKind() == AttributeList::AT_DLLExport) {
7220 Diag(ExternLoc,
7221 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7222 Diag(A->getLoc(), diag::note_attribute);
7223 break;
7224 }
7225 }
7226
7227 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7228 Diag(ExternLoc,
7229 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7230 Diag(A->getLocation(), diag::note_attribute);
7231 }
7232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007233
Douglas Gregora1f49972009-05-13 00:25:59 +00007234 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007235 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007236 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007237
7238 // Check that the template argument list is well-formed for this
7239 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007240 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007241 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7242 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007243 return true;
7244
Douglas Gregora1f49972009-05-13 00:25:59 +00007245 // Find the class template specialization declaration that
7246 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007247 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007248 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007249 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007250
Abramo Bagnara8075c852010-06-12 07:44:57 +00007251 TemplateSpecializationKind PrevDecl_TSK
7252 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7253
Douglas Gregor54888652009-10-07 00:13:32 +00007254 // C++0x [temp.explicit]p2:
7255 // [...] An explicit instantiation shall appear in an enclosing
7256 // namespace of its template. [...]
7257 //
7258 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007259 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7260 SS.isSet()))
7261 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007262
Craig Topperc3ec1492014-05-26 06:22:03 +00007263 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007264
Abramo Bagnara8075c852010-06-12 07:44:57 +00007265 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007266 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007267 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007268 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007269 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007270 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007271 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007272
Abramo Bagnara8075c852010-06-12 07:44:57 +00007273 // Even though HasNoEffect == true means that this explicit instantiation
7274 // has no effect on semantics, we go on to put its syntax in the AST.
7275
7276 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7277 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007278 // Since the only prior class template specialization with these
7279 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007280 // declaration node as our own, updating the source location
7281 // for the template name to reflect our new declaration.
7282 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007283 Specialization = PrevDecl;
7284 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007285 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007286 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007287 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007288
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007289 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007290 // Create a new class template specialization declaration node for
7291 // this explicit specialization.
7292 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007293 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007294 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007295 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007296 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007297 Converted.data(),
7298 Converted.size(),
7299 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007300 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007301
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007302 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007303 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007304 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007305 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007306 }
7307
7308 // Build the fully-sugared type for this explicit instantiation as
7309 // the user wrote in the explicit instantiation itself. This means
7310 // that we'll pretty-print the type retrieved from the
7311 // specialization's declaration the way that the user actually wrote
7312 // the explicit instantiation, rather than formatting the name based
7313 // on the "canonical" representation used to store the template
7314 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007315 TypeSourceInfo *WrittenTy
7316 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7317 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007318 Context.getTypeDeclType(Specialization));
7319 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007320
Abramo Bagnara8075c852010-06-12 07:44:57 +00007321 // Set source locations for keywords.
7322 Specialization->setExternLoc(ExternLoc);
7323 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007324 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007325
Rafael Espindola0b062072012-01-03 06:04:21 +00007326 if (Attr)
7327 ProcessDeclAttributeList(S, Specialization, Attr);
7328
Abramo Bagnara8075c852010-06-12 07:44:57 +00007329 // Add the explicit instantiation into its lexical context. However,
7330 // since explicit instantiations are never found by name lookup, we
7331 // just put it into the declaration context directly.
7332 Specialization->setLexicalDeclContext(CurContext);
7333 CurContext->addDecl(Specialization);
7334
7335 // Syntax is now OK, so return if it has no other effect on semantics.
7336 if (HasNoEffect) {
7337 // Set the template specialization kind.
7338 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007339 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007340 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007341
7342 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007343 // A definition of a class template or class member template
7344 // shall be in scope at the point of the explicit instantiation of
7345 // the class template or class member template.
7346 //
7347 // This check comes when we actually try to perform the
7348 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007349 ClassTemplateSpecializationDecl *Def
7350 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007351 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007352 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007353 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007354 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007355 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007356 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7357 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007358
Douglas Gregor1d957a32009-10-27 18:42:08 +00007359 // Instantiate the members of this class template specialization.
7360 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007361 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007362 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007363 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7364
7365 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7366 // TSK_ExplicitInstantiationDefinition
7367 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007368 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007369 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007370 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007371
Hans Wennborg17f9b442015-05-27 00:06:45 +00007372 if (!getDLLAttr(Def) && getDLLAttr(Specialization)) {
7373 auto *A = cast<InheritableAttr>(
7374 getDLLAttr(Specialization)->clone(getASTContext()));
7375 A->setInherited(true);
7376 Def->addAttr(A);
7377 checkClassLevelDLLAttribute(Def);
7378 }
7379 }
7380
Douglas Gregor12e49d32009-10-15 22:53:21 +00007381 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007382 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007383
Abramo Bagnara8075c852010-06-12 07:44:57 +00007384 // Set the template specialization kind.
7385 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007386 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007387}
7388
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007389// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007390DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007391Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007392 SourceLocation ExternLoc,
7393 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007394 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007395 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007396 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007397 IdentifierInfo *Name,
7398 SourceLocation NameLoc,
7399 AttributeList *Attr) {
7400
Douglas Gregord6ab8742009-05-28 23:31:59 +00007401 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007402 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007403 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007404 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007405 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007406 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007407 SourceLocation(), false, TypeResult(),
7408 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007409 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7410
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007411 if (!TagD)
7412 return true;
7413
John McCall48871652010-08-21 09:40:31 +00007414 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007415 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007416
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007417 if (Tag->isInvalidDecl())
7418 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007419
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007420 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7421 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7422 if (!Pattern) {
7423 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7424 << Context.getTypeDeclType(Record);
7425 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7426 return true;
7427 }
7428
Douglas Gregore47f5a72009-10-14 23:41:34 +00007429 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007430 // If the explicit instantiation is for a class or member class, the
7431 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007432 // simple-template-id.
7433 //
7434 // C++98 has the same restriction, just worded differently.
7435 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007436 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007437 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007438
Douglas Gregore47f5a72009-10-14 23:41:34 +00007439 // C++0x [temp.explicit]p2:
7440 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007441 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007442 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007443 TemplateSpecializationKind TSK
7444 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7445 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007446
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007447 // C++0x [temp.explicit]p2:
7448 // [...] An explicit instantiation shall appear in an enclosing
7449 // namespace of its template. [...]
7450 //
7451 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007452 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007454 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007455 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007456 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007457 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007458 PrevDecl = Record;
7459 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007460 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007461 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007462 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007463 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007464 PrevDecl,
7465 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007466 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007467 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007468 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007469 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007470 return TagD;
7471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007472
Douglas Gregor12e49d32009-10-15 22:53:21 +00007473 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007474 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007475 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007476 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007477 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007478 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007479 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007480 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007481 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007482 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7483 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007484 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7485 << Pattern;
7486 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007487 } else {
7488 if (InstantiateClass(NameLoc, Record, Def,
7489 getTemplateInstantiationArgs(Record),
7490 TSK))
7491 return true;
7492
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007493 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007494 if (!RecordDef)
7495 return true;
7496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007497 }
7498
Douglas Gregor1d957a32009-10-27 18:42:08 +00007499 // Instantiate all of the members of the class.
7500 InstantiateClassMembers(NameLoc, RecordDef,
7501 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007502
Douglas Gregor88d292c2010-05-13 16:44:06 +00007503 if (TSK == TSK_ExplicitInstantiationDefinition)
7504 MarkVTableUsed(NameLoc, RecordDef, true);
7505
Mike Stump87c57ac2009-05-16 07:39:55 +00007506 // FIXME: We don't have any representation for explicit instantiations of
7507 // member classes. Such a representation is not needed for compilation, but it
7508 // should be available for clients that want to see all of the declarations in
7509 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007510 return TagD;
7511}
7512
John McCallfaf5fb42010-08-26 23:41:50 +00007513DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7514 SourceLocation ExternLoc,
7515 SourceLocation TemplateLoc,
7516 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007517 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007518 // TODO: check if/when DNInfo should replace Name.
7519 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7520 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007521 if (!Name) {
7522 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007523 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007524 diag::err_explicit_instantiation_requires_name)
7525 << D.getDeclSpec().getSourceRange()
7526 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007527
Douglas Gregor450f00842009-09-25 18:43:00 +00007528 return true;
7529 }
7530
7531 // The scope passed in may not be a decl scope. Zip up the scope tree until
7532 // we find one that is.
7533 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7534 (S->getFlags() & Scope::TemplateParamScope) != 0)
7535 S = S->getParent();
7536
7537 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007538 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7539 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007540 if (R.isNull())
7541 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007542
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007543 // C++ [dcl.stc]p1:
7544 // A storage-class-specifier shall not be specified in [...] an explicit
7545 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007546 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007547 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7548 << Name;
7549 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007550 } else if (D.getDeclSpec().getStorageClassSpec()
7551 != DeclSpec::SCS_unspecified) {
7552 // Complain about then remove the storage class specifier.
7553 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7554 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7555
7556 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007557 }
7558
Douglas Gregor3c74d412009-10-14 20:14:33 +00007559 // C++0x [temp.explicit]p1:
7560 // [...] An explicit instantiation of a function template shall not use the
7561 // inline or constexpr specifiers.
7562 // Presumably, this also applies to member functions of class templates as
7563 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007564 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007565 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007566 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007567 diag::err_explicit_instantiation_inline :
7568 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007569 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007570 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007571 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7572 // not already specified.
7573 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7574 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007575
Douglas Gregore47f5a72009-10-14 23:41:34 +00007576 // C++0x [temp.explicit]p2:
7577 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578 // definition and an explicit instantiation declaration. An explicit
7579 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007580 TemplateSpecializationKind TSK
7581 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7582 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007583
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007584 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007585 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007586
7587 if (!R->isFunctionType()) {
7588 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007589 // A [...] static data member of a class template can be explicitly
7590 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007591 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007592 // C++1y [temp.explicit]p1:
7593 // A [...] variable [...] template specialization can be explicitly
7594 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007595 if (Previous.isAmbiguous())
7596 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007597
John McCall67c00872009-12-02 08:25:40 +00007598 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007599 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007600
Larisse Voufo39a1e502013-08-06 01:03:05 +00007601 if (!PrevTemplate) {
7602 if (!Prev || !Prev->isStaticDataMember()) {
7603 // We expect to see a data data member here.
7604 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7605 << Name;
7606 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7607 P != PEnd; ++P)
7608 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7609 return true;
7610 }
7611
7612 if (!Prev->getInstantiatedFromStaticDataMember()) {
7613 // FIXME: Check for explicit specialization?
7614 Diag(D.getIdentifierLoc(),
7615 diag::err_explicit_instantiation_data_member_not_instantiated)
7616 << Prev;
7617 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7618 // FIXME: Can we provide a note showing where this was declared?
7619 return true;
7620 }
7621 } else {
7622 // Explicitly instantiate a variable template.
7623
7624 // C++1y [dcl.spec.auto]p6:
7625 // ... A program that uses auto or decltype(auto) in a context not
7626 // explicitly allowed in this section is ill-formed.
7627 //
7628 // This includes auto-typed variable template instantiations.
7629 if (R->isUndeducedType()) {
7630 Diag(T->getTypeLoc().getLocStart(),
7631 diag::err_auto_not_allowed_var_inst);
7632 return true;
7633 }
7634
Richard Smithef985ac2013-09-18 02:10:12 +00007635 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7636 // C++1y [temp.explicit]p3:
7637 // If the explicit instantiation is for a variable, the unqualified-id
7638 // in the declaration shall be a template-id.
7639 Diag(D.getIdentifierLoc(),
7640 diag::err_explicit_instantiation_without_template_id)
7641 << PrevTemplate;
7642 Diag(PrevTemplate->getLocation(),
7643 diag::note_explicit_instantiation_here);
7644 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007645 }
7646
Richard Smithef985ac2013-09-18 02:10:12 +00007647 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007648 TemplateArgumentListInfo TemplateArgs =
7649 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007650
Larisse Voufo39a1e502013-08-06 01:03:05 +00007651 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7652 D.getIdentifierLoc(), TemplateArgs);
7653 if (Res.isInvalid())
7654 return true;
7655
7656 // Ignore access control bits, we don't need them for redeclaration
7657 // checking.
7658 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007660
Douglas Gregore47f5a72009-10-14 23:41:34 +00007661 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007662 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007663 // or a static data member of a class template specialization, the name of
7664 // the class template specialization in the qualified-id for the member
7665 // name shall be a simple-template-id.
7666 //
7667 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007668 //
Richard Smith5977d872013-09-18 21:55:14 +00007669 // This does not apply to variable template specializations, where the
7670 // template-id is in the unqualified-id instead.
7671 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007672 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007673 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007674 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007675
Douglas Gregore47f5a72009-10-14 23:41:34 +00007676 // Check the scope of this explicit instantiation.
7677 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007678
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007679 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007680 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7681 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007682 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007683 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007684 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007685 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007686
Larisse Voufo39a1e502013-08-06 01:03:05 +00007687 if (!HasNoEffect) {
7688 // Instantiate static data member or variable template.
7689
7690 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7691 if (PrevTemplate) {
7692 // Merge attributes.
7693 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7694 ProcessDeclAttributeList(S, Prev, Attr);
7695 }
7696 if (TSK == TSK_ExplicitInstantiationDefinition)
7697 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7698 }
7699
7700 // Check the new variable specialization against the parsed input.
7701 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7702 Diag(T->getTypeLoc().getLocStart(),
7703 diag::err_invalid_var_template_spec_type)
7704 << 0 << PrevTemplate << R << Prev->getType();
7705 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7706 << 2 << PrevTemplate->getDeclName();
7707 return true;
7708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007709
Douglas Gregor450f00842009-09-25 18:43:00 +00007710 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007711 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007713
7714 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007715 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007716 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007717 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007718 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007719 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007720 HasExplicitTemplateArgs = true;
7721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722
Douglas Gregor450f00842009-09-25 18:43:00 +00007723 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007724 // A [...] function [...] can be explicitly instantiated from its template.
7725 // A member function [...] of a class template can be explicitly
7726 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007727 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007728 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007729 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007730 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7731 P != PEnd; ++P) {
7732 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007733 if (!HasExplicitTemplateArgs) {
7734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007735 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7736 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007737 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007738
John McCall58cc69d2010-01-27 01:50:18 +00007739 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007740 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7741 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007742 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007743 }
7744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007745
Douglas Gregor450f00842009-09-25 18:43:00 +00007746 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7747 if (!FunTmpl)
7748 continue;
7749
Larisse Voufo98b20f12013-07-19 23:00:19 +00007750 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007751 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007752 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007753 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007754 (HasExplicitTemplateArgs ? &TemplateArgs
7755 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007756 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007757 // Keep track of almost-matches.
7758 FailedCandidates.addCandidate()
7759 .set(FunTmpl->getTemplatedDecl(),
7760 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007761 (void)TDK;
7762 continue;
7763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007764
John McCall58cc69d2010-01-27 01:50:18 +00007765 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007767
Douglas Gregor450f00842009-09-25 18:43:00 +00007768 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007769 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007770 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007771 D.getIdentifierLoc(),
7772 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7773 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7774 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007775
John McCall58cc69d2010-01-27 01:50:18 +00007776 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007777 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007778
7779 // Ignore access control bits, we don't need them for redeclaration checking.
7780 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007781
Alexey Bataev73983912014-11-06 10:10:50 +00007782 // C++11 [except.spec]p4
7783 // In an explicit instantiation an exception-specification may be specified,
7784 // but is not required.
7785 // If an exception-specification is specified in an explicit instantiation
7786 // directive, it shall be compatible with the exception-specifications of
7787 // other declarations of that function.
7788 if (auto *FPT = R->getAs<FunctionProtoType>())
7789 if (FPT->hasExceptionSpec()) {
7790 unsigned DiagID =
7791 diag::err_mismatched_exception_spec_explicit_instantiation;
7792 if (getLangOpts().MicrosoftExt)
7793 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7794 bool Result = CheckEquivalentExceptionSpec(
7795 PDiag(DiagID) << Specialization->getType(),
7796 PDiag(diag::note_explicit_instantiation_here),
7797 Specialization->getType()->getAs<FunctionProtoType>(),
7798 Specialization->getLocation(), FPT, D.getLocStart());
7799 // In Microsoft mode, mismatching exception specifications just cause a
7800 // warning.
7801 if (!getLangOpts().MicrosoftExt && Result)
7802 return true;
7803 }
7804
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007805 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007806 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007807 diag::err_explicit_instantiation_member_function_not_instantiated)
7808 << Specialization
7809 << (Specialization->getTemplateSpecializationKind() ==
7810 TSK_ExplicitSpecialization);
7811 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7812 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007813 }
7814
Douglas Gregorec9fd132012-01-14 16:38:05 +00007815 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007816 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7817 PrevDecl = Specialization;
7818
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007819 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007820 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007821 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007822 PrevDecl,
7823 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007824 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007825 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007826 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007827
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007828 // FIXME: We may still want to build some representation of this
7829 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007830 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007831 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007832 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007833
7834 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007835 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7836 if (Attr)
7837 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007838
Richard Smitheb36ddf2014-04-24 22:45:46 +00007839 if (Specialization->isDefined()) {
7840 // Let the ASTConsumer know that this function has been explicitly
7841 // instantiated now, and its linkage might have changed.
7842 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7843 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007844 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007845
Douglas Gregore47f5a72009-10-14 23:41:34 +00007846 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007847 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007848 // or a static data member of a class template specialization, the name of
7849 // the class template specialization in the qualified-id for the member
7850 // name shall be a simple-template-id.
7851 //
7852 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007853 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007854 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007855 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007856 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007857 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007858 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007859 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007860
Douglas Gregore47f5a72009-10-14 23:41:34 +00007861 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007862 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007863 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007864 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007865 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007866
Douglas Gregor450f00842009-09-25 18:43:00 +00007867 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007868 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007869}
7870
John McCallfaf5fb42010-08-26 23:41:50 +00007871TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007872Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7873 const CXXScopeSpec &SS, IdentifierInfo *Name,
7874 SourceLocation TagLoc, SourceLocation NameLoc) {
7875 // This has to hold, because SS is expected to be defined.
7876 assert(Name && "Expected a name in a dependent tag");
7877
Aaron Ballman4a979672014-01-03 13:56:08 +00007878 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007879 if (!NNS)
7880 return true;
7881
Abramo Bagnara6150c882010-05-11 21:36:43 +00007882 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007883
Douglas Gregorba41d012010-04-24 16:38:41 +00007884 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7885 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007886 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007887 return true;
7888 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007889
Douglas Gregore7c20652011-03-02 00:47:37 +00007890 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007891 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007892 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7893
7894 // Create type-source location information for this type.
7895 TypeLocBuilder TLB;
7896 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007897 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007898 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7899 TL.setNameLoc(NameLoc);
7900 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007901}
7902
John McCallfaf5fb42010-08-26 23:41:50 +00007903TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007904Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7905 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007906 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007907 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007908 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007909
Richard Smith0bf8a4922011-10-18 20:49:44 +00007910 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7911 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007912 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007913 diag::warn_cxx98_compat_typename_outside_of_template :
7914 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007915 << FixItHint::CreateRemoval(TypenameLoc);
7916
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007917 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007918 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7919 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007920 if (T.isNull())
7921 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007922
7923 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7924 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007925 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007926 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007927 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007928 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007929 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007930 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007931 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007932 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007933 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007935
John McCallba7bf592010-08-24 05:47:05 +00007936 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007937}
7938
John McCallfaf5fb42010-08-26 23:41:50 +00007939TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007940Sema::ActOnTypenameType(Scope *S,
7941 SourceLocation TypenameLoc,
7942 const CXXScopeSpec &SS,
7943 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007944 TemplateTy TemplateIn,
7945 SourceLocation TemplateNameLoc,
7946 SourceLocation LAngleLoc,
7947 ASTTemplateArgsPtr TemplateArgsIn,
7948 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007949 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7950 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007951 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007952 diag::warn_cxx98_compat_typename_outside_of_template :
7953 diag::ext_typename_outside_of_template)
7954 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007955
7956 // Translate the parser's template argument list in our AST format.
7957 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7958 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7959
7960 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007961 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7962 // Construct a dependent template specialization type.
7963 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00007964 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007965 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7966 DTN->getQualifier(),
7967 DTN->getIdentifier(),
7968 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007969
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007970 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00007971 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007972 DependentTemplateSpecializationTypeLoc SpecTL
7973 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007974 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7975 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00007976 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007977 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007978 SpecTL.setLAngleLoc(LAngleLoc);
7979 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007980 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7981 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007982 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00007983 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00007984
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007985 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7986 if (T.isNull())
7987 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00007988
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007989 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00007990 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007991 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007992 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007993 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7994 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007995 SpecTL.setLAngleLoc(LAngleLoc);
7996 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007997 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7998 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7999
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008000 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8001 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008002 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008003 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8004
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008005 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8006 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008007}
8008
Douglas Gregorb09518c2011-02-27 22:46:49 +00008009
Richard Smith6f8d2c62012-05-09 05:17:00 +00008010/// Determine whether this failed name lookup should be treated as being
8011/// disabled by a usage of std::enable_if.
8012static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8013 SourceRange &CondRange) {
8014 // We must be looking for a ::type...
8015 if (!II.isStr("type"))
8016 return false;
8017
8018 // ... within an explicitly-written template specialization...
8019 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8020 return false;
8021 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008022 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8023 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8024 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008025 return false;
8026 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008027 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008028
8029 // ... which names a complete class template declaration...
8030 const TemplateDecl *EnableIfDecl =
8031 EnableIfTST->getTemplateName().getAsTemplateDecl();
8032 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8033 return false;
8034
8035 // ... called "enable_if".
8036 const IdentifierInfo *EnableIfII =
8037 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8038 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8039 return false;
8040
8041 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008042 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008043 return true;
8044}
8045
Douglas Gregor333489b2009-03-27 23:10:48 +00008046/// \brief Build the type that describes a C++ typename specifier,
8047/// e.g., "typename T::type".
8048QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008049Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8050 SourceLocation KeywordLoc,
8051 NestedNameSpecifierLoc QualifierLoc,
8052 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008053 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008054 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008055 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008056
John McCall0b66eb32010-05-01 00:40:08 +00008057 DeclContext *Ctx = computeDeclContext(SS);
8058 if (!Ctx) {
8059 // If the nested-name-specifier is dependent and couldn't be
8060 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008061 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8062 return Context.getDependentNameType(Keyword,
8063 QualifierLoc.getNestedNameSpecifier(),
8064 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008065 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008066
John McCall0b66eb32010-05-01 00:40:08 +00008067 // If the nested-name-specifier refers to the current instantiation,
8068 // the "typename" keyword itself is superfluous. In C++03, the
8069 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8070 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008071 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008072
John McCall0b66eb32010-05-01 00:40:08 +00008073 if (RequireCompleteDeclContext(SS, Ctx))
8074 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008075
8076 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008077 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008078 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008079 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008080 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008081 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008082 case LookupResult::NotFound: {
8083 // If we're looking up 'type' within a template named 'enable_if', produce
8084 // a more specific diagnostic.
8085 SourceRange CondRange;
8086 if (isEnableIf(QualifierLoc, II, CondRange)) {
8087 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8088 << Ctx << CondRange;
8089 return QualType();
8090 }
8091
Douglas Gregore40876a2009-10-13 21:16:44 +00008092 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008093 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008094 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008095
8096 case LookupResult::FoundUnresolvedValue: {
8097 // We found a using declaration that is a value. Most likely, the using
8098 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008099 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008100 IILoc);
8101 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8102 << Name << Ctx << FullRange;
8103 if (UnresolvedUsingValueDecl *Using
8104 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008105 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008106 Diag(Loc, diag::note_using_value_decl_missing_typename)
8107 << FixItHint::CreateInsertion(Loc, "typename ");
8108 }
8109 }
8110 // Fall through to create a dependent typename type, from which we can recover
8111 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008112
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008113 case LookupResult::NotFoundInCurrentInstantiation:
8114 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008115 return Context.getDependentNameType(Keyword,
8116 QualifierLoc.getNestedNameSpecifier(),
8117 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008118
8119 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008120 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008121 // We found a type. Build an ElaboratedType, since the
8122 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008123 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008124 return Context.getElaboratedType(ETK_Typename,
8125 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008126 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008127 }
8128
8129 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008130 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008131 break;
8132
8133 case LookupResult::FoundOverloaded:
8134 DiagID = diag::err_typename_nested_not_type;
8135 Referenced = *Result.begin();
8136 break;
8137
John McCall6538c932009-10-10 05:48:19 +00008138 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008139 return QualType();
8140 }
8141
8142 // If we get here, it's because name lookup did not find a
8143 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008144 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008145 IILoc);
8146 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008147 if (Referenced)
8148 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8149 << Name;
8150 return QualType();
8151}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008152
8153namespace {
8154 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008155 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008156 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008157 SourceLocation Loc;
8158 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008159
Douglas Gregor15acfb92009-08-06 16:20:37 +00008160 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008161 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008162
Mike Stump11289f42009-09-09 15:08:12 +00008163 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008164 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008165 DeclarationName Entity)
8166 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008167 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008168
8169 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008170 /// transformed.
8171 ///
8172 /// For the purposes of type reconstruction, a type has already been
8173 /// transformed if it is NULL or if it is not dependent.
8174 bool AlreadyTransformed(QualType T) {
8175 return T.isNull() || !T->isDependentType();
8176 }
Mike Stump11289f42009-09-09 15:08:12 +00008177
8178 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008179 /// rebuilt.
8180 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008181
Douglas Gregor15acfb92009-08-06 16:20:37 +00008182 /// \brief Returns the name of the entity whose type is being rebuilt.
8183 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008184
Douglas Gregoref6ab412009-10-27 06:26:26 +00008185 /// \brief Sets the "base" location and entity when that
8186 /// information is known based on another transformation.
8187 void setBase(SourceLocation Loc, DeclarationName Entity) {
8188 this->Loc = Loc;
8189 this->Entity = Entity;
8190 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008191
8192 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8193 // Lambdas never need to be transformed.
8194 return E;
8195 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008196 };
8197}
8198
Douglas Gregor15acfb92009-08-06 16:20:37 +00008199/// \brief Rebuilds a type within the context of the current instantiation.
8200///
Mike Stump11289f42009-09-09 15:08:12 +00008201/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008202/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008203/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008204/// partial specialization thereof). This routine will rebuild that type now
8205/// that we have entered the declarator's scope, which may produce different
8206/// canonical types, e.g.,
8207///
8208/// \code
8209/// template<typename T>
8210/// struct X {
8211/// typedef T* pointer;
8212/// pointer data();
8213/// };
8214///
8215/// template<typename T>
8216/// typename X<T>::pointer X<T>::data() { ... }
8217/// \endcode
8218///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008219/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008220/// since we do not know that we can look into X<T> when we parsed the type.
8221/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008222/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008223/// as the canonical type of T*, allowing the return types of the out-of-line
8224/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008225TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8226 SourceLocation Loc,
8227 DeclarationName Name) {
8228 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008229 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008230
Douglas Gregor15acfb92009-08-06 16:20:37 +00008231 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8232 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008233}
Douglas Gregorbe999392009-09-15 16:23:51 +00008234
John McCalldadc5752010-08-24 06:29:42 +00008235ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008236 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8237 DeclarationName());
8238 return Rebuilder.TransformExpr(E);
8239}
8240
John McCall99b2fe52010-04-29 23:50:39 +00008241bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008242 if (SS.isInvalid())
8243 return true;
John McCall2408e322010-04-27 00:57:59 +00008244
Douglas Gregor10176412011-02-25 16:07:42 +00008245 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008246 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8247 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008248 NestedNameSpecifierLoc Rebuilt
8249 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8250 if (!Rebuilt)
8251 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008252
Douglas Gregor10176412011-02-25 16:07:42 +00008253 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008254 return false;
John McCall2408e322010-04-27 00:57:59 +00008255}
8256
Douglas Gregor041b0842011-10-14 15:31:12 +00008257/// \brief Rebuild the template parameters now that we know we're in a current
8258/// instantiation.
8259bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8260 TemplateParameterList *Params) {
8261 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8262 Decl *Param = Params->getParam(I);
8263
8264 // There is nothing to rebuild in a type parameter.
8265 if (isa<TemplateTypeParmDecl>(Param))
8266 continue;
8267
8268 // Rebuild the template parameter list of a template template parameter.
8269 if (TemplateTemplateParmDecl *TTP
8270 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8271 if (RebuildTemplateParamsInCurrentInstantiation(
8272 TTP->getTemplateParameters()))
8273 return true;
8274
8275 continue;
8276 }
8277
8278 // Rebuild the type of a non-type template parameter.
8279 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8280 TypeSourceInfo *NewTSI
8281 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8282 NTTP->getLocation(),
8283 NTTP->getDeclName());
8284 if (!NewTSI)
8285 return true;
8286
8287 if (NewTSI != NTTP->getTypeSourceInfo()) {
8288 NTTP->setTypeSourceInfo(NewTSI);
8289 NTTP->setType(NewTSI->getType());
8290 }
8291 }
8292
8293 return false;
8294}
8295
Douglas Gregorbe999392009-09-15 16:23:51 +00008296/// \brief Produces a formatted string that describes the binding of
8297/// template parameters to template arguments.
8298std::string
8299Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8300 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008301 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008302}
8303
8304std::string
8305Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8306 const TemplateArgument *Args,
8307 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008308 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008309 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008310
Douglas Gregore62e6a02009-11-11 19:13:48 +00008311 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008312 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008313
Douglas Gregorbe999392009-09-15 16:23:51 +00008314 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008315 if (I >= NumArgs)
8316 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008317
Douglas Gregorbe999392009-09-15 16:23:51 +00008318 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008319 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008320 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008321 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322
Douglas Gregorbe999392009-09-15 16:23:51 +00008323 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008324 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008325 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008326 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008328
Douglas Gregor0192c232010-12-20 16:52:59 +00008329 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008330 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008331 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008332
8333 Out << ']';
8334 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008335}
Francois Pichet1c229c02011-04-22 22:18:13 +00008336
Richard Smithe40f2ba2013-08-07 21:41:30 +00008337void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8338 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008339 if (!FD)
8340 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008341
8342 LateParsedTemplate *LPT = new LateParsedTemplate;
8343
8344 // Take tokens to avoid allocations
8345 LPT->Toks.swap(Toks);
8346 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008347 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008348
8349 FD->setLateTemplateParsed(true);
8350}
8351
8352void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8353 if (!FD)
8354 return;
8355 FD->setLateTemplateParsed(false);
8356}
Francois Pichet1c229c02011-04-22 22:18:13 +00008357
8358bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8359 DeclContext *DC = CurContext;
8360
8361 while (DC) {
8362 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8363 const FunctionDecl *FD = RD->isLocalClass();
8364 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8365 } else if (DC->isTranslationUnit() || DC->isNamespace())
8366 return false;
8367
8368 DC = DC->getParent();
8369 }
8370 return false;
8371}