blob: d6ea3d0e2edf2ccf3a26fba72b8362f158288878 [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))
110 if (!ClassTemplates.insert(ClassTmpl)) {
111 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
321 CorrectionCandidateCallback FilterCCC;
322 FilterCCC.WantTypeSpecifiers = false;
323 FilterCCC.WantExpressionKeywords = false;
324 FilterCCC.WantRemainingKeywords = false;
325 FilterCCC.WantCXXNamedCasts = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000326 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
327 Found.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +0000328 FilterCCC, CTK_ErrorRecovery,
329 LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000330 Found.setLookupName(Corrected.getCorrection());
331 if (Corrected.getCorrectionDecl())
332 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000333 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000334 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000335 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000336 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
337 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000338 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000339 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
340 << Name << LookupCtx << DroppedSpecifier
341 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000342 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000343 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000344 }
John McCalle9cccd82010-06-16 08:42:20 +0000345 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000346 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000347 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000348 }
349 }
350
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000351 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000352 if (Found.empty()) {
353 if (isDependent)
354 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000355 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000356 }
John McCalle66edc12009-11-24 19:00:30 +0000357
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000358 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000359 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000360 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000361 // [...] If the lookup in the class of the object expression finds a
362 // template, the name is also looked up in the context of the entire
363 // postfix-expression and [...]
364 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000365 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000366 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
367 LookupOrdinaryName);
368 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000369 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000370
John McCalle66edc12009-11-24 19:00:30 +0000371 if (FoundOuter.empty()) {
372 // - if the name is not found, the name found in the class of the
373 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000374 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
375 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000376 // - if the name is found in the context of the entire
377 // postfix-expression and does not name a class template, the name
378 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000379 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000380 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000381 // - if the name found is a class template, it must refer to the same
382 // entity as the one found in the class of the object expression,
383 // otherwise the program is ill-formed.
384 if (!Found.isSingleResult() ||
385 Found.getFoundDecl()->getCanonicalDecl()
386 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000388 diag::ext_nested_name_member_ref_lookup_ambiguous)
389 << Found.getLookupName()
390 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000391 Diag(Found.getRepresentativeDecl()->getLocation(),
392 diag::note_ambig_member_ref_object_type)
393 << ObjectType;
394 Diag(FoundOuter.getFoundDecl()->getLocation(),
395 diag::note_ambig_member_ref_scope);
396
397 // Recover by taking the template that we found in the object
398 // expression's type.
399 }
400 }
401 }
402}
403
John McCallcd4b4772009-12-02 03:53:29 +0000404/// ActOnDependentIdExpression - Handle a dependent id-expression that
405/// was just parsed. This is only possible with an explicit scope
406/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000407ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000408Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000409 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000410 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000411 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000412 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000413 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000414
John McCallcd4b4772009-12-02 03:53:29 +0000415 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000416 isa<CXXMethodDecl>(DC) &&
417 cast<CXXMethodDecl>(DC)->isInstance()) {
418 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419
John McCalle66edc12009-11-24 19:00:30 +0000420 // Since the 'this' expression is synthesized, we don't need to
421 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000422 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000423
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000424 return CXXDependentScopeMemberExpr::Create(
425 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
426 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
427 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000428 }
429
Abramo Bagnara7945c982012-01-27 09:46:47 +0000430 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000431}
432
John McCalldadc5752010-08-24 06:29:42 +0000433ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000434Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000435 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000436 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000437 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000438 return DependentScopeDeclRefExpr::Create(
439 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
440 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000441}
442
Douglas Gregor5101c242008-12-05 18:15:24 +0000443/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
444/// that the template parameter 'PrevDecl' is being shadowed by a new
445/// declaration at location Loc. Returns true to indicate that this is
446/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000447void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000448 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000449
450 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000451 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000452 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000453
454 // C++ [temp.local]p4:
455 // A template-parameter shall not be redeclared within its
456 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000457 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000458 << cast<NamedDecl>(PrevDecl)->getDeclName();
459 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000460 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000461}
462
Douglas Gregor463421d2009-03-03 04:44:36 +0000463/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000464/// the parameter D to reference the templated declaration and return a pointer
465/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000466TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
467 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
468 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000469 return Temp;
470 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000471 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000472}
473
Douglas Gregoreb29d182011-01-05 17:40:24 +0000474ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
475 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000476 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000477 "Only template template arguments can be pack expansions here");
478 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
479 "Template template argument pack expansion without packs");
480 ParsedTemplateArgument Result(*this);
481 Result.EllipsisLoc = EllipsisLoc;
482 return Result;
483}
484
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000485static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
486 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000487
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000488 switch (Arg.getKind()) {
489 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000490 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000491 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000493 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000494 return TemplateArgumentLoc(TemplateArgument(T), DI);
495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000496
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000497 case ParsedTemplateArgument::NonType: {
498 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
499 return TemplateArgumentLoc(TemplateArgument(E), E);
500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000502 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000503 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000504 TemplateArgument TArg;
505 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000506 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000507 else
508 TArg = Template;
509 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000510 Arg.getScopeSpec().getWithLocInContext(
511 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000512 Arg.getLocation(),
513 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000514 }
515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000517 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000518}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000520/// \brief Translates template arguments as provided by the parser
521/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000522void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
523 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000524 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000525 TemplateArgs.addArgument(translateTemplateArgument(*this,
526 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000527}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000528
Richard Smithb80d5402013-06-25 22:21:36 +0000529static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
530 SourceLocation Loc,
531 IdentifierInfo *Name) {
532 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
533 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
534 if (PrevDecl && PrevDecl->isTemplateParameter())
535 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
536}
537
Douglas Gregor5101c242008-12-05 18:15:24 +0000538/// ActOnTypeParameter - Called when a C++ template type parameter
539/// (e.g., "typename T") has been parsed. Typename specifies whether
540/// the keyword "typename" was used to declare the type parameter
541/// (otherwise, "class" was used), and KeyLoc is the location of the
542/// "class" or "typename" keyword. ParamName is the name of the
543/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000544/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000545/// If the type parameter has a default argument, it will be added
546/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000547Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000548 SourceLocation EllipsisLoc,
549 SourceLocation KeyLoc,
550 IdentifierInfo *ParamName,
551 SourceLocation ParamNameLoc,
552 unsigned Depth, unsigned Position,
553 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000554 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000555 assert(S->isTemplateParamScope() &&
556 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000557 bool Invalid = false;
558
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000559 SourceLocation Loc = ParamNameLoc;
560 if (!ParamName)
561 Loc = KeyLoc;
562
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000563 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000564 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000565 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000566 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000567 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000568 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000569 if (Invalid)
570 Param->setInvalidDecl();
571
572 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000573 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
574
Douglas Gregor5101c242008-12-05 18:15:24 +0000575 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000576 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 IdResolver.AddDecl(Param);
578 }
579
Douglas Gregorf5500772011-01-05 15:48:55 +0000580 // C++0x [temp.param]p9:
581 // A default template-argument may be specified for any kind of
582 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000583 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000584 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
585 DefaultArg = ParsedType();
586 }
587
Douglas Gregordc13ded2010-07-01 00:00:45 +0000588 // Handle the default argument, if provided.
589 if (DefaultArg) {
590 TypeSourceInfo *DefaultTInfo;
591 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregordc13ded2010-07-01 00:00:45 +0000593 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000595 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000597 UPPC_DefaultArgument))
598 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Douglas Gregordc13ded2010-07-01 00:00:45 +0000600 // Check the template argument itself.
601 if (CheckTemplateArgument(Param, DefaultTInfo)) {
602 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000603 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregordc13ded2010-07-01 00:00:45 +0000606 Param->setDefaultArgument(DefaultTInfo, false);
607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
John McCall48871652010-08-21 09:40:31 +0000609 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000610}
611
Douglas Gregor463421d2009-03-03 04:44:36 +0000612/// \brief Check that the type of a non-type template parameter is
613/// well-formed.
614///
615/// \returns the (possibly-promoted) parameter type if valid;
616/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000617QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000618Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000619 // We don't allow variably-modified types as the type of non-type template
620 // parameters.
621 if (T->isVariablyModifiedType()) {
622 Diag(Loc, diag::err_variably_modified_nontype_template_param)
623 << T;
624 return QualType();
625 }
626
Douglas Gregor463421d2009-03-03 04:44:36 +0000627 // C++ [temp.param]p4:
628 //
629 // A non-type template-parameter shall have one of the following
630 // (optionally cv-qualified) types:
631 //
632 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000633 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000634 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000635 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000636 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000637 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000638 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000639 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000640 // -- std::nullptr_t.
641 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000642 // If T is a dependent type, we can't do the check now, so we
643 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000644 T->isDependentType()) {
645 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
646 // are ignored when determining its type.
647 return T.getUnqualifiedType();
648 }
649
Douglas Gregor463421d2009-03-03 04:44:36 +0000650 // C++ [temp.param]p8:
651 //
652 // A non-type template-parameter of type "array of T" or
653 // "function returning T" is adjusted to be of type "pointer to
654 // T" or "pointer to function returning T", respectively.
655 else if (T->isArrayType())
656 // FIXME: Keep the type prior to promotion?
657 return Context.getArrayDecayedType(T);
658 else if (T->isFunctionType())
659 // FIXME: Keep the type prior to promotion?
660 return Context.getPointerType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Douglas Gregor463421d2009-03-03 04:44:36 +0000662 Diag(Loc, diag::err_template_nontype_parm_bad_type)
663 << T;
664
665 return QualType();
666}
667
John McCall48871652010-08-21 09:40:31 +0000668Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
669 unsigned Depth,
670 unsigned Position,
671 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000672 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000673 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
674 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000675
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000676 assert(S->isTemplateParamScope() &&
677 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000678 bool Invalid = false;
679
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000680 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
681 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000682 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000683 Invalid = true;
684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Richard Smithb80d5402013-06-25 22:21:36 +0000686 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000687 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000688 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000689 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000690 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000691 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000693 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000694 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000695
Douglas Gregor5101c242008-12-05 18:15:24 +0000696 if (Invalid)
697 Param->setInvalidDecl();
698
Richard Smithb80d5402013-06-25 22:21:36 +0000699 if (ParamName) {
700 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
701 ParamName);
702
Douglas Gregor5101c242008-12-05 18:15:24 +0000703 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000704 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000705 IdResolver.AddDecl(Param);
706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707
Douglas Gregorf5500772011-01-05 15:48:55 +0000708 // C++0x [temp.param]p9:
709 // A default template-argument may be specified for any kind of
710 // template-parameter that is not a template parameter pack.
711 if (Default && IsParameterPack) {
712 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000713 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000714 }
715
Douglas Gregordc13ded2010-07-01 00:00:45 +0000716 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000717 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000718 // Check for unexpanded parameter packs.
719 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
720 return Param;
721
Douglas Gregordc13ded2010-07-01 00:00:45 +0000722 TemplateArgument Converted;
John Wiegley01296292011-04-08 18:41:53 +0000723 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
724 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000725 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000726 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000727 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000728 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000729
John McCallb268a282010-08-23 23:25:46 +0000730 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000731 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000732
John McCall48871652010-08-21 09:40:31 +0000733 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000734}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000735
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000736/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000737/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000738/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000739Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
740 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000741 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000742 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000743 IdentifierInfo *Name,
744 SourceLocation NameLoc,
745 unsigned Depth,
746 unsigned Position,
747 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000748 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000749 assert(S->isTemplateParamScope() &&
750 "Template template parameter not in template parameter scope!");
751
752 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000753 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000754 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000755 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000756 NameLoc.isInvalid()? TmpLoc : NameLoc,
757 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000758 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000759 Param->setAccess(AS_public);
760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000761 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000762 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000763 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000764 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
765
John McCall48871652010-08-21 09:40:31 +0000766 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000767 IdResolver.AddDecl(Param);
768 }
769
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000770 if (Params->size() == 0) {
771 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
772 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
773 Param->setInvalidDecl();
774 }
775
Douglas Gregorf5500772011-01-05 15:48:55 +0000776 // C++0x [temp.param]p9:
777 // A default template-argument may be specified for any kind of
778 // template-parameter that is not a template parameter pack.
779 if (IsParameterPack && !Default.isInvalid()) {
780 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
781 Default = ParsedTemplateArgument();
782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000783
Douglas Gregordc13ded2010-07-01 00:00:45 +0000784 if (!Default.isInvalid()) {
785 // Check only that we have a template template argument. We don't want to
786 // try to check well-formedness now, because our template template parameter
787 // might have dependent types in its template parameters, which we wouldn't
788 // be able to match now.
789 //
790 // If none of the template template parameter's template arguments mention
791 // other template parameters, we could actually perform more checking here.
792 // However, it isn't worth doing.
793 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
794 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
795 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
796 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000797 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000800 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000802 DefaultArg.getArgument().getAsTemplate(),
803 UPPC_DefaultArgument))
804 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregordc13ded2010-07-01 00:00:45 +0000806 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808
John McCall48871652010-08-21 09:40:31 +0000809 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000810}
811
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000812/// ActOnTemplateParameterList - Builds a TemplateParameterList that
813/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000814TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000815Sema::ActOnTemplateParameterList(unsigned Depth,
816 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000817 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000818 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000819 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000820 SourceLocation RAngleLoc) {
821 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000822 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000823
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000824 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825 (NamedDecl**)Params, NumParams,
Douglas Gregorbe999392009-09-15 16:23:51 +0000826 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000827}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000828
John McCall3e11ebe2010-03-15 10:12:16 +0000829static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
830 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000831 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000832}
833
John McCallfaf5fb42010-08-26 23:41:50 +0000834DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000835Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000836 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000837 IdentifierInfo *Name, SourceLocation NameLoc,
838 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000839 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000840 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000841 unsigned NumOuterTemplateParamLists,
842 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump11289f42009-09-09 15:08:12 +0000843 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000844 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000845 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000846 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000847
848 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000849 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000850 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000851
Abramo Bagnara6150c882010-05-11 21:36:43 +0000852 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
853 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000854
855 // There is no such thing as an unnamed class template.
856 if (!Name) {
857 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000858 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000859 }
860
Richard Smith6483d222012-04-21 01:27:54 +0000861 // Find any previous declaration with this name. For a friend with no
862 // scope explicitly specified, we only look for tag declarations (per
863 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000864 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000865 LookupResult Previous(*this, Name, NameLoc,
866 (SS.isEmpty() && TUK == TUK_Friend)
867 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000868 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000869 if (SS.isNotEmpty() && !SS.isInvalid()) {
870 SemanticContext = computeDeclContext(SS, true);
871 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000872 // FIXME: Horrible, horrible hack! We can't currently represent this
873 // in the AST, and historically we have just ignored such friend
874 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000875 Diag(NameLoc, TUK == TUK_Friend
876 ? diag::warn_template_qualified_friend_ignored
877 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000878 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000879 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000880 }
Mike Stump11289f42009-09-09 15:08:12 +0000881
John McCall0b66eb32010-05-01 00:40:08 +0000882 if (RequireCompleteDeclContext(SS, SemanticContext))
883 return true;
884
Douglas Gregor041b0842011-10-14 15:31:12 +0000885 // If we're adding a template to a dependent context, we may need to
886 // rebuilding some of the types used within the template parameter list,
887 // now that we know what the current instantiation is.
888 if (SemanticContext->isDependentContext()) {
889 ContextRAII SavedContext(*this, SemanticContext);
890 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
891 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000892 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
893 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000894
John McCall27b18f82009-11-17 02:14:36 +0000895 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000896 } else {
897 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000898 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000901 if (Previous.isAmbiguous())
902 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903
Craig Topperc3ec1492014-05-26 06:22:03 +0000904 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000905 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000906 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000907
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000908 // If there is a previous declaration with the same name, check
909 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000910 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000911 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000912
913 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000915 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000917 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
918 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000919 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000920 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
921 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
922 PrevClassTemplate
923 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
924 ->getSpecializedTemplate();
925 }
926 }
927
John McCalld43784f2009-12-18 11:25:59 +0000928 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000929 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000930 // [...] When looking for a prior declaration of a class or a function
931 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000932 // function is neither a qualified name nor a template-id, scopes outside
933 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000934 if (!SS.isSet()) {
935 DeclContext *OutermostContext = CurContext;
936 while (!OutermostContext->isFileContext())
937 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000938
Richard Smith61e582f2012-04-20 07:12:26 +0000939 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000940 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
941 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
942 SemanticContext = PrevDecl->getDeclContext();
943 } else {
944 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000946 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000947 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000948 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000949
950 // Check that the chosen semantic context doesn't already contain a
951 // declaration of this name as a non-tag type.
952 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
953 ForRedeclaration);
954 DeclContext *LookupContext = SemanticContext;
955 while (LookupContext->isTransparentContext())
956 LookupContext = LookupContext->getLookupParent();
957 LookupQualifiedName(Previous, LookupContext);
958
959 if (Previous.isAmbiguous())
960 return true;
961
962 if (Previous.begin() != Previous.end())
963 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000964 }
John McCall90d3bb92009-12-17 23:21:11 +0000965 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000966 } else if (PrevDecl &&
967 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000968 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000970 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000971 // Ensure that the template parameter lists are compatible. Skip this check
972 // for a friend in a dependent context: the template parameter list itself
973 // could be dependent.
974 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
975 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000976 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000977 /*Complain=*/true,
978 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000979 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000980
981 // C++ [temp.class]p4:
982 // In a redeclaration, partial specialization, explicit
983 // specialization or explicit instantiation of a class template,
984 // the class-key shall agree in kind with the original class
985 // template declaration (7.1.5.3).
986 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +0000987 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
988 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000989 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000990 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000991 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000992 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000993 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000994 }
995
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000996 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000997 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000998 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000999 Diag(NameLoc, diag::err_redefinition) << Name;
1000 Diag(Def->getLocation(), diag::note_previous_definition);
1001 // FIXME: Would it make sense to try to "forget" the previous
1002 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001003 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001004 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001005 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001006 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1007 // Maybe we will complain about the shadowed template parameter.
1008 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1009 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001010 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001011 } else if (PrevDecl) {
1012 // C++ [temp]p5:
1013 // A class template shall not have the same name as any other
1014 // template, class, function, object, enumeration, enumerator,
1015 // namespace, or type in the same scope (3.3), except as specified
1016 // in (14.5.4).
1017 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1018 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001019 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001020 }
1021
Douglas Gregordba32632009-02-10 19:49:53 +00001022 // Check the template parameter list of this declaration, possibly
1023 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001024 // template declaration. Skip this check for a friend in a dependent
1025 // context, because the template parameter list might be dependent.
1026 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001027 CheckTemplateParameterList(
1028 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001029 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1030 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001031 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1032 SemanticContext->isDependentContext())
1033 ? TPC_ClassTemplateMember
1034 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1035 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001036 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001037
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001038 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001039 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001040 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001041 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1042 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001043 : diag::err_member_decl_does_not_match)
1044 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001045 Invalid = true;
1046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047 }
1048
Mike Stump11289f42009-09-09 15:08:12 +00001049 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001050 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001051 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001052 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001053 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001054 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001055 if (NumOuterTemplateParamLists > 0)
1056 NewClass->setTemplateParameterListsInfo(Context,
1057 NumOuterTemplateParamLists,
1058 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001059
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001060 // Add alignment attributes if necessary; these attributes are checked when
1061 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001062 if (TUK == TUK_Definition) {
1063 AddAlignmentAttributesForRecord(NewClass);
1064 AddMsStructLayoutForRecord(NewClass);
1065 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001066
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001067 ClassTemplateDecl *NewTemplate
1068 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1069 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001070 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001071 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001072
Douglas Gregor21823bf2011-12-20 18:11:52 +00001073 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001074 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001075
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001076 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001077 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001078 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001079 assert(T->isDependentType() && "Class template type is not dependent?");
1080 (void)T;
1081
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001082 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001083 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001085 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1086 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087
Anders Carlsson137108d2009-03-26 01:24:28 +00001088 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001089 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001090 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001091
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001092 // Set the lexical context of these templates
1093 NewClass->setLexicalDeclContext(CurContext);
1094 NewTemplate->setLexicalDeclContext(CurContext);
1095
John McCall9bb74a52009-07-31 02:45:11 +00001096 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001097 NewClass->startDefinition();
1098
1099 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001100 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001101
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001102 if (PrevClassTemplate)
1103 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1104
Rafael Espindola385c0422012-07-13 18:04:45 +00001105 AddPushedVisibilityAttribute(NewClass);
1106
John McCall27b5c252009-09-14 21:59:20 +00001107 if (TUK != TUK_Friend)
1108 PushOnScopeChains(NewTemplate, S);
1109 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001110 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001111 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001112 NewClass->setAccess(PrevClassTemplate->getAccess());
1113 }
John McCall27b5c252009-09-14 21:59:20 +00001114
Richard Smith64017682013-07-17 23:53:16 +00001115 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116
John McCall27b5c252009-09-14 21:59:20 +00001117 // Friend templates are visible in fairly strange ways.
1118 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001119 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001120 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001121 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1122 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125
Douglas Gregor3dad8422009-09-26 06:47:28 +00001126 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1127 NewClass->getLocation(),
1128 NewTemplate,
1129 /*FIXME:*/NewClass->getLocation());
1130 Friend->setAccess(AS_public);
1131 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001132 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001133
Douglas Gregordba32632009-02-10 19:49:53 +00001134 if (Invalid) {
1135 NewTemplate->setInvalidDecl();
1136 NewClass->setInvalidDecl();
1137 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001138
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001139 ActOnDocumentableDecl(NewTemplate);
1140
John McCall48871652010-08-21 09:40:31 +00001141 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001142}
1143
Douglas Gregored5731f2009-11-25 17:50:39 +00001144/// \brief Diagnose the presence of a default template argument on a
1145/// template parameter, which is ill-formed in certain contexts.
1146///
1147/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001149 Sema::TemplateParamListContext TPC,
1150 SourceLocation ParamLoc,
1151 SourceRange DefArgRange) {
1152 switch (TPC) {
1153 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001154 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001155 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001156 return false;
1157
1158 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001159 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001160 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001161 // A default template-argument shall not be specified in a
1162 // function template declaration or a function template
1163 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001164 // If a friend function template declaration specifies a default
1165 // template-argument, that declaration shall be a definition and shall be
1166 // the only declaration of the function template in the translation unit.
1167 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001168 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001169 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1170 : diag::ext_template_parameter_default_in_function_template)
1171 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001172 return false;
1173
1174 case Sema::TPC_ClassTemplateMember:
1175 // C++0x [temp.param]p9:
1176 // A default template-argument shall not be specified in the
1177 // template-parameter-lists of the definition of a member of a
1178 // class template that appears outside of the member's class.
1179 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1180 << DefArgRange;
1181 return true;
1182
David Majnemerba8f17a2013-06-25 22:08:55 +00001183 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001184 case Sema::TPC_FriendFunctionTemplate:
1185 // C++ [temp.param]p9:
1186 // A default template-argument shall not be specified in a
1187 // friend template declaration.
1188 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1189 << DefArgRange;
1190 return true;
1191
1192 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1193 // for friend function templates if there is only a single
1194 // declaration (and it is a definition). Strange!
1195 }
1196
David Blaikie8a40f702012-01-17 06:56:22 +00001197 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001198}
1199
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001200/// \brief Check for unexpanded parameter packs within the template parameters
1201/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001202static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1203 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001204 // A template template parameter which is a parameter pack is also a pack
1205 // expansion.
1206 if (TTP->isParameterPack())
1207 return false;
1208
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001209 TemplateParameterList *Params = TTP->getTemplateParameters();
1210 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1211 NamedDecl *P = Params->getParam(I);
1212 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001213 if (!NTTP->isParameterPack() &&
1214 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001215 NTTP->getTypeSourceInfo(),
1216 Sema::UPPC_NonTypeTemplateParameterType))
1217 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001219 continue;
1220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221
1222 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001223 = dyn_cast<TemplateTemplateParmDecl>(P))
1224 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1225 return true;
1226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001228 return false;
1229}
1230
Douglas Gregordba32632009-02-10 19:49:53 +00001231/// \brief Checks the validity of a template parameter list, possibly
1232/// considering the template parameter list from a previous
1233/// declaration.
1234///
1235/// If an "old" template parameter list is provided, it must be
1236/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1237/// template parameter list.
1238///
1239/// \param NewParams Template parameter list for a new template
1240/// declaration. This template parameter list will be updated with any
1241/// default arguments that are carried through from the previous
1242/// template parameter list.
1243///
1244/// \param OldParams If provided, template parameter list from a
1245/// previous declaration of the same template. Default template
1246/// arguments will be merged from the old template parameter list to
1247/// the new template parameter list.
1248///
Douglas Gregored5731f2009-11-25 17:50:39 +00001249/// \param TPC Describes the context in which we are checking the given
1250/// template parameter list.
1251///
Douglas Gregordba32632009-02-10 19:49:53 +00001252/// \returns true if an error occurred, false otherwise.
1253bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001254 TemplateParameterList *OldParams,
1255 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001256 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001257
Douglas Gregordba32632009-02-10 19:49:53 +00001258 // C++ [temp.param]p10:
1259 // The set of default template-arguments available for use with a
1260 // template declaration or definition is obtained by merging the
1261 // default arguments from the definition (if in scope) and all
1262 // declarations in scope in the same way default function
1263 // arguments are (8.3.6).
1264 bool SawDefaultArgument = false;
1265 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001266
Mike Stumpc89c8e32009-02-11 23:03:27 +00001267 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001268 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001269 if (OldParams)
1270 OldParam = OldParams->begin();
1271
Douglas Gregor0693def2011-01-27 01:40:17 +00001272 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001273 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1274 NewParamEnd = NewParams->end();
1275 NewParam != NewParamEnd; ++NewParam) {
1276 // Variables used to diagnose redundant default arguments
1277 bool RedundantDefaultArg = false;
1278 SourceLocation OldDefaultLoc;
1279 SourceLocation NewDefaultLoc;
1280
David Blaikie651c73c2011-10-19 05:19:50 +00001281 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001282 bool MissingDefaultArg = false;
1283
David Blaikie651c73c2011-10-19 05:19:50 +00001284 // Variable used to diagnose non-final parameter packs
1285 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001286
Douglas Gregordba32632009-02-10 19:49:53 +00001287 if (TemplateTypeParmDecl *NewTypeParm
1288 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001289 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001290 if (NewTypeParm->hasDefaultArgument() &&
1291 DiagnoseDefaultTemplateArgument(*this, TPC,
1292 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001293 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001294 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001295 NewTypeParm->removeDefaultArgument();
1296
1297 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001298 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001299 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001300
Anders Carlsson327865d2009-06-12 23:20:15 +00001301 if (NewTypeParm->isParameterPack()) {
1302 assert(!NewTypeParm->hasDefaultArgument() &&
1303 "Parameter packs can't have a default argument!");
1304 SawParameterPack = true;
Mike Stump11289f42009-09-09 15:08:12 +00001305 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001306 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001307 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1308 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1309 SawDefaultArgument = true;
1310 RedundantDefaultArg = true;
1311 PreviousDefaultArgLoc = NewDefaultLoc;
1312 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1313 // Merge the default argument from the old declaration to the
1314 // new declaration.
John McCall0ad16662009-10-29 08:12:44 +00001315 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001316 true);
1317 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1318 } else if (NewTypeParm->hasDefaultArgument()) {
1319 SawDefaultArgument = true;
1320 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1321 } else if (SawDefaultArgument)
1322 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001323 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001324 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001325 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001326 if (!NewNonTypeParm->isParameterPack() &&
1327 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001329 UPPC_NonTypeTemplateParameterType)) {
1330 Invalid = true;
1331 continue;
1332 }
1333
Douglas Gregored5731f2009-11-25 17:50:39 +00001334 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335 if (NewNonTypeParm->hasDefaultArgument() &&
1336 DiagnoseDefaultTemplateArgument(*this, TPC,
1337 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001338 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001339 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001340 }
1341
Mike Stump12b8ce12009-08-04 21:02:39 +00001342 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001343 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001344 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001345 if (NewNonTypeParm->isParameterPack()) {
1346 assert(!NewNonTypeParm->hasDefaultArgument() &&
1347 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001348 if (!NewNonTypeParm->isPackExpansion())
1349 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001350 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Richard Smith35828f12013-07-22 03:31:14 +00001351 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001352 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1353 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1354 SawDefaultArgument = true;
1355 RedundantDefaultArg = true;
1356 PreviousDefaultArgLoc = NewDefaultLoc;
1357 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1358 // Merge the default argument from the old declaration to the
1359 // new declaration.
Douglas Gregordba32632009-02-10 19:49:53 +00001360 // FIXME: We need to create a new kind of "default argument"
Douglas Gregorf5500772011-01-05 15:48:55 +00001361 // expression that points to a previous non-type template
Douglas Gregordba32632009-02-10 19:49:53 +00001362 // parameter.
1363 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001364 OldNonTypeParm->getDefaultArgument(),
1365 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001366 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1367 } else if (NewNonTypeParm->hasDefaultArgument()) {
1368 SawDefaultArgument = true;
1369 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1370 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001371 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001372 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001373 TemplateTemplateParmDecl *NewTemplateParm
1374 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001375
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001376 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001377 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001378 Invalid = true;
1379 continue;
1380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381
David Blaikie651c73c2011-10-19 05:19:50 +00001382 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383 if (NewTemplateParm->hasDefaultArgument() &&
1384 DiagnoseDefaultTemplateArgument(*this, TPC,
1385 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001386 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001387 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001388
1389 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001390 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001391 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001392 if (NewTemplateParm->isParameterPack()) {
1393 assert(!NewTemplateParm->hasDefaultArgument() &&
1394 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001395 if (!NewTemplateParm->isPackExpansion())
1396 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001397 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001398 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001399 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1400 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001401 SawDefaultArgument = true;
1402 RedundantDefaultArg = true;
1403 PreviousDefaultArgLoc = NewDefaultLoc;
1404 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1405 // Merge the default argument from the old declaration to the
1406 // new declaration.
Mike Stump87c57ac2009-05-16 07:39:55 +00001407 // FIXME: We need to create a new kind of "default argument" expression
1408 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001409 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001410 OldTemplateParm->getDefaultArgument(),
1411 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001412 PreviousDefaultArgLoc
1413 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001414 } else if (NewTemplateParm->hasDefaultArgument()) {
1415 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001416 PreviousDefaultArgLoc
1417 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001418 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001419 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001420 }
1421
Richard Smith1fde8ec2012-09-07 02:06:42 +00001422 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001423 // If a template parameter of a primary class template or alias template
1424 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001425 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001426 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1427 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001428 Diag((*NewParam)->getLocation(),
1429 diag::err_template_param_pack_must_be_last_template_parameter);
1430 Invalid = true;
1431 }
1432
Douglas Gregordba32632009-02-10 19:49:53 +00001433 if (RedundantDefaultArg) {
1434 // C++ [temp.param]p12:
1435 // A template-parameter shall not be given default arguments
1436 // by two different declarations in the same scope.
1437 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1438 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1439 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001440 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001441 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001442 // If a template-parameter of a class template has a default
1443 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001444 // have a default template-argument supplied or be a template parameter
1445 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001446 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001447 diag::err_template_param_default_arg_missing);
1448 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1449 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001450 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001451 }
1452
1453 // If we have an old template parameter list that we're merging
1454 // in, move on to the next parameter.
1455 if (OldParams)
1456 ++OldParam;
1457 }
1458
Douglas Gregor0693def2011-01-27 01:40:17 +00001459 // We were missing some default arguments at the end of the list, so remove
1460 // all of the default arguments.
1461 if (RemoveDefaultArguments) {
1462 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1463 NewParamEnd = NewParams->end();
1464 NewParam != NewParamEnd; ++NewParam) {
1465 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1466 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001468 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1469 NTTP->removeDefaultArgument();
1470 else
1471 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1472 }
1473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474
Douglas Gregordba32632009-02-10 19:49:53 +00001475 return Invalid;
1476}
Douglas Gregord32e0282009-02-09 23:23:08 +00001477
John McCalla020a012010-10-20 05:44:58 +00001478namespace {
1479
1480/// A class which looks for a use of a certain level of template
1481/// parameter.
1482struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1483 typedef RecursiveASTVisitor<DependencyChecker> super;
1484
1485 unsigned Depth;
1486 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001487 SourceLocation MatchLoc;
1488
1489 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001490
1491 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1492 NamedDecl *ND = Params->getParam(0);
1493 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1494 Depth = PD->getDepth();
1495 } else if (NonTypeTemplateParmDecl *PD =
1496 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1497 Depth = PD->getDepth();
1498 } else {
1499 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1500 }
1501 }
1502
Richard Smith6056d5e2014-02-09 00:54:43 +00001503 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001504 if (ParmDepth >= Depth) {
1505 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001506 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001507 return true;
1508 }
1509 return false;
1510 }
1511
Richard Smith6056d5e2014-02-09 00:54:43 +00001512 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1513 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1514 }
1515
John McCalla020a012010-10-20 05:44:58 +00001516 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1517 return !Matches(T->getDepth());
1518 }
1519
1520 bool TraverseTemplateName(TemplateName N) {
1521 if (TemplateTemplateParmDecl *PD =
1522 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001523 if (Matches(PD->getDepth()))
1524 return false;
John McCalla020a012010-10-20 05:44:58 +00001525 return super::TraverseTemplateName(N);
1526 }
1527
1528 bool VisitDeclRefExpr(DeclRefExpr *E) {
1529 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001530 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1531 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001532 return false;
John McCalla020a012010-10-20 05:44:58 +00001533 return super::VisitDeclRefExpr(E);
1534 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001535
1536 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1537 return TraverseType(T->getReplacementType());
1538 }
1539
1540 bool
1541 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1542 return TraverseTemplateArgument(T->getArgumentPack());
1543 }
1544
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001545 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1546 return TraverseType(T->getInjectedSpecializationType());
1547 }
John McCalla020a012010-10-20 05:44:58 +00001548};
1549}
1550
Douglas Gregor972fe532011-05-10 18:27:06 +00001551/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001552/// list.
1553static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001554DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001555 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001556 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001557 return Checker.Match;
1558}
1559
Douglas Gregor972fe532011-05-10 18:27:06 +00001560// Find the source range corresponding to the named type in the given
1561// nested-name-specifier, if any.
1562static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1563 QualType T,
1564 const CXXScopeSpec &SS) {
1565 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1566 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1567 if (const Type *CurType = NNS->getAsType()) {
1568 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1569 return NNSLoc.getTypeLoc().getSourceRange();
1570 } else
1571 break;
1572
1573 NNSLoc = NNSLoc.getPrefix();
1574 }
1575
1576 return SourceRange();
1577}
1578
Mike Stump11289f42009-09-09 15:08:12 +00001579/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001580/// specifier, returning the template parameter list that applies to the
1581/// name.
1582///
1583/// \param DeclStartLoc the start of the declaration that has a scope
1584/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001585///
Douglas Gregor972fe532011-05-10 18:27:06 +00001586/// \param DeclLoc The location of the declaration itself.
1587///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001588/// \param SS the scope specifier that will be matched to the given template
1589/// parameter lists. This scope specifier precedes a qualified name that is
1590/// being declared.
1591///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001592/// \param TemplateId The template-id following the scope specifier, if there
1593/// is one. Used to check for a missing 'template<>'.
1594///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001595/// \param ParamLists the template parameter lists, from the outermost to the
1596/// innermost template parameter lists.
1597///
John McCalle820e5e2010-04-13 20:37:33 +00001598/// \param IsFriend Whether to apply the slightly different rules for
1599/// matching template parameters to scope specifiers in friend
1600/// declarations.
1601///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001602/// \param IsExplicitSpecialization will be set true if the entity being
1603/// declared is an explicit specialization, false otherwise.
1604///
Mike Stump11289f42009-09-09 15:08:12 +00001605/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001606/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001607/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001608/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001609/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001610/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001611TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1612 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001613 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001614 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1615 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001616 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001617 Invalid = false;
1618
1619 // The sequence of nested types to which we will match up the template
1620 // parameter lists. We first build this list by starting with the type named
1621 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001622 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001623 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001624 if (SS.getScopeRep()) {
1625 if (CXXRecordDecl *Record
1626 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1627 T = Context.getTypeDeclType(Record);
1628 else
1629 T = QualType(SS.getScopeRep()->getAsType(), 0);
1630 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001631
1632 // If we found an explicit specialization that prevents us from needing
1633 // 'template<>' headers, this will be set to the location of that
1634 // explicit specialization.
1635 SourceLocation ExplicitSpecLoc;
1636
1637 while (!T.isNull()) {
1638 NestedTypes.push_back(T);
1639
1640 // Retrieve the parent of a record type.
1641 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1642 // If this type is an explicit specialization, we're done.
1643 if (ClassTemplateSpecializationDecl *Spec
1644 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1645 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1646 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1647 ExplicitSpecLoc = Spec->getLocation();
1648 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001649 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001650 } else if (Record->getTemplateSpecializationKind()
1651 == TSK_ExplicitSpecialization) {
1652 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001653 break;
1654 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001655
1656 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1657 T = Context.getTypeDeclType(Parent);
1658 else
1659 T = QualType();
1660 continue;
1661 }
1662
1663 if (const TemplateSpecializationType *TST
1664 = T->getAs<TemplateSpecializationType>()) {
1665 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1666 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1667 T = Context.getTypeDeclType(Parent);
1668 else
1669 T = QualType();
1670 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001671 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001672 }
1673
1674 // Look one step prior in a dependent template specialization type.
1675 if (const DependentTemplateSpecializationType *DependentTST
1676 = T->getAs<DependentTemplateSpecializationType>()) {
1677 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1678 T = QualType(NNS->getAsType(), 0);
1679 else
1680 T = QualType();
1681 continue;
1682 }
1683
1684 // Look one step prior in a dependent name type.
1685 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1686 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1687 T = QualType(NNS->getAsType(), 0);
1688 else
1689 T = QualType();
1690 continue;
1691 }
1692
1693 // Retrieve the parent of an enumeration type.
1694 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1695 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1696 // check here.
1697 EnumDecl *Enum = EnumT->getDecl();
1698
1699 // Get to the parent type.
1700 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1701 T = Context.getTypeDeclType(Parent);
1702 else
1703 T = QualType();
1704 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregor972fe532011-05-10 18:27:06 +00001707 T = QualType();
1708 }
1709 // Reverse the nested types list, since we want to traverse from the outermost
1710 // to the innermost while checking template-parameter-lists.
1711 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001712
Douglas Gregor972fe532011-05-10 18:27:06 +00001713 // C++0x [temp.expl.spec]p17:
1714 // A member or a member template may be nested within many
1715 // enclosing class templates. In an explicit specialization for
1716 // such a member, the member declaration shall be preceded by a
1717 // template<> for each enclosing class template that is
1718 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001719 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001720
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001721 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001722 if (SawNonEmptyTemplateParameterList) {
1723 Diag(DeclLoc, diag::err_specialize_member_of_template)
1724 << !Recovery << Range;
1725 Invalid = true;
1726 IsExplicitSpecialization = false;
1727 return true;
1728 }
1729
1730 return false;
1731 };
1732
1733 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1734 // Check that we can have an explicit specialization here.
1735 if (CheckExplicitSpecialization(Range, true))
1736 return true;
1737
1738 // We don't have a template header, but we should.
1739 SourceLocation ExpectedTemplateLoc;
1740 if (!ParamLists.empty())
1741 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1742 else
1743 ExpectedTemplateLoc = DeclStartLoc;
1744
1745 Diag(DeclLoc, diag::err_template_spec_needs_header)
1746 << Range
1747 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1748 return false;
1749 };
1750
Douglas Gregor972fe532011-05-10 18:27:06 +00001751 unsigned ParamIdx = 0;
1752 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1753 ++TypeIdx) {
1754 T = NestedTypes[TypeIdx];
1755
1756 // Whether we expect a 'template<>' header.
1757 bool NeedEmptyTemplateHeader = false;
1758
1759 // Whether we expect a template header with parameters.
1760 bool NeedNonemptyTemplateHeader = false;
1761
1762 // For a dependent type, the set of template parameters that we
1763 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001764 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001765
Douglas Gregor373af9b2011-05-11 23:26:17 +00001766 // C++0x [temp.expl.spec]p15:
1767 // A member or a member template may be nested within many enclosing
1768 // class templates. In an explicit specialization for such a member, the
1769 // member declaration shall be preceded by a template<> for each
1770 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001771 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1772 if (ClassTemplatePartialSpecializationDecl *Partial
1773 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1774 ExpectedTemplateParams = Partial->getTemplateParameters();
1775 NeedNonemptyTemplateHeader = true;
1776 } else if (Record->isDependentType()) {
1777 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001778 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001779 ->getTemplateParameters();
1780 NeedNonemptyTemplateHeader = true;
1781 }
1782 } else if (ClassTemplateSpecializationDecl *Spec
1783 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1784 // C++0x [temp.expl.spec]p4:
1785 // Members of an explicitly specialized class template are defined
1786 // in the same manner as members of normal classes, and not using
1787 // the template<> syntax.
1788 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1789 NeedEmptyTemplateHeader = true;
1790 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001791 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001792 } else if (Record->getTemplateSpecializationKind()) {
1793 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001794 != TSK_ExplicitSpecialization &&
1795 TypeIdx == NumTypes - 1)
1796 IsExplicitSpecialization = true;
1797
1798 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001799 }
1800 } else if (const TemplateSpecializationType *TST
1801 = T->getAs<TemplateSpecializationType>()) {
1802 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1803 ExpectedTemplateParams = Template->getTemplateParameters();
1804 NeedNonemptyTemplateHeader = true;
1805 }
1806 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1807 // FIXME: We actually could/should check the template arguments here
1808 // against the corresponding template parameter list.
1809 NeedNonemptyTemplateHeader = false;
1810 }
1811
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001812 // C++ [temp.expl.spec]p16:
1813 // In an explicit specialization declaration for a member of a class
1814 // template or a member template that ap- pears in namespace scope, the
1815 // member template and some of its enclosing class templates may remain
1816 // unspecialized, except that the declaration shall not explicitly
1817 // specialize a class member template if its en- closing class templates
1818 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001819 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001820 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001821 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1822 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001823 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001824 } else
1825 SawNonEmptyTemplateParameterList = true;
1826 }
1827
Douglas Gregor972fe532011-05-10 18:27:06 +00001828 if (NeedEmptyTemplateHeader) {
1829 // If we're on the last of the types, and we need a 'template<>' header
1830 // here, then it's an explicit specialization.
1831 if (TypeIdx == NumTypes - 1)
1832 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001833
1834 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001835 if (ParamLists[ParamIdx]->size() > 0) {
1836 // The header has template parameters when it shouldn't. Complain.
1837 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1838 diag::err_template_param_list_matches_nontemplate)
1839 << T
1840 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1841 ParamLists[ParamIdx]->getRAngleLoc())
1842 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1843 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001844 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001845 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001846
Douglas Gregor972fe532011-05-10 18:27:06 +00001847 // Consume this template header.
1848 ++ParamIdx;
1849 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001850 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001851
1852 if (!IsFriend)
1853 if (DiagnoseMissingExplicitSpecialization(
1854 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001855 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001856
Douglas Gregor972fe532011-05-10 18:27:06 +00001857 continue;
1858 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001859
Douglas Gregor972fe532011-05-10 18:27:06 +00001860 if (NeedNonemptyTemplateHeader) {
1861 // In friend declarations we can have template-ids which don't
1862 // depend on the corresponding template parameter lists. But
1863 // assume that empty parameter lists are supposed to match this
1864 // template-id.
1865 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001866 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001867 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001868 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001869 else
1870 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001871 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001872
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001873 if (ParamIdx < ParamLists.size()) {
1874 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001875 if (ExpectedTemplateParams &&
1876 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1877 ExpectedTemplateParams,
1878 true, TPL_TemplateMatch))
1879 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001880
Douglas Gregor972fe532011-05-10 18:27:06 +00001881 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001882 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001883 TPC_ClassTemplateMember))
1884 Invalid = true;
1885
1886 ++ParamIdx;
1887 continue;
1888 }
1889
1890 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1891 << T
1892 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1893 Invalid = true;
1894 continue;
1895 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001896 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001897
Douglas Gregord8d297c2009-07-21 23:53:31 +00001898 // If there were at least as many template-ids as there were template
1899 // parameter lists, then there are no template parameter lists remaining for
1900 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001901 if (ParamIdx >= ParamLists.size()) {
1902 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001903 // We don't have a template header for the declaration itself, but we
1904 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001905 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001906 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1907 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001908
1909 // Fabricate an empty template parameter list for the invented header.
1910 return TemplateParameterList::Create(Context, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001911 SourceLocation(), nullptr, 0,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001912 SourceLocation());
1913 }
1914
Craig Topperc3ec1492014-05-26 06:22:03 +00001915 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001916 }
Mike Stump11289f42009-09-09 15:08:12 +00001917
Douglas Gregord8d297c2009-07-21 23:53:31 +00001918 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001919 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001920 bool HasAnyExplicitSpecHeader = false;
1921 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001922 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001923 if (ParamLists[I]->size() == 0)
1924 HasAnyExplicitSpecHeader = true;
1925 else
1926 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001927 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001928
Douglas Gregor972fe532011-05-10 18:27:06 +00001929 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001930 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1931 : diag::err_template_spec_extra_headers)
1932 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1933 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001934
1935 // If there was a specialization somewhere, such that 'template<>' is
1936 // not required, and there were any 'template<>' headers, note where the
1937 // specialization occurred.
1938 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1939 Diag(ExplicitSpecLoc,
1940 diag::note_explicit_template_spec_does_not_need_header)
1941 << NestedTypes.back();
1942
1943 // We have a template parameter list with no corresponding scope, which
1944 // means that the resulting template declaration can't be instantiated
1945 // properly (we'll end up with dependent nodes when we shouldn't).
1946 if (!AllExplicitSpecHeaders)
1947 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001948 }
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001950 // C++ [temp.expl.spec]p16:
1951 // In an explicit specialization declaration for a member of a class
1952 // template or a member template that ap- pears in namespace scope, the
1953 // member template and some of its enclosing class templates may remain
1954 // unspecialized, except that the declaration shall not explicitly
1955 // specialize a class member template if its en- closing class templates
1956 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001957 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001958 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1959 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001960 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001961
Douglas Gregord8d297c2009-07-21 23:53:31 +00001962 // Return the last template parameter list, which corresponds to the
1963 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001964 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001965}
1966
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001967void Sema::NoteAllFoundTemplates(TemplateName Name) {
1968 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1969 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001970 << (isa<FunctionTemplateDecl>(Template)
1971 ? 0
1972 : isa<ClassTemplateDecl>(Template)
1973 ? 1
1974 : isa<VarTemplateDecl>(Template)
1975 ? 2
1976 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1977 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001978 return;
1979 }
1980
1981 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1982 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1983 IEnd = OST->end();
1984 I != IEnd; ++I)
1985 Diag((*I)->getLocation(), diag::note_template_declared_here)
1986 << 0 << (*I)->getDeclName();
1987
1988 return;
1989 }
1990}
1991
Douglas Gregordc572a32009-03-30 22:58:21 +00001992QualType Sema::CheckTemplateIdType(TemplateName Name,
1993 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00001994 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00001995 DependentTemplateName *DTN
1996 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001997 if (DTN && DTN->isIdentifier())
1998 // When building a template-id where the template-name is dependent,
1999 // assume the template is a type template. Either our assumption is
2000 // correct, or the code is ill-formed and will be diagnosed when the
2001 // dependent name is substituted.
2002 return Context.getDependentTemplateSpecializationType(ETK_None,
2003 DTN->getQualifier(),
2004 DTN->getIdentifier(),
2005 TemplateArgs);
2006
Douglas Gregordc572a32009-03-30 22:58:21 +00002007 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002008 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2009 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002010 // We might have a substituted template template parameter pack. If so,
2011 // build a template specialization type for it.
2012 if (Name.getAsSubstTemplateTemplateParmPack())
2013 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002014
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002015 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2016 << Name;
2017 NoteAllFoundTemplates(Name);
2018 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002019 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002020
Douglas Gregorc40290e2009-03-09 23:48:35 +00002021 // Check that the template argument list is well-formed for this
2022 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002023 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002024 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002025 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002026 return QualType();
2027
Douglas Gregorc40290e2009-03-09 23:48:35 +00002028 QualType CanonType;
2029
Douglas Gregor678d76c2011-07-01 01:22:09 +00002030 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002031 if (TypeAliasTemplateDecl *AliasTemplate =
2032 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002033 // Find the canonical type for this type alias template specialization.
2034 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2035 if (Pattern->isInvalidDecl())
2036 return QualType();
2037
2038 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2039 Converted.data(), Converted.size());
2040
2041 // Only substitute for the innermost template argument list.
2042 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002043 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002044 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2045 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002046 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002047
Richard Smith802c4b72012-08-23 06:16:52 +00002048 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002049 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002050 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002051 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002052
Richard Smith3f1b5d02011-05-05 21:57:07 +00002053 CanonType = SubstType(Pattern->getUnderlyingType(),
2054 TemplateArgLists, AliasTemplate->getLocation(),
2055 AliasTemplate->getDeclName());
2056 if (CanonType.isNull())
2057 return QualType();
2058 } else if (Name.isDependent() ||
2059 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002060 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002061 // This class template specialization is a dependent
2062 // type. Therefore, its canonical type is another class template
2063 // specialization type that contains all of the converted
2064 // arguments in canonical form. This ensures that, e.g., A<T> and
2065 // A<T, T> have identical types when A is declared as:
2066 //
2067 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002068 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002069 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002070 Converted.data(),
2071 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregora8e02e72009-07-28 23:00:59 +00002073 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002074 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002075 // In the future, we need to teach getTemplateSpecializationType to only
2076 // build the canonical type and return that to us.
2077 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002078
2079 // This might work out to be a current instantiation, in which
2080 // case the canonical type needs to be the InjectedClassNameType.
2081 //
2082 // TODO: in theory this could be a simple hashtable lookup; most
2083 // changes to CurContext don't change the set of current
2084 // instantiations.
2085 if (isa<ClassTemplateDecl>(Template)) {
2086 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2087 // If we get out to a namespace, we're done.
2088 if (Ctx->isFileContext()) break;
2089
2090 // If this isn't a record, keep looking.
2091 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2092 if (!Record) continue;
2093
2094 // Look for one of the two cases with InjectedClassNameTypes
2095 // and check whether it's the same template.
2096 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2097 !Record->getDescribedClassTemplate())
2098 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002099
John McCall2408e322010-04-27 00:57:59 +00002100 // Fetch the injected class name type and check whether its
2101 // injected type is equal to the type we just built.
2102 QualType ICNT = Context.getTypeDeclType(Record);
2103 QualType Injected = cast<InjectedClassNameType>(ICNT)
2104 ->getInjectedSpecializationType();
2105
2106 if (CanonType != Injected->getCanonicalTypeInternal())
2107 continue;
2108
2109 // If so, the canonical type of this TST is the injected
2110 // class name type of the record we just found.
2111 assert(ICNT.isCanonical());
2112 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002113 break;
2114 }
2115 }
Mike Stump11289f42009-09-09 15:08:12 +00002116 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002117 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002118 // Find the class template specialization declaration that
2119 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002120 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002121 ClassTemplateSpecializationDecl *Decl
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002123 InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002124 if (!Decl) {
2125 // This is the first time we have referenced this class template
2126 // specialization. Create the canonical declaration and add it to
2127 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002128 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002129 ClassTemplate->getTemplatedDecl()->getTagKind(),
2130 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002131 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002132 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002133 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002135 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002136 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002137 if (ClassTemplate->isOutOfLine())
2138 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002139 }
2140
Chandler Carruth2acfb222013-09-27 22:14:40 +00002141 // Diagnose uses of this specialization.
2142 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2143
Douglas Gregorc40290e2009-03-09 23:48:35 +00002144 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002145 assert(isa<RecordType>(CanonType) &&
2146 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002147 }
Mike Stump11289f42009-09-09 15:08:12 +00002148
Douglas Gregorc40290e2009-03-09 23:48:35 +00002149 // Build the fully-sugared type for this class template
2150 // specialization, which refers back to the class template
2151 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002152 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002153}
2154
John McCallfaf5fb42010-08-26 23:41:50 +00002155TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002156Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002157 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002158 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002159 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002160 SourceLocation RAngleLoc,
2161 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002162 if (SS.isInvalid())
2163 return true;
2164
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002165 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002166
Douglas Gregorc40290e2009-03-09 23:48:35 +00002167 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002168 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002169 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002170
Douglas Gregor5a064722011-02-28 17:23:35 +00002171 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002172 QualType T
2173 = Context.getDependentTemplateSpecializationType(ETK_None,
2174 DTN->getQualifier(),
2175 DTN->getIdentifier(),
2176 TemplateArgs);
2177 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002178 TypeLocBuilder TLB;
2179 DependentTemplateSpecializationTypeLoc SpecTL
2180 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002181 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2182 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002183 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002184 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002185 SpecTL.setLAngleLoc(LAngleLoc);
2186 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002187 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2188 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2189 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2190 }
2191
John McCall6b51f282009-11-23 01:53:49 +00002192 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002193
2194 if (Result.isNull())
2195 return true;
2196
Douglas Gregore7c20652011-03-02 00:47:37 +00002197 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002198 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002199 TemplateSpecializationTypeLoc SpecTL
2200 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002201 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002202 SpecTL.setTemplateNameLoc(TemplateLoc);
2203 SpecTL.setLAngleLoc(LAngleLoc);
2204 SpecTL.setRAngleLoc(RAngleLoc);
2205 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2206 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002207
Abramo Bagnara4244b432012-01-27 08:46:19 +00002208 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2209 // constructor or destructor name (in such a case, the scope specifier
2210 // will be attached to the enclosing Decl or Expr node).
2211 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002212 // Create an elaborated-type-specifier containing the nested-name-specifier.
2213 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2214 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002215 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002216 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2217 }
2218
2219 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002220}
John McCall06f6fe8d2009-09-04 01:14:41 +00002221
Douglas Gregore7c20652011-03-02 00:47:37 +00002222TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002223 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002224 SourceLocation TagLoc,
2225 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002226 SourceLocation TemplateKWLoc,
2227 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002228 SourceLocation TemplateLoc,
2229 SourceLocation LAngleLoc,
2230 ASTTemplateArgsPtr TemplateArgsIn,
2231 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002232 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002233
2234 // Translate the parser's template argument list in our AST format.
2235 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2236 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2237
2238 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002239 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002240 ElaboratedTypeKeyword Keyword
2241 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002242
Douglas Gregore7c20652011-03-02 00:47:37 +00002243 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2244 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2245 DTN->getQualifier(),
2246 DTN->getIdentifier(),
2247 TemplateArgs);
2248
2249 // Build type-source information.
2250 TypeLocBuilder TLB;
2251 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002252 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2253 SpecTL.setElaboratedKeywordLoc(TagLoc);
2254 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002255 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002256 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002257 SpecTL.setLAngleLoc(LAngleLoc);
2258 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002259 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2260 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2261 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2262 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002263
2264 if (TypeAliasTemplateDecl *TAT =
2265 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2266 // C++0x [dcl.type.elab]p2:
2267 // If the identifier resolves to a typedef-name or the simple-template-id
2268 // resolves to an alias template specialization, the
2269 // elaborated-type-specifier is ill-formed.
2270 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2271 Diag(TAT->getLocation(), diag::note_declared_at);
2272 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002273
2274 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2275 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002276 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002277
2278 // Check the tag kind
2279 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002280 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002281
John McCalld8fe9af2009-09-08 17:47:29 +00002282 IdentifierInfo *Id = D->getIdentifier();
2283 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002284
Richard Trieucaa33d32011-06-10 03:11:26 +00002285 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2286 TagLoc, *Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002287 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002288 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002289 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002290 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002291 }
2292 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002293
Douglas Gregore7c20652011-03-02 00:47:37 +00002294 // Provide source-location information for the template specialization.
2295 TypeLocBuilder TLB;
2296 TemplateSpecializationTypeLoc SpecTL
2297 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002298 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002299 SpecTL.setTemplateNameLoc(TemplateLoc);
2300 SpecTL.setLAngleLoc(LAngleLoc);
2301 SpecTL.setRAngleLoc(RAngleLoc);
2302 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2303 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002304
Douglas Gregore7c20652011-03-02 00:47:37 +00002305 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002306 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002307 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2308 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002309 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002310 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2311 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002312}
2313
Larisse Voufo39a1e502013-08-06 01:03:05 +00002314static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002315 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2316 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002317
2318static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2319 NamedDecl *PrevDecl,
2320 SourceLocation Loc,
2321 bool IsPartialSpecialization);
2322
2323static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002324
Richard Smith300e0c32013-09-24 04:49:23 +00002325static bool isTemplateArgumentTemplateParameter(
2326 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2327 switch (Arg.getKind()) {
2328 case TemplateArgument::Null:
2329 case TemplateArgument::NullPtr:
2330 case TemplateArgument::Integral:
2331 case TemplateArgument::Declaration:
2332 case TemplateArgument::Pack:
2333 case TemplateArgument::TemplateExpansion:
2334 return false;
2335
2336 case TemplateArgument::Type: {
2337 QualType Type = Arg.getAsType();
2338 const TemplateTypeParmType *TPT =
2339 Arg.getAsType()->getAs<TemplateTypeParmType>();
2340 return TPT && !Type.hasQualifiers() &&
2341 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2342 }
2343
2344 case TemplateArgument::Expression: {
2345 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2346 if (!DRE || !DRE->getDecl())
2347 return false;
2348 const NonTypeTemplateParmDecl *NTTP =
2349 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2350 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2351 }
2352
2353 case TemplateArgument::Template:
2354 const TemplateTemplateParmDecl *TTP =
2355 dyn_cast_or_null<TemplateTemplateParmDecl>(
2356 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2357 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2358 }
2359 llvm_unreachable("unexpected kind of template argument");
2360}
2361
2362static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2363 ArrayRef<TemplateArgument> Args) {
2364 if (Params->size() != Args.size())
2365 return false;
2366
2367 unsigned Depth = Params->getDepth();
2368
2369 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2370 TemplateArgument Arg = Args[I];
2371
2372 // If the parameter is a pack expansion, the argument must be a pack
2373 // whose only element is a pack expansion.
2374 if (Params->getParam(I)->isParameterPack()) {
2375 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2376 !Arg.pack_begin()->isPackExpansion())
2377 return false;
2378 Arg = Arg.pack_begin()->getPackExpansionPattern();
2379 }
2380
2381 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2382 return false;
2383 }
2384
2385 return true;
2386}
2387
Richard Smith4b55a9c2014-04-17 03:29:33 +00002388/// Convert the parser's template argument list representation into our form.
2389static TemplateArgumentListInfo
2390makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2391 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2392 TemplateId.RAngleLoc);
2393 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2394 TemplateId.NumArgs);
2395 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2396 return TemplateArgs;
2397}
2398
Larisse Voufo39a1e502013-08-06 01:03:05 +00002399DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002400 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2401 TemplateParameterList *TemplateParams, VarDecl::StorageClass SC,
2402 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002403 // D must be variable template id.
2404 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2405 "Variable template specialization is declared with a template it.");
2406
2407 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002408 TemplateArgumentListInfo TemplateArgs =
2409 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002410 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2411 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2412 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002413
Richard Smithbeef3452014-01-16 23:39:20 +00002414 TemplateName Name = TemplateId->Template.get();
2415
2416 // The template-id must name a variable template.
2417 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002418 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2419 if (!VarTemplate) {
2420 NamedDecl *FnTemplate;
2421 if (auto *OTS = Name.getAsOverloadedTemplate())
2422 FnTemplate = *OTS->begin();
2423 else
2424 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2425 if (FnTemplate)
2426 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2427 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002428 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2429 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002430 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002431
2432 // Check for unexpanded parameter packs in any of the template arguments.
2433 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2434 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2435 UPPC_PartialSpecialization))
2436 return true;
2437
2438 // Check that the template argument list is well-formed for this
2439 // template.
2440 SmallVector<TemplateArgument, 4> Converted;
2441 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2442 false, Converted))
2443 return true;
2444
2445 // Check that the type of this variable template specialization
2446 // matches the expected type.
2447 TypeSourceInfo *ExpectedDI;
2448 {
2449 // Do substitution on the type of the declaration
2450 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2451 Converted.data(), Converted.size());
2452 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002453 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002454 return true;
2455 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2456 ExpectedDI =
2457 SubstType(Templated->getTypeSourceInfo(),
2458 MultiLevelTemplateArgumentList(TemplateArgList),
2459 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2460 }
2461 if (!ExpectedDI)
2462 return true;
2463
Larisse Voufo39a1e502013-08-06 01:03:05 +00002464 // Find the variable template (partial) specialization declaration that
2465 // corresponds to these arguments.
2466 if (IsPartialSpecialization) {
2467 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002468 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2469 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002470 return true;
2471
2472 bool InstantiationDependent;
2473 if (!Name.isDependent() &&
2474 !TemplateSpecializationType::anyDependentTemplateArguments(
2475 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2476 InstantiationDependent)) {
2477 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2478 << VarTemplate->getDeclName();
2479 IsPartialSpecialization = false;
2480 }
Richard Smith300e0c32013-09-24 04:49:23 +00002481
2482 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2483 Converted)) {
2484 // C++ [temp.class.spec]p9b3:
2485 //
2486 // -- The argument list of the specialization shall not be identical
2487 // to the implicit argument list of the primary template.
2488 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2489 << /*variable template*/ 1
2490 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2491 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2492 // FIXME: Recover from this by treating the declaration as a redeclaration
2493 // of the primary template.
2494 return true;
2495 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002496 }
2497
Craig Topperc3ec1492014-05-26 06:22:03 +00002498 void *InsertPos = nullptr;
2499 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002500
2501 if (IsPartialSpecialization)
2502 // FIXME: Template parameter list matters too
2503 PrevDecl = VarTemplate->findPartialSpecialization(
2504 Converted.data(), Converted.size(), InsertPos);
2505 else
2506 PrevDecl = VarTemplate->findSpecialization(Converted.data(),
2507 Converted.size(), InsertPos);
2508
Craig Topperc3ec1492014-05-26 06:22:03 +00002509 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002510
2511 // Check whether we can declare a variable template specialization in
2512 // the current scope.
2513 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2514 TemplateNameLoc,
2515 IsPartialSpecialization))
2516 return true;
2517
2518 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2519 // Since the only prior variable template specialization with these
2520 // arguments was referenced but not declared, reuse that
2521 // declaration node as our own, updating its source location and
2522 // the list of outer template parameters to reflect our new declaration.
2523 Specialization = PrevDecl;
2524 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002525 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002526 } else if (IsPartialSpecialization) {
2527 // Create a new class template partial specialization declaration node.
2528 VarTemplatePartialSpecializationDecl *PrevPartial =
2529 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002530 VarTemplatePartialSpecializationDecl *Partial =
2531 VarTemplatePartialSpecializationDecl::Create(
2532 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2533 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002534 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002535
2536 if (!PrevPartial)
2537 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2538 Specialization = Partial;
2539
2540 // If we are providing an explicit specialization of a member variable
2541 // template specialization, make a note of that.
2542 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002543 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002544
2545 // Check that all of the template parameters of the variable template
2546 // partial specialization are deducible from the template
2547 // arguments. If not, this variable template partial specialization
2548 // will never be used.
2549 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2550 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2551 TemplateParams->getDepth(), DeducibleParams);
2552
2553 if (!DeducibleParams.all()) {
2554 unsigned NumNonDeducible =
2555 DeducibleParams.size() - DeducibleParams.count();
2556 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002557 << /*variable template*/ 1 << (NumNonDeducible > 1)
2558 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002559 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2560 if (!DeducibleParams[I]) {
2561 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2562 if (Param->getDeclName())
2563 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2564 << Param->getDeclName();
2565 else
2566 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002567 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002568 }
2569 }
2570 }
2571 } else {
2572 // Create a new class template specialization declaration node for
2573 // this explicit specialization or friend declaration.
2574 Specialization = VarTemplateSpecializationDecl::Create(
2575 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2576 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2577 Specialization->setTemplateArgsInfo(TemplateArgs);
2578
2579 if (!PrevDecl)
2580 VarTemplate->AddSpecialization(Specialization, InsertPos);
2581 }
2582
2583 // C++ [temp.expl.spec]p6:
2584 // If a template, a member template or the member of a class template is
2585 // explicitly specialized then that specialization shall be declared
2586 // before the first use of that specialization that would cause an implicit
2587 // instantiation to take place, in every translation unit in which such a
2588 // use occurs; no diagnostic is required.
2589 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2590 bool Okay = false;
2591 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2592 // Is there any previous explicit specialization declaration?
2593 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2594 Okay = true;
2595 break;
2596 }
2597 }
2598
2599 if (!Okay) {
2600 SourceRange Range(TemplateNameLoc, RAngleLoc);
2601 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2602 << Name << Range;
2603
2604 Diag(PrevDecl->getPointOfInstantiation(),
2605 diag::note_instantiation_required_here)
2606 << (PrevDecl->getTemplateSpecializationKind() !=
2607 TSK_ImplicitInstantiation);
2608 return true;
2609 }
2610 }
2611
2612 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2613 Specialization->setLexicalDeclContext(CurContext);
2614
2615 // Add the specialization into its lexical context, so that it can
2616 // be seen when iterating through the list of declarations in that
2617 // context. However, specializations are not found by name lookup.
2618 CurContext->addDecl(Specialization);
2619
2620 // Note that this is an explicit specialization.
2621 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2622
2623 if (PrevDecl) {
2624 // Check that this isn't a redefinition of this specialization,
2625 // merging with previous declarations.
2626 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2627 ForRedeclaration);
2628 PrevSpec.addDecl(PrevDecl);
2629 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002630 } else if (Specialization->isStaticDataMember() &&
2631 Specialization->isOutOfLine()) {
2632 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002633 }
2634
2635 // Link instantiations of static data members back to the template from
2636 // which they were instantiated.
2637 if (Specialization->isStaticDataMember())
2638 Specialization->setInstantiationOfStaticDataMember(
2639 VarTemplate->getTemplatedDecl(),
2640 Specialization->getSpecializationKind());
2641
2642 return Specialization;
2643}
2644
2645namespace {
2646/// \brief A partial specialization whose template arguments have matched
2647/// a given template-id.
2648struct PartialSpecMatchResult {
2649 VarTemplatePartialSpecializationDecl *Partial;
2650 TemplateArgumentList *Args;
2651};
2652}
2653
2654DeclResult
2655Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2656 SourceLocation TemplateNameLoc,
2657 const TemplateArgumentListInfo &TemplateArgs) {
2658 assert(Template && "A variable template id without template?");
2659
2660 // Check that the template argument list is well-formed for this template.
2661 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002662 if (CheckTemplateArgumentList(
2663 Template, TemplateNameLoc,
2664 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002665 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002666 return true;
2667
2668 // Find the variable template specialization declaration that
2669 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002670 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002671 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2672 Converted.data(), Converted.size(), InsertPos))
2673 // If we already have a variable template specialization, return it.
2674 return Spec;
2675
2676 // This is the first time we have referenced this variable template
2677 // specialization. Create the canonical declaration and add it to
2678 // the set of specializations, based on the closest partial specialization
2679 // that it represents. That is,
2680 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2681 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2682 Converted.data(), Converted.size());
2683 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2684 bool AmbiguousPartialSpec = false;
2685 typedef PartialSpecMatchResult MatchResult;
2686 SmallVector<MatchResult, 4> Matched;
2687 SourceLocation PointOfInstantiation = TemplateNameLoc;
2688 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2689
2690 // 1. Attempt to find the closest partial specialization that this
2691 // specializes, if any.
2692 // If any of the template arguments is dependent, then this is probably
2693 // a placeholder for an incomplete declarative context; which must be
2694 // complete by instantiation time. Thus, do not search through the partial
2695 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002696 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2697 // Perhaps better after unification of DeduceTemplateArguments() and
2698 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002699 bool InstantiationDependent = false;
2700 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2701 TemplateArgs, InstantiationDependent)) {
2702
2703 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2704 Template->getPartialSpecializations(PartialSpecs);
2705
2706 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2707 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2708 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2709
2710 if (TemplateDeductionResult Result =
2711 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2712 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002713 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002714 FailedCandidates.addCandidate()
2715 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2716 (void)Result;
2717 } else {
2718 Matched.push_back(PartialSpecMatchResult());
2719 Matched.back().Partial = Partial;
2720 Matched.back().Args = Info.take();
2721 }
2722 }
2723
Larisse Voufo39a1e502013-08-06 01:03:05 +00002724 if (Matched.size() >= 1) {
2725 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2726 if (Matched.size() == 1) {
2727 // -- If exactly one matching specialization is found, the
2728 // instantiation is generated from that specialization.
2729 // We don't need to do anything for this.
2730 } else {
2731 // -- If more than one matching specialization is found, the
2732 // partial order rules (14.5.4.2) are used to determine
2733 // whether one of the specializations is more specialized
2734 // than the others. If none of the specializations is more
2735 // specialized than all of the other matching
2736 // specializations, then the use of the variable template is
2737 // ambiguous and the program is ill-formed.
2738 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2739 PEnd = Matched.end();
2740 P != PEnd; ++P) {
2741 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2742 PointOfInstantiation) ==
2743 P->Partial)
2744 Best = P;
2745 }
2746
2747 // Determine if the best partial specialization is more specialized than
2748 // the others.
2749 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2750 PEnd = Matched.end();
2751 P != PEnd; ++P) {
2752 if (P != Best && getMoreSpecializedPartialSpecialization(
2753 P->Partial, Best->Partial,
2754 PointOfInstantiation) != Best->Partial) {
2755 AmbiguousPartialSpec = true;
2756 break;
2757 }
2758 }
2759 }
2760
2761 // Instantiate using the best variable template partial specialization.
2762 InstantiationPattern = Best->Partial;
2763 InstantiationArgs = Best->Args;
2764 } else {
2765 // -- If no match is found, the instantiation is generated
2766 // from the primary template.
2767 // InstantiationPattern = Template->getTemplatedDecl();
2768 }
2769 }
2770
Larisse Voufo39a1e502013-08-06 01:03:05 +00002771 // 2. Create the canonical declaration.
2772 // Note that we do not instantiate the variable just yet, since
2773 // instantiation is handled in DoMarkVarDeclReferenced().
2774 // FIXME: LateAttrs et al.?
2775 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2776 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2777 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2778 if (!Decl)
2779 return true;
2780
2781 if (AmbiguousPartialSpec) {
2782 // Partial ordering did not produce a clear winner. Complain.
2783 Decl->setInvalidDecl();
2784 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2785 << Decl;
2786
2787 // Print the matching partial specializations.
2788 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2789 PEnd = Matched.end();
2790 P != PEnd; ++P)
2791 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2792 << getTemplateArgumentBindingsText(
2793 P->Partial->getTemplateParameters(), *P->Args);
2794 return true;
2795 }
2796
2797 if (VarTemplatePartialSpecializationDecl *D =
2798 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2799 Decl->setInstantiationOf(D, InstantiationArgs);
2800
2801 assert(Decl && "No variable template specialization?");
2802 return Decl;
2803}
2804
2805ExprResult
2806Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2807 const DeclarationNameInfo &NameInfo,
2808 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2809 const TemplateArgumentListInfo *TemplateArgs) {
2810
2811 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2812 *TemplateArgs);
2813 if (Decl.isInvalid())
2814 return ExprError();
2815
2816 VarDecl *Var = cast<VarDecl>(Decl.get());
2817 if (!Var->getTemplateSpecializationKind())
2818 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2819 NameInfo.getLoc());
2820
2821 // Build an ordinary singleton decl ref.
2822 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002823 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002824}
2825
John McCalldadc5752010-08-24 06:29:42 +00002826ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002827 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002828 LookupResult &R,
2829 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002830 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002831 // FIXME: Can we do any checking at this point? I guess we could check the
2832 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002833 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002834 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002835 // foo<int> could identify a single function unambiguously
2836 // This approach does NOT work, since f<int>(1);
2837 // gets resolved prior to resorting to overload resolution
2838 // i.e., template<class T> void f(double);
2839 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002840
2841 // These should be filtered out by our callers.
2842 assert(!R.empty() && "empty lookup results when building templateid");
2843 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2844
Larisse Voufo39a1e502013-08-06 01:03:05 +00002845 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002846 bool InstantiationDependent;
2847 if (R.getAsSingle<VarTemplateDecl>() &&
2848 !TemplateSpecializationType::anyDependentTemplateArguments(
2849 *TemplateArgs, InstantiationDependent)) {
2850 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2851 R.getAsSingle<VarTemplateDecl>(),
2852 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002853 }
2854
John McCall58cc69d2010-01-27 01:50:18 +00002855 // We don't want lookup warnings at this point.
2856 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857
John McCalle66edc12009-11-24 19:00:30 +00002858 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002859 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002860 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002861 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002862 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002864 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002865
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002866 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002867}
2868
John McCalle66edc12009-11-24 19:00:30 +00002869// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002870ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002871Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002872 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002873 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002874 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002875
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002876 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002877 DeclContext *DC;
2878 if (!(DC = computeDeclContext(SS, false)) ||
2879 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002880 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002881 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002882
Douglas Gregor786123d2010-05-21 23:18:07 +00002883 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002884 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002885 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002886 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002887
John McCalle66edc12009-11-24 19:00:30 +00002888 if (R.isAmbiguous())
2889 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002890
John McCalle66edc12009-11-24 19:00:30 +00002891 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002892 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2893 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002894 return ExprError();
2895 }
2896
2897 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002898 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002899 << SS.getScopeRep()
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002900 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002901 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2902 return ExprError();
2903 }
2904
Abramo Bagnara7945c982012-01-27 09:46:47 +00002905 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002906}
2907
Douglas Gregorb67535d2009-03-31 00:43:58 +00002908/// \brief Form a dependent template name.
2909///
2910/// This action forms a dependent template name given the template
2911/// name and its (presumably dependent) scope specifier. For
2912/// example, given "MetaFun::template apply", the scope specifier \p
2913/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2914/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002916 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002917 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002918 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002919 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002920 bool EnteringContext,
2921 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002922 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2923 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002924 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002925 diag::warn_cxx98_compat_template_outside_of_template :
2926 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927 << FixItHint::CreateRemoval(TemplateKWLoc);
2928
Craig Topperc3ec1492014-05-26 06:22:03 +00002929 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002930 if (SS.isSet())
2931 LookupCtx = computeDeclContext(SS, EnteringContext);
2932 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002933 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002934 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002935 // C++0x [temp.names]p5:
2936 // If a name prefixed by the keyword template is not the name of
2937 // a template, the program is ill-formed. [Note: the keyword
2938 // template may not be applied to non-template members of class
2939 // templates. -end note ] [ Note: as is the case with the
2940 // typename prefix, the template prefix is allowed in cases
2941 // where it is not strictly necessary; i.e., when the
2942 // nested-name-specifier or the expression on the left of the ->
2943 // or . is not dependent on a template-parameter, or the use
2944 // does not appear in the scope of a template. -end note]
2945 //
2946 // Note: C++03 was more strict here, because it banned the use of
2947 // the "template" keyword prior to a template-name that was not a
2948 // dependent name. C++ DR468 relaxed this requirement (the
2949 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00002950 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00002951 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00002952 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002953 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00002954 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00002955 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2956 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00002957 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2958 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00002959 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00002960 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002961 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002962 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002963 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002964 << Name.getSourceRange()
2965 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002966 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00002967 } else {
2968 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00002969 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002970 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00002971 }
2972
Aaron Ballman4a979672014-01-03 13:56:08 +00002973 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974
Douglas Gregor3cf81312009-11-03 23:16:33 +00002975 switch (Name.getKind()) {
2976 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002977 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00002978 Name.Identifier));
2979 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980
Douglas Gregor71395fa2009-11-04 00:56:37 +00002981 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00002982 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002983 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00002984 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00002985
2986 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00002987 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00002988
Douglas Gregor3cf81312009-11-03 23:16:33 +00002989 default:
2990 break;
2991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002992
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002993 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002994 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002995 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002996 << Name.getSourceRange()
2997 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002998 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002999}
3000
Mike Stump11289f42009-09-09 15:08:12 +00003001bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00003002 const TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003003 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003004 const TemplateArgument &Arg = AL.getArgument();
3005
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003006 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003007 switch(Arg.getKind()) {
3008 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003009 // C++ [temp.arg.type]p1:
3010 // A template-argument for a template-parameter which is a
3011 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003012 break;
3013 case TemplateArgument::Template: {
3014 // We have a template type parameter but the template argument
3015 // is a template without any arguments.
3016 SourceRange SR = AL.getSourceRange();
3017 TemplateName Name = Arg.getAsTemplate();
3018 Diag(SR.getBegin(), diag::err_template_missing_args)
3019 << Name << SR;
3020 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3021 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003022
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003023 return true;
3024 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003025 case TemplateArgument::Expression: {
3026 // We have a template type parameter but the template argument is an
3027 // expression; see if maybe it is missing the "typename" keyword.
3028 CXXScopeSpec SS;
3029 DeclarationNameInfo NameInfo;
3030
3031 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3032 SS.Adopt(ArgExpr->getQualifierLoc());
3033 NameInfo = ArgExpr->getNameInfo();
3034 } else if (DependentScopeDeclRefExpr *ArgExpr =
3035 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3036 SS.Adopt(ArgExpr->getQualifierLoc());
3037 NameInfo = ArgExpr->getNameInfo();
3038 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3039 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003040 if (ArgExpr->isImplicitAccess()) {
3041 SS.Adopt(ArgExpr->getQualifierLoc());
3042 NameInfo = ArgExpr->getMemberNameInfo();
3043 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003044 }
3045
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003046 if (NameInfo.getName().isIdentifier()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003047 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3048 LookupParsedName(Result, CurScope, &SS);
3049
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003050 if (Result.getAsSingle<TypeDecl>() ||
3051 Result.getResultKind() ==
3052 LookupResult::NotFoundInCurrentInstantiation) {
3053 // FIXME: Add a FixIt and fix up the template argument for recovery.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003054 SourceLocation Loc = AL.getSourceRange().getBegin();
3055 Diag(Loc, diag::err_template_arg_must_be_type_suggest);
3056 Diag(Param->getLocation(), diag::note_template_param_here);
3057 return true;
3058 }
3059 }
3060 // fallthrough
3061 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003062 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003063 // We have a template type parameter but the template argument
3064 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003065 SourceRange SR = AL.getSourceRange();
3066 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003067 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003068
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003069 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003070 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003071 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003072
John McCallbcd03502009-12-07 02:54:59 +00003073 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003074 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003075
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003076 // Add the converted template type argument.
Douglas Gregore46db902011-06-17 22:11:49 +00003077 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
3078
3079 // Objective-C ARC:
3080 // If an explicitly-specified template argument type is a lifetime type
3081 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003082 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003083 ArgType->isObjCLifetimeType() &&
3084 !ArgType.getObjCLifetime()) {
3085 Qualifiers Qs;
3086 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3087 ArgType = Context.getQualifiedType(ArgType, Qs);
3088 }
3089
3090 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003091 return false;
3092}
3093
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003094/// \brief Substitute template arguments into the default template argument for
3095/// the given template type parameter.
3096///
3097/// \param SemaRef the semantic analysis object for which we are performing
3098/// the substitution.
3099///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003100/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003101/// for.
3102///
3103/// \param TemplateLoc the location of the template name that started the
3104/// template-id we are checking.
3105///
3106/// \param RAngleLoc the location of the right angle bracket ('>') that
3107/// terminates the template-id.
3108///
3109/// \param Param the template template parameter whose default we are
3110/// substituting into.
3111///
3112/// \param Converted the list of template arguments provided for template
3113/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003114/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003115static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003116SubstDefaultTemplateArgument(Sema &SemaRef,
3117 TemplateDecl *Template,
3118 SourceLocation TemplateLoc,
3119 SourceLocation RAngleLoc,
3120 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003121 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003122 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003123
3124 // If the argument type is dependent, instantiate it now based
3125 // on the previously-computed template arguments.
3126 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003127 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003128 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003129 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003130 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003131 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003132
David Majnemer89189202013-08-28 23:48:32 +00003133 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3134 Converted.data(), Converted.size());
3135
3136 // Only substitute for the innermost template argument list.
3137 MultiLevelTemplateArgumentList TemplateArgLists;
3138 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3139 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3140 TemplateArgLists.addOuterTemplateArguments(None);
3141
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003142 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003143 ArgType =
3144 SemaRef.SubstType(ArgType, TemplateArgLists,
3145 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003146 }
3147
3148 return ArgType;
3149}
3150
3151/// \brief Substitute template arguments into the default template argument for
3152/// the given non-type template parameter.
3153///
3154/// \param SemaRef the semantic analysis object for which we are performing
3155/// the substitution.
3156///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003158/// for.
3159///
3160/// \param TemplateLoc the location of the template name that started the
3161/// template-id we are checking.
3162///
3163/// \param RAngleLoc the location of the right angle bracket ('>') that
3164/// terminates the template-id.
3165///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003166/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003167/// substituting into.
3168///
3169/// \param Converted the list of template arguments provided for template
3170/// parameters that precede \p Param in the template parameter list.
3171///
3172/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003173static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003174SubstDefaultTemplateArgument(Sema &SemaRef,
3175 TemplateDecl *Template,
3176 SourceLocation TemplateLoc,
3177 SourceLocation RAngleLoc,
3178 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003179 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003180 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003181 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003182 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003183 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003184 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003185
David Majnemer89189202013-08-28 23:48:32 +00003186 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3187 Converted.data(), Converted.size());
3188
3189 // Only substitute for the innermost template argument list.
3190 MultiLevelTemplateArgumentList TemplateArgLists;
3191 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3192 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3193 TemplateArgLists.addOuterTemplateArguments(None);
3194
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003195 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003196 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003197 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003198}
3199
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003200/// \brief Substitute template arguments into the default template argument for
3201/// the given template template parameter.
3202///
3203/// \param SemaRef the semantic analysis object for which we are performing
3204/// the substitution.
3205///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003207/// for.
3208///
3209/// \param TemplateLoc the location of the template name that started the
3210/// template-id we are checking.
3211///
3212/// \param RAngleLoc the location of the right angle bracket ('>') that
3213/// terminates the template-id.
3214///
3215/// \param Param the template template parameter whose default we are
3216/// substituting into.
3217///
3218/// \param Converted the list of template arguments provided for template
3219/// parameters that precede \p Param in the template parameter list.
3220///
Douglas Gregordf846d12011-03-02 18:46:51 +00003221/// \param QualifierLoc Will be set to the nested-name-specifier (with
3222/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003223///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003224/// \returns the substituted template argument, or NULL if an error occurred.
3225static TemplateName
3226SubstDefaultTemplateArgument(Sema &SemaRef,
3227 TemplateDecl *Template,
3228 SourceLocation TemplateLoc,
3229 SourceLocation RAngleLoc,
3230 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003231 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003232 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003233 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003234 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003235 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003236 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237
David Majnemer89189202013-08-28 23:48:32 +00003238 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3239 Converted.data(), Converted.size());
3240
3241 // Only substitute for the innermost template argument list.
3242 MultiLevelTemplateArgumentList TemplateArgLists;
3243 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3244 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3245 TemplateArgLists.addOuterTemplateArguments(None);
3246
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003247 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003248 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003249 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003250 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003251 QualifierLoc =
3252 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003253 if (!QualifierLoc)
3254 return TemplateName();
3255 }
David Majnemer89189202013-08-28 23:48:32 +00003256
3257 return SemaRef.SubstTemplateName(
3258 QualifierLoc,
3259 Param->getDefaultArgument().getArgument().getAsTemplate(),
3260 Param->getDefaultArgument().getTemplateNameLoc(),
3261 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003262}
3263
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003264/// \brief If the given template parameter has a default template
3265/// argument, substitute into that default template argument and
3266/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003268Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3269 SourceLocation TemplateLoc,
3270 SourceLocation RAngleLoc,
3271 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003272 SmallVectorImpl<TemplateArgument>
3273 &Converted,
3274 bool &HasDefaultArg) {
3275 HasDefaultArg = false;
3276
3277 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003278 if (!TypeParm->hasDefaultArgument())
3279 return TemplateArgumentLoc();
3280
Richard Smithc87b9382013-07-04 01:01:24 +00003281 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003282 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003283 TemplateLoc,
3284 RAngleLoc,
3285 TypeParm,
3286 Converted);
3287 if (DI)
3288 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3289
3290 return TemplateArgumentLoc();
3291 }
3292
3293 if (NonTypeTemplateParmDecl *NonTypeParm
3294 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3295 if (!NonTypeParm->hasDefaultArgument())
3296 return TemplateArgumentLoc();
3297
Richard Smithc87b9382013-07-04 01:01:24 +00003298 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003299 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003300 TemplateLoc,
3301 RAngleLoc,
3302 NonTypeParm,
3303 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003304 if (Arg.isInvalid())
3305 return TemplateArgumentLoc();
3306
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003307 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003308 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3309 }
3310
3311 TemplateTemplateParmDecl *TempTempParm
3312 = cast<TemplateTemplateParmDecl>(Param);
3313 if (!TempTempParm->hasDefaultArgument())
3314 return TemplateArgumentLoc();
3315
Richard Smithc87b9382013-07-04 01:01:24 +00003316 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003317 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003318 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003319 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003320 RAngleLoc,
3321 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003322 Converted,
3323 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003324 if (TName.isNull())
3325 return TemplateArgumentLoc();
3326
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003328 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003329 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3330}
3331
Douglas Gregorda0fb532009-11-11 19:31:23 +00003332/// \brief Check that the given template argument corresponds to the given
3333/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003334///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003336/// checked.
3337///
3338/// \param Arg The template argument.
3339///
3340/// \param Template The template in which the template argument resides.
3341///
3342/// \param TemplateLoc The location of the template name for the template
3343/// whose argument list we're matching.
3344///
3345/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3346/// the template argument list.
3347///
3348/// \param ArgumentPackIndex The index into the argument pack where this
3349/// argument will be placed. Only valid if the parameter is a parameter pack.
3350///
3351/// \param Converted The checked, converted argument will be added to the
3352/// end of this small vector.
3353///
3354/// \param CTAK Describes how we arrived at this particular template argument:
3355/// explicitly written, deduced, etc.
3356///
3357/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003358bool Sema::CheckTemplateArgument(NamedDecl *Param,
3359 const TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003360 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003361 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003362 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003363 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003364 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003365 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003366 // Check template type parameters.
3367 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003368 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369
Douglas Gregoreebed722009-11-11 19:41:09 +00003370 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003372 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003373 // with the template arguments we've seen thus far. But if the
3374 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003375 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003376 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3377 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378
Peter Collingbourne01687632010-12-10 17:08:53 +00003379 if (NTTPType->isDependentType() &&
3380 !isa<TemplateTemplateParmDecl>(Template) &&
3381 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003382 // Do substitution on the type of the non-type template parameter.
3383 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003384 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003385 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003386 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003387 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388
3389 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003390 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003391 NTTPType = SubstType(NTTPType,
3392 MultiLevelTemplateArgumentList(TemplateArgs),
3393 NTTP->getLocation(),
3394 NTTP->getDeclName());
3395 // If that worked, check the non-type template parameter type
3396 // for validity.
3397 if (!NTTPType.isNull())
3398 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3399 NTTP->getLocation());
3400 if (NTTPType.isNull())
3401 return true;
3402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregorda0fb532009-11-11 19:31:23 +00003404 switch (Arg.getArgument().getKind()) {
3405 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003406 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407
Douglas Gregorda0fb532009-11-11 19:31:23 +00003408 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003409 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003410 ExprResult Res =
3411 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3412 Result, CTAK);
3413 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003414 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003416 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003417 break;
3418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregorda0fb532009-11-11 19:31:23 +00003420 case TemplateArgument::Declaration:
3421 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003422 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003423 // We've already checked this template argument, so just copy
3424 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003425 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003426 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Douglas Gregorda0fb532009-11-11 19:31:23 +00003428 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003429 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003430 // We were given a template template argument. It may not be ill-formed;
3431 // see below.
3432 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003433 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3434 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003435 // We have a template argument such as \c T::template X, which we
3436 // parsed as a template template argument. However, since we now
3437 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003438 // template name into an expression.
3439
3440 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3441 Arg.getTemplateNameLoc());
3442
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003443 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003444 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003445 // FIXME: the template-template arg was a DependentTemplateName,
3446 // so it was provided with a template keyword. However, its source
3447 // location is not stored in the template argument structure.
3448 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003449 ExprResult E = DependentScopeDeclRefExpr::Create(
3450 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3451 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003453 // If we parsed the template argument as a pack expansion, create a
3454 // pack expansion expression.
3455 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003456 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003457 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003458 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460
Douglas Gregorda0fb532009-11-11 19:31:23 +00003461 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003462 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003463 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003464 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003466 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003467 break;
3468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469
Douglas Gregorda0fb532009-11-11 19:31:23 +00003470 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003471 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003472 // therefore cannot be a non-type template argument.
3473 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3474 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregorda0fb532009-11-11 19:31:23 +00003476 Diag(Param->getLocation(), diag::note_template_param_here);
3477 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478
Douglas Gregorda0fb532009-11-11 19:31:23 +00003479 case TemplateArgument::Type: {
3480 // We have a non-type template parameter but the template
3481 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482
Douglas Gregorda0fb532009-11-11 19:31:23 +00003483 // C++ [temp.arg]p2:
3484 // In a template-argument, an ambiguity between a type-id and
3485 // an expression is resolved to a type-id, regardless of the
3486 // form of the corresponding template-parameter.
3487 //
3488 // We warn specifically about this case, since it can be rather
3489 // confusing for users.
3490 QualType T = Arg.getArgument().getAsType();
3491 SourceRange SR = Arg.getSourceRange();
3492 if (T->isFunctionType())
3493 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3494 else
3495 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3496 Diag(Param->getLocation(), diag::note_template_param_here);
3497 return true;
3498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
Douglas Gregorda0fb532009-11-11 19:31:23 +00003500 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003501 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503
Douglas Gregorda0fb532009-11-11 19:31:23 +00003504 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505 }
3506
3507
Douglas Gregorda0fb532009-11-11 19:31:23 +00003508 // Check template template parameters.
3509 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510
Douglas Gregorda0fb532009-11-11 19:31:23 +00003511 // Substitute into the template parameter list of the template
3512 // template parameter, since previously-supplied template arguments
3513 // may appear within the template template parameter.
3514 {
3515 // Set up a template instantiation context.
3516 LocalInstantiationScope Scope(*this);
3517 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003518 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003519 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003520 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003521 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522
3523 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003524 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003525 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003526 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003527 MultiLevelTemplateArgumentList(TemplateArgs)));
3528 if (!TempParm)
3529 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregorda0fb532009-11-11 19:31:23 +00003532 switch (Arg.getArgument().getKind()) {
3533 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003534 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregorda0fb532009-11-11 19:31:23 +00003536 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003537 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003538 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003539 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003541 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543
Douglas Gregorda0fb532009-11-11 19:31:23 +00003544 case TemplateArgument::Expression:
3545 case TemplateArgument::Type:
3546 // We have a template template parameter but the template
3547 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003548 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003549 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003550 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregorda0fb532009-11-11 19:31:23 +00003552 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003553 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003554 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003555 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003556 case TemplateArgument::NullPtr:
3557 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Douglas Gregorda0fb532009-11-11 19:31:23 +00003559 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003560 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562
Douglas Gregorda0fb532009-11-11 19:31:23 +00003563 return false;
3564}
3565
Douglas Gregor8e072612012-02-03 07:34:46 +00003566/// \brief Diagnose an arity mismatch in the
3567static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3568 SourceLocation TemplateLoc,
3569 TemplateArgumentListInfo &TemplateArgs) {
3570 TemplateParameterList *Params = Template->getTemplateParameters();
3571 unsigned NumParams = Params->size();
3572 unsigned NumArgs = TemplateArgs.size();
3573
3574 SourceRange Range;
3575 if (NumArgs > NumParams)
3576 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3577 TemplateArgs.getRAngleLoc());
3578 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3579 << (NumArgs > NumParams)
3580 << (isa<ClassTemplateDecl>(Template)? 0 :
3581 isa<FunctionTemplateDecl>(Template)? 1 :
3582 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3583 << Template << Range;
3584 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3585 << Params->getSourceRange();
3586 return true;
3587}
3588
Richard Smith1fde8ec2012-09-07 02:06:42 +00003589/// \brief Check whether the template parameter is a pack expansion, and if so,
3590/// determine the number of parameters produced by that expansion. For instance:
3591///
3592/// \code
3593/// template<typename ...Ts> struct A {
3594/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3595/// };
3596/// \endcode
3597///
3598/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3599/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003600static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003601 if (NonTypeTemplateParmDecl *NTTP
3602 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3603 if (NTTP->isExpandedParameterPack())
3604 return NTTP->getNumExpansionTypes();
3605 }
3606
3607 if (TemplateTemplateParmDecl *TTP
3608 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3609 if (TTP->isExpandedParameterPack())
3610 return TTP->getNumExpansionTemplateParameters();
3611 }
3612
David Blaikie7a30dc52013-02-21 01:47:18 +00003613 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003614}
3615
Douglas Gregord32e0282009-02-09 23:23:08 +00003616/// \brief Check that the given template argument list is well-formed
3617/// for specializing the given template.
3618bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3619 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003620 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003621 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003622 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00003623 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003624
John McCall6b51f282009-11-23 01:53:49 +00003625 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3626
Mike Stump11289f42009-09-09 15:08:12 +00003627 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003628 // [...] The type and form of each template-argument specified in
3629 // a template-id shall match the type and form specified for the
3630 // corresponding parameter declared by the template in its
3631 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003632 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003633 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003634 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003635 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003636 for (TemplateParameterList::iterator Param = Params->begin(),
3637 ParamEnd = Params->end();
3638 Param != ParamEnd; /* increment in loop */) {
3639 // If we have an expanded parameter pack, make sure we don't have too
3640 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003641 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003642 if (*Expansions == ArgumentPack.size()) {
3643 // We're done with this parameter pack. Pack up its arguments and add
3644 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003645 Converted.push_back(
3646 TemplateArgument::CreatePackCopy(Context,
3647 ArgumentPack.data(),
3648 ArgumentPack.size()));
3649 ArgumentPack.clear();
3650
Richard Smith1fde8ec2012-09-07 02:06:42 +00003651 // This argument is assigned to the next parameter.
3652 ++Param;
3653 continue;
3654 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3655 // Not enough arguments for this parameter pack.
3656 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3657 << false
3658 << (isa<ClassTemplateDecl>(Template)? 0 :
3659 isa<FunctionTemplateDecl>(Template)? 1 :
3660 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3661 << Template;
3662 Diag(Template->getLocation(), diag::note_template_decl_here)
3663 << Params->getSourceRange();
3664 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003665 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Richard Smith1fde8ec2012-09-07 02:06:42 +00003668 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003669 // Check the template argument we were given.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3671 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003672 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003673 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Richard Smith83b11aa2014-01-09 02:22:22 +00003675 if (TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
3676 isa<TypeAliasTemplateDecl>(Template) &&
3677 !(Param + 1 == ParamEnd && (*Param)->isTemplateParameterPack() &&
3678 !getExpandedPackSize(*Param))) {
3679 // Core issue 1430: we have a pack expansion as an argument to an
3680 // alias template, and it's not part of a final parameter pack. This
3681 // can't be canonicalized, so reject it now.
3682 Diag(TemplateArgs[ArgIdx].getLocation(),
3683 diag::err_alias_template_expansion_into_fixed_list)
3684 << TemplateArgs[ArgIdx].getSourceRange();
3685 Diag((*Param)->getLocation(), diag::note_template_param_here);
3686 return true;
3687 }
3688
Richard Smith1fde8ec2012-09-07 02:06:42 +00003689 // We're now done with this argument.
3690 ++ArgIdx;
3691
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003692 if ((*Param)->isTemplateParameterPack()) {
3693 // The template parameter was a template parameter pack, so take the
3694 // deduced argument and place it on the argument pack. Note that we
3695 // stay on the same template parameter so that we can deduce more
3696 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003697 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003698 } else {
3699 // Move to the next template parameter.
3700 ++Param;
3701 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003702
3703 // If we just saw a pack expansion, then directly convert the remaining
3704 // arguments, because we don't know what parameters they'll match up
3705 // with.
3706 if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) {
3707 bool InFinalParameterPack = Param != ParamEnd &&
3708 Param + 1 == ParamEnd &&
3709 (*Param)->isTemplateParameterPack() &&
3710 !getExpandedPackSize(*Param);
3711
3712 if (!InFinalParameterPack && !ArgumentPack.empty()) {
3713 // If we were part way through filling in an expanded parameter pack,
3714 // fall back to just producing individual arguments.
3715 Converted.insert(Converted.end(),
3716 ArgumentPack.begin(), ArgumentPack.end());
3717 ArgumentPack.clear();
3718 }
3719
3720 while (ArgIdx < NumArgs) {
3721 if (InFinalParameterPack)
3722 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3723 else
3724 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3725 ++ArgIdx;
3726 }
3727
3728 // Push the argument pack onto the list of converted arguments.
3729 if (InFinalParameterPack) {
Eli Friedmanb826a002012-09-26 02:36:12 +00003730 Converted.push_back(
3731 TemplateArgument::CreatePackCopy(Context,
3732 ArgumentPack.data(),
3733 ArgumentPack.size()));
3734 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003735 }
3736
3737 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003738 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003739
Douglas Gregor84d49a22009-11-11 21:54:23 +00003740 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Douglas Gregor2f157c92011-06-03 02:59:40 +00003743 // If we're checking a partial template argument list, we're done.
3744 if (PartialTemplateArgs) {
3745 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3746 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3747 ArgumentPack.data(),
3748 ArgumentPack.size()));
3749
Richard Smith1fde8ec2012-09-07 02:06:42 +00003750 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003751 }
3752
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003754 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003755 if ((*Param)->isTemplateParameterPack()) {
3756 assert(!getExpandedPackSize(*Param) &&
3757 "Should have dealt with this already");
3758
3759 // A non-expanded parameter pack before the end of the parameter list
3760 // only occurs for an ill-formed template parameter list, unless we've
3761 // got a partial argument list for a function template, so just bail out.
3762 if (Param + 1 != ParamEnd)
3763 return true;
3764
Eli Friedmanb826a002012-09-26 02:36:12 +00003765 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3766 ArgumentPack.data(),
3767 ArgumentPack.size()));
3768 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003769
3770 ++Param;
3771 continue;
3772 }
3773
Douglas Gregor8e072612012-02-03 07:34:46 +00003774 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003775 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776
Douglas Gregor84d49a22009-11-11 21:54:23 +00003777 // Retrieve the default template argument from the template
3778 // parameter. For each kind of template parameter, we substitute the
3779 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003781 // the default argument.
3782 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003783 if (!TTP->hasDefaultArgument())
3784 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3785 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003786
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003788 Template,
3789 TemplateLoc,
3790 RAngleLoc,
3791 TTP,
3792 Converted);
3793 if (!ArgType)
3794 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Douglas Gregor84d49a22009-11-11 21:54:23 +00003796 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3797 ArgType);
3798 } else if (NonTypeTemplateParmDecl *NTTP
3799 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003800 if (!NTTP->hasDefaultArgument())
3801 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3802 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003803
John McCalldadc5752010-08-24 06:29:42 +00003804 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805 TemplateLoc,
3806 RAngleLoc,
3807 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003808 Converted);
3809 if (E.isInvalid())
3810 return true;
3811
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003812 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003813 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3814 } else {
3815 TemplateTemplateParmDecl *TempParm
3816 = cast<TemplateTemplateParmDecl>(*Param);
3817
Douglas Gregor8e072612012-02-03 07:34:46 +00003818 if (!TempParm->hasDefaultArgument())
3819 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3820 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003821
Douglas Gregordf846d12011-03-02 18:46:51 +00003822 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003823 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 TemplateLoc,
3825 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003826 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003827 Converted,
3828 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003829 if (Name.isNull())
3830 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003831
Douglas Gregor9d802122011-03-02 17:09:35 +00003832 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3833 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835
Douglas Gregor84d49a22009-11-11 21:54:23 +00003836 // Introduce an instantiation record that describes where we are using
3837 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003838 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3839 SourceRange(TemplateLoc, RAngleLoc));
3840 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003841 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842
Douglas Gregor84d49a22009-11-11 21:54:23 +00003843 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003844 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003845 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003846 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847
Douglas Gregor739b107a2011-03-03 02:41:12 +00003848 // Core issue 150 (assumed resolution): if this is a template template
3849 // parameter, keep track of the default template arguments from the
3850 // template definition.
3851 if (isTemplateTemplateParameter)
3852 TemplateArgs.addArgument(Arg);
3853
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003854 // Move to the next template parameter and argument.
3855 ++Param;
3856 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858
Richard Smith07f79912014-06-06 16:00:50 +00003859 // If we're performing a partial argument substitution, allow any trailing
3860 // pack expansions; they might be empty. This can happen even if
3861 // PartialTemplateArgs is false (the list of arguments is complete but
3862 // still dependent).
3863 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3864 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3865 while (ArgIdx < NumArgs &&
3866 TemplateArgs[ArgIdx].getArgument().isPackExpansion())
3867 Converted.push_back(TemplateArgs[ArgIdx++].getArgument());
3868 }
3869
Douglas Gregor8e072612012-02-03 07:34:46 +00003870 // If we have any leftover arguments, then there were too many arguments.
3871 // Complain and fail.
3872 if (ArgIdx < NumArgs)
3873 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874
Richard Smith1fde8ec2012-09-07 02:06:42 +00003875 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003876}
3877
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003878namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879 class UnnamedLocalNoLinkageFinder
3880 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003881 {
3882 Sema &S;
3883 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003885 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003887 public:
3888 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3889
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890 bool Visit(QualType T) {
3891 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003894#define TYPE(Class, Parent) \
3895 bool Visit##Class##Type(const Class##Type *);
3896#define ABSTRACT_TYPE(Class, Parent) \
3897 bool Visit##Class##Type(const Class##Type *) { return false; }
3898#define NON_CANONICAL_TYPE(Class, Parent) \
3899 bool Visit##Class##Type(const Class##Type *) { return false; }
3900#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003902 bool VisitTagDecl(const TagDecl *Tag);
3903 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3904 };
3905}
3906
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003908 return false;
3909}
3910
3911bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3912 return Visit(T->getElementType());
3913}
3914
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003916 return Visit(T->getPointeeType());
3917}
3918
3919bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003920 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003921 return Visit(T->getPointeeType());
3922}
3923
3924bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003925 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003926 return Visit(T->getPointeeType());
3927}
3928
3929bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003931 return Visit(T->getPointeeType());
3932}
3933
3934bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003936 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3937}
3938
3939bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003941 return Visit(T->getElementType());
3942}
3943
3944bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003946 return Visit(T->getElementType());
3947}
3948
3949bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003951 return Visit(T->getElementType());
3952}
3953
3954bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003956 return Visit(T->getElementType());
3957}
3958
3959bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003960 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003961 return Visit(T->getElementType());
3962}
3963
3964bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3965 return Visit(T->getElementType());
3966}
3967
3968bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3969 return Visit(T->getElementType());
3970}
3971
3972bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3973 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003974 for (const auto &A : T->param_types()) {
3975 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003976 return true;
3977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978
Alp Toker314cc812014-01-25 16:55:45 +00003979 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003980}
3981
3982bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3983 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00003984 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003985}
3986
3987bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3988 const UnresolvedUsingType*) {
3989 return false;
3990}
3991
3992bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3993 return false;
3994}
3995
3996bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3997 return Visit(T->getUnderlyingType());
3998}
3999
4000bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4001 return false;
4002}
4003
Alexis Hunte852b102011-05-24 22:41:36 +00004004bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4005 const UnaryTransformType*) {
4006 return false;
4007}
4008
Richard Smith30482bc2011-02-20 03:19:35 +00004009bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4010 return Visit(T->getDeducedType());
4011}
4012
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004013bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4014 return VisitTagDecl(T->getDecl());
4015}
4016
4017bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4018 return VisitTagDecl(T->getDecl());
4019}
4020
4021bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4022 const TemplateTypeParmType*) {
4023 return false;
4024}
4025
Douglas Gregorada4b792011-01-14 02:55:32 +00004026bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4027 const SubstTemplateTypeParmPackType *) {
4028 return false;
4029}
4030
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004031bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4032 const TemplateSpecializationType*) {
4033 return false;
4034}
4035
4036bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4037 const InjectedClassNameType* T) {
4038 return VisitTagDecl(T->getDecl());
4039}
4040
4041bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4042 const DependentNameType* T) {
4043 return VisitNestedNameSpecifier(T->getQualifier());
4044}
4045
4046bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4047 const DependentTemplateSpecializationType* T) {
4048 return VisitNestedNameSpecifier(T->getQualifier());
4049}
4050
Douglas Gregord2fa7662010-12-20 02:24:11 +00004051bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4052 const PackExpansionType* T) {
4053 return Visit(T->getPattern());
4054}
4055
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004056bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4057 return false;
4058}
4059
4060bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4061 const ObjCInterfaceType *) {
4062 return false;
4063}
4064
4065bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4066 const ObjCObjectPointerType *) {
4067 return false;
4068}
4069
Eli Friedman0dfb8892011-10-06 23:00:33 +00004070bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4071 return Visit(T->getValueType());
4072}
4073
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004074bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4075 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004076 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004077 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004078 diag::warn_cxx98_compat_template_arg_local_type :
4079 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004080 << S.Context.getTypeDeclType(Tag) << SR;
4081 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082 }
4083
John McCall5ea95772013-03-09 00:54:27 +00004084 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004085 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004086 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004087 diag::warn_cxx98_compat_template_arg_unnamed_type :
4088 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004089 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4090 return true;
4091 }
4092
4093 return false;
4094}
4095
4096bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4097 NestedNameSpecifier *NNS) {
4098 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4099 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004101 switch (NNS->getKind()) {
4102 case NestedNameSpecifier::Identifier:
4103 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004104 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004105 case NestedNameSpecifier::Global:
4106 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004108 case NestedNameSpecifier::TypeSpec:
4109 case NestedNameSpecifier::TypeSpecWithTemplate:
4110 return Visit(QualType(NNS->getAsType(), 0));
4111 }
David Blaikie8a40f702012-01-17 06:56:22 +00004112 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004113}
4114
4115
Douglas Gregord32e0282009-02-09 23:23:08 +00004116/// \brief Check a template argument against its corresponding
4117/// template type parameter.
4118///
4119/// This routine implements the semantics of C++ [temp.arg.type]. It
4120/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004121bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004122 TypeSourceInfo *ArgInfo) {
4123 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004124 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004125 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004126
4127 if (Arg->isVariablyModifiedType()) {
4128 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004129 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004130 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004131 }
4132
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004133 // C++03 [temp.arg.type]p2:
4134 // A local type, a type with no linkage, an unnamed type or a type
4135 // compounded from any of these types shall not be used as a
4136 // template-argument for a template type-parameter.
4137 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004138 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004139 // a warning.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004140 if (LangOpts.CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004141 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
4142 SR.getBegin()) != DiagnosticsEngine::Ignored ||
4143 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
4144 SR.getBegin()) != DiagnosticsEngine::Ignored :
4145 Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004146 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4147 (void)Finder.Visit(Context.getCanonicalType(Arg));
4148 }
4149
Douglas Gregord32e0282009-02-09 23:23:08 +00004150 return false;
4151}
4152
Douglas Gregor20fdef32012-04-10 17:08:25 +00004153enum NullPointerValueKind {
4154 NPV_NotNullPointer,
4155 NPV_NullPointer,
4156 NPV_Error
4157};
4158
4159/// \brief Determine whether the given template argument is a null pointer
4160/// value of the appropriate type.
4161static NullPointerValueKind
4162isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4163 QualType ParamType, Expr *Arg) {
4164 if (Arg->isValueDependent() || Arg->isTypeDependent())
4165 return NPV_NotNullPointer;
4166
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004167 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004168 return NPV_NotNullPointer;
4169
4170 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004171 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4172 if (ArgRV.isInvalid())
4173 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004174 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004175
Douglas Gregor20fdef32012-04-10 17:08:25 +00004176 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004177 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004178 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004179 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004180 EvalResult.HasSideEffects) {
4181 SourceLocation DiagLoc = Arg->getExprLoc();
4182
4183 // If our only note is the usual "invalid subexpression" note, just point
4184 // the caret at its location rather than producing an essentially
4185 // redundant note.
4186 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4187 diag::note_invalid_subexpr_in_const_expr) {
4188 DiagLoc = Notes[0].first;
4189 Notes.clear();
4190 }
4191
4192 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4193 << Arg->getType() << Arg->getSourceRange();
4194 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4195 S.Diag(Notes[I].first, Notes[I].second);
4196
4197 S.Diag(Param->getLocation(), diag::note_template_param_here);
4198 return NPV_Error;
4199 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004200
4201 // C++11 [temp.arg.nontype]p1:
4202 // - an address constant expression of type std::nullptr_t
4203 if (Arg->getType()->isNullPtrType())
4204 return NPV_NullPointer;
4205
4206 // - a constant expression that evaluates to a null pointer value (4.10); or
4207 // - a constant expression that evaluates to a null member pointer value
4208 // (4.11); or
4209 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4210 (EvalResult.Val.isMemberPointer() &&
4211 !EvalResult.Val.getMemberPointerDecl())) {
4212 // If our expression has an appropriate type, we've succeeded.
4213 bool ObjCLifetimeConversion;
4214 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4215 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4216 ObjCLifetimeConversion))
4217 return NPV_NullPointer;
4218
4219 // The types didn't match, but we know we got a null pointer; complain,
4220 // then recover as if the types were correct.
4221 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4222 << Arg->getType() << ParamType << Arg->getSourceRange();
4223 S.Diag(Param->getLocation(), diag::note_template_param_here);
4224 return NPV_NullPointer;
4225 }
4226
4227 // If we don't have a null pointer value, but we do have a NULL pointer
4228 // constant, suggest a cast to the appropriate type.
4229 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4230 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4231 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004232 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4233 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4234 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004235 S.Diag(Param->getLocation(), diag::note_template_param_here);
4236 return NPV_NullPointer;
4237 }
4238
4239 // FIXME: If we ever want to support general, address-constant expressions
4240 // as non-type template arguments, we should return the ExprResult here to
4241 // be interpreted by the caller.
4242 return NPV_NotNullPointer;
4243}
4244
David Majnemer61c39a12013-08-23 05:39:39 +00004245/// \brief Checks whether the given template argument is compatible with its
4246/// template parameter.
4247static bool CheckTemplateArgumentIsCompatibleWithParameter(
4248 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4249 Expr *Arg, QualType ArgType) {
4250 bool ObjCLifetimeConversion;
4251 if (ParamType->isPointerType() &&
4252 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4253 S.IsQualificationConversion(ArgType, ParamType, false,
4254 ObjCLifetimeConversion)) {
4255 // For pointer-to-object types, qualification conversions are
4256 // permitted.
4257 } else {
4258 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4259 if (!ParamRef->getPointeeType()->isFunctionType()) {
4260 // C++ [temp.arg.nontype]p5b3:
4261 // For a non-type template-parameter of type reference to
4262 // object, no conversions apply. The type referred to by the
4263 // reference may be more cv-qualified than the (otherwise
4264 // identical) type of the template- argument. The
4265 // template-parameter is bound directly to the
4266 // template-argument, which shall be an lvalue.
4267
4268 // FIXME: Other qualifiers?
4269 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4270 unsigned ArgQuals = ArgType.getCVRQualifiers();
4271
4272 if ((ParamQuals | ArgQuals) != ParamQuals) {
4273 S.Diag(Arg->getLocStart(),
4274 diag::err_template_arg_ref_bind_ignores_quals)
4275 << ParamType << Arg->getType() << Arg->getSourceRange();
4276 S.Diag(Param->getLocation(), diag::note_template_param_here);
4277 return true;
4278 }
4279 }
4280 }
4281
4282 // At this point, the template argument refers to an object or
4283 // function with external linkage. We now need to check whether the
4284 // argument and parameter types are compatible.
4285 if (!S.Context.hasSameUnqualifiedType(ArgType,
4286 ParamType.getNonReferenceType())) {
4287 // We can't perform this conversion or binding.
4288 if (ParamType->isReferenceType())
4289 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4290 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4291 else
4292 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4293 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4294 S.Diag(Param->getLocation(), diag::note_template_param_here);
4295 return true;
4296 }
4297 }
4298
4299 return false;
4300}
4301
Douglas Gregorccb07762009-02-11 19:52:55 +00004302/// \brief Checks whether the given template argument is the address
4303/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004305CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4306 NonTypeTemplateParmDecl *Param,
4307 QualType ParamType,
4308 Expr *ArgIn,
4309 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004310 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004311 Expr *Arg = ArgIn;
4312 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004313
Douglas Gregor20fdef32012-04-10 17:08:25 +00004314 // If our parameter has pointer type, check for a null template value.
4315 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4316 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4317 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004318 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00004319 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004320 return false;
4321
4322 case NPV_Error:
4323 return true;
4324
4325 case NPV_NotNullPointer:
4326 break;
4327 }
4328 }
John McCall7c454bb2011-07-15 05:09:51 +00004329
Douglas Gregorb242683d2010-04-01 18:32:35 +00004330 bool AddressTaken = false;
4331 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004332 if (S.getLangOpts().MicrosoftExt) {
4333 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4334 // dereference and address-of operators.
4335 Arg = Arg->IgnoreParenCasts();
4336
4337 bool ExtWarnMSTemplateArg = false;
4338 UnaryOperatorKind FirstOpKind;
4339 SourceLocation FirstOpLoc;
4340 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4341 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4342 if (UnOpKind == UO_Deref)
4343 ExtWarnMSTemplateArg = true;
4344 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4345 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4346 if (!AddrOpLoc.isValid()) {
4347 FirstOpKind = UnOpKind;
4348 FirstOpLoc = UnOp->getOperatorLoc();
4349 }
4350 } else
4351 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004352 }
David Majnemer61c39a12013-08-23 05:39:39 +00004353 if (FirstOpLoc.isValid()) {
4354 if (ExtWarnMSTemplateArg)
4355 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4356 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004357
David Majnemer61c39a12013-08-23 05:39:39 +00004358 if (FirstOpKind == UO_AddrOf)
4359 AddressTaken = true;
4360 else if (Arg->getType()->isPointerType()) {
4361 // We cannot let pointers get dereferenced here, that is obviously not a
4362 // constant expression.
4363 assert(FirstOpKind == UO_Deref);
4364 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4365 << Arg->getSourceRange();
4366 }
4367 }
4368 } else {
4369 // See through any implicit casts we added to fix the type.
4370 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004371
David Majnemer61c39a12013-08-23 05:39:39 +00004372 // C++ [temp.arg.nontype]p1:
4373 //
4374 // A template-argument for a non-type, non-template
4375 // template-parameter shall be one of: [...]
4376 //
4377 // -- the address of an object or function with external
4378 // linkage, including function templates and function
4379 // template-ids but excluding non-static class members,
4380 // expressed as & id-expression where the & is optional if
4381 // the name refers to a function or array, or if the
4382 // corresponding template-parameter is a reference; or
4383
4384 // In C++98/03 mode, give an extension warning on any extra parentheses.
4385 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4386 bool ExtraParens = false;
4387 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4388 if (!Invalid && !ExtraParens) {
4389 S.Diag(Arg->getLocStart(),
4390 S.getLangOpts().CPlusPlus11
4391 ? diag::warn_cxx98_compat_template_arg_extra_parens
4392 : diag::ext_template_arg_extra_parens)
4393 << Arg->getSourceRange();
4394 ExtraParens = true;
4395 }
4396
4397 Arg = Parens->getSubExpr();
4398 }
4399
4400 while (SubstNonTypeTemplateParmExpr *subst =
4401 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4402 Arg = subst->getReplacement()->IgnoreImpCasts();
4403
4404 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4405 if (UnOp->getOpcode() == UO_AddrOf) {
4406 Arg = UnOp->getSubExpr();
4407 AddressTaken = true;
4408 AddrOpLoc = UnOp->getOperatorLoc();
4409 }
4410 }
4411
4412 while (SubstNonTypeTemplateParmExpr *subst =
4413 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4414 Arg = subst->getReplacement()->IgnoreImpCasts();
4415 }
John McCall7c454bb2011-07-15 05:09:51 +00004416
Chandler Carruth724a8a12010-01-31 10:01:20 +00004417 // Stop checking the precise nature of the argument if it is value dependent,
4418 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004419 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004420 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004421 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004422 }
David Majnemer61c39a12013-08-23 05:39:39 +00004423
4424 if (isa<CXXUuidofExpr>(Arg)) {
4425 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4426 ArgIn, Arg, ArgType))
4427 return true;
4428
4429 Converted = TemplateArgument(ArgIn);
4430 return false;
4431 }
4432
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004433 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4434 if (!DRE) {
4435 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4436 << Arg->getSourceRange();
4437 S.Diag(Param->getLocation(), diag::note_template_param_here);
4438 return true;
4439 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004440
Eli Friedmanb826a002012-09-26 02:36:12 +00004441 ValueDecl *Entity = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00004442
4443 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004444 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004445 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004446 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004447 S.Diag(Param->getLocation(), diag::note_template_param_here);
4448 return true;
4449 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004450
4451 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004453 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004454 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004455 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004456 S.Diag(Param->getLocation(), diag::note_template_param_here);
4457 return true;
4458 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004459 }
Mike Stump11289f42009-09-09 15:08:12 +00004460
Richard Smith9380e0e2012-04-04 21:11:30 +00004461 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4462 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004463
Richard Smith9380e0e2012-04-04 21:11:30 +00004464 // A non-type template argument must refer to an object or function.
4465 if (!Func && !Var) {
4466 // We found something, but we don't know specifically what it is.
4467 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4468 << Arg->getSourceRange();
4469 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4470 return true;
4471 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004472
Richard Smith9380e0e2012-04-04 21:11:30 +00004473 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004474 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004475 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004476 diag::warn_cxx98_compat_template_arg_object_internal :
4477 diag::ext_template_arg_object_internal)
4478 << !Func << Entity << Arg->getSourceRange();
4479 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4480 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004481 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004482 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4483 << !Func << Entity << Arg->getSourceRange();
4484 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4485 << !Func;
4486 return true;
4487 }
4488
4489 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004490 // If the template parameter has pointer type, the function decays.
4491 if (ParamType->isPointerType() && !AddressTaken)
4492 ArgType = S.Context.getPointerType(Func->getType());
4493 else if (AddressTaken && ParamType->isReferenceType()) {
4494 // If we originally had an address-of operator, but the
4495 // parameter has reference type, complain and (if things look
4496 // like they will work) drop the address-of operator.
4497 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4498 ParamType.getNonReferenceType())) {
4499 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4500 << ParamType;
4501 S.Diag(Param->getLocation(), diag::note_template_param_here);
4502 return true;
4503 }
4504
4505 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4506 << ParamType
4507 << FixItHint::CreateRemoval(AddrOpLoc);
4508 S.Diag(Param->getLocation(), diag::note_template_param_here);
4509
4510 ArgType = Func->getType();
4511 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004512 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004513 // A value of reference type is not an object.
4514 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004515 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004516 diag::err_template_arg_reference_var)
4517 << Var->getType() << Arg->getSourceRange();
4518 S.Diag(Param->getLocation(), diag::note_template_param_here);
4519 return true;
4520 }
4521
Richard Smith9380e0e2012-04-04 21:11:30 +00004522 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004523 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004524 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4525 << Arg->getSourceRange();
4526 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4527 return true;
4528 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004529
4530 // If the template parameter has pointer type, we must have taken
4531 // the address of this object.
4532 if (ParamType->isReferenceType()) {
4533 if (AddressTaken) {
4534 // If we originally had an address-of operator, but the
4535 // parameter has reference type, complain and (if things look
4536 // like they will work) drop the address-of operator.
4537 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4538 ParamType.getNonReferenceType())) {
4539 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4540 << ParamType;
4541 S.Diag(Param->getLocation(), diag::note_template_param_here);
4542 return true;
4543 }
4544
4545 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4546 << ParamType
4547 << FixItHint::CreateRemoval(AddrOpLoc);
4548 S.Diag(Param->getLocation(), diag::note_template_param_here);
4549
4550 ArgType = Var->getType();
4551 }
4552 } else if (!AddressTaken && ParamType->isPointerType()) {
4553 if (Var->getType()->isArrayType()) {
4554 // Array-to-pointer decay.
4555 ArgType = S.Context.getArrayDecayedType(Var->getType());
4556 } else {
4557 // If the template parameter has pointer type but the address of
4558 // this object was not taken, complain and (possibly) recover by
4559 // taking the address of the entity.
4560 ArgType = S.Context.getPointerType(Var->getType());
4561 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4562 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4563 << ParamType;
4564 S.Diag(Param->getLocation(), diag::note_template_param_here);
4565 return true;
4566 }
4567
4568 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4569 << ParamType
4570 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4571
4572 S.Diag(Param->getLocation(), diag::note_template_param_here);
4573 }
4574 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004575 }
Mike Stump11289f42009-09-09 15:08:12 +00004576
David Majnemer61c39a12013-08-23 05:39:39 +00004577 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4578 Arg, ArgType))
4579 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004580
4581 // Create the template argument.
Eli Friedmanb826a002012-09-26 02:36:12 +00004582 Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
4583 ParamType->isReferenceType());
Nick Lewycky45b50522013-02-02 00:25:55 +00004584 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004585 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004586}
4587
4588/// \brief Checks whether the given template argument is a pointer to
4589/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004590static bool CheckTemplateArgumentPointerToMember(Sema &S,
4591 NonTypeTemplateParmDecl *Param,
4592 QualType ParamType,
4593 Expr *&ResultArg,
4594 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004595 bool Invalid = false;
4596
Douglas Gregor20fdef32012-04-10 17:08:25 +00004597 // Check for a null pointer value.
4598 Expr *Arg = ResultArg;
4599 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4600 case NPV_Error:
4601 return true;
4602 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004603 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00004604 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004605 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4606 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004607 return false;
4608 case NPV_NotNullPointer:
4609 break;
4610 }
4611
4612 bool ObjCLifetimeConversion;
4613 if (S.IsQualificationConversion(Arg->getType(),
4614 ParamType.getNonReferenceType(),
4615 false, ObjCLifetimeConversion)) {
4616 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004617 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004618 ResultArg = Arg;
4619 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4620 ParamType.getNonReferenceType())) {
4621 // We can't perform this conversion.
4622 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4623 << Arg->getType() << ParamType << Arg->getSourceRange();
4624 S.Diag(Param->getLocation(), diag::note_template_param_here);
4625 return true;
4626 }
4627
Douglas Gregorccb07762009-02-11 19:52:55 +00004628 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004629 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004630 Arg = Cast->getSubExpr();
4631
4632 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004633 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004634 // A template-argument for a non-type, non-template
4635 // template-parameter shall be one of: [...]
4636 //
4637 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004638 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004639
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004640 // In C++98/03 mode, give an extension warning on any extra parentheses.
4641 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4642 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004643 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004644 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004645 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004646 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004647 diag::warn_cxx98_compat_template_arg_extra_parens :
4648 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004649 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004650 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004651 }
4652
4653 Arg = Parens->getSubExpr();
4654 }
4655
John McCall7c454bb2011-07-15 05:09:51 +00004656 while (SubstNonTypeTemplateParmExpr *subst =
4657 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4658 Arg = subst->getReplacement()->IgnoreImpCasts();
4659
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004660 // A pointer-to-member constant written &Class::member.
4661 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004662 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004663 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4664 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004665 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004668 // A constant of pointer-to-member type.
4669 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4670 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4671 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004672 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004673 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004674 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004675 } else {
4676 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4677 Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4678 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004679 return Invalid;
4680 }
4681 }
4682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Craig Topperc3ec1492014-05-26 06:22:03 +00004684 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
Douglas Gregorccb07762009-02-11 19:52:55 +00004687 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004688 return S.Diag(Arg->getLocStart(),
4689 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004690 << Arg->getSourceRange();
4691
David Majnemer3ac84e62013-10-22 21:56:38 +00004692 if (isa<FieldDecl>(DRE->getDecl()) ||
4693 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4694 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004695 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004696 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004697 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4698 "Only non-static member pointers can make it here");
4699
4700 // Okay: this is the address of a non-static member, and therefore
4701 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004702 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004703 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004704 } else {
4705 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4706 Converted = TemplateArgument(D, /*isReferenceParam*/false);
4707 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004708 return Invalid;
4709 }
4710
4711 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004712 S.Diag(Arg->getLocStart(),
4713 diag::err_template_arg_not_pointer_to_member_form)
4714 << Arg->getSourceRange();
4715 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004716 return true;
4717}
4718
Douglas Gregord32e0282009-02-09 23:23:08 +00004719/// \brief Check a template argument against its corresponding
4720/// non-type template parameter.
4721///
Douglas Gregor463421d2009-03-03 04:44:36 +00004722/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004723/// If an error occurred, it returns ExprError(); otherwise, it
4724/// returns the converted template argument. \p
Douglas Gregor463421d2009-03-03 04:44:36 +00004725/// InstantiatedParamType is the type of the non-type template
4726/// parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004727ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4728 QualType InstantiatedParamType, Expr *Arg,
4729 TemplateArgument &Converted,
4730 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004731 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004732
Douglas Gregor86560402009-02-10 23:36:10 +00004733 // If either the parameter has a dependent type or the argument is
4734 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00004735 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4736 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004737 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004738 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004739 }
Douglas Gregor86560402009-02-10 23:36:10 +00004740
4741 // C++ [temp.arg.nontype]p5:
4742 // The following conversions are performed on each expression used
4743 // as a non-type template-argument. If a non-type
4744 // template-argument cannot be converted to the type of the
4745 // corresponding template-parameter then the program is
4746 // ill-formed.
Douglas Gregor463421d2009-03-03 04:44:36 +00004747 QualType ParamType = InstantiatedParamType;
Douglas Gregorb90df602010-06-16 00:17:44 +00004748 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004749 // C++11:
4750 // -- for a non-type template-parameter of integral or
4751 // enumeration type, conversions permitted in a converted
4752 // constant expression are applied.
4753 //
4754 // C++98:
4755 // -- for a non-type template-parameter of integral or
4756 // enumeration type, integral promotions (4.5) and integral
4757 // conversions (4.7) are applied.
4758
4759 if (CTAK == CTAK_Deduced &&
4760 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4761 // C++ [temp.deduct.type]p17:
4762 // If, in the declaration of a function template with a non-type
4763 // template-parameter, the non-type template-parameter is used
4764 // in an expression in the function parameter-list and, if the
4765 // corresponding template-argument is deduced, the
4766 // template-argument type shall match the type of the
4767 // template-parameter exactly, except that a template-argument
4768 // deduced from an array bound may be of any integral type.
4769 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4770 << Arg->getType().getUnqualifiedType()
4771 << ParamType.getUnqualifiedType();
4772 Diag(Param->getLocation(), diag::note_template_param_here);
4773 return ExprError();
4774 }
4775
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004776 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004777 // We can't check arbitrary value-dependent arguments.
4778 // FIXME: If there's no viable conversion to the template parameter type,
4779 // we should be able to diagnose that prior to instantiation.
4780 if (Arg->isValueDependent()) {
4781 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004782 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00004783 }
4784
4785 // C++ [temp.arg.nontype]p1:
4786 // A template-argument for a non-type, non-template template-parameter
4787 // shall be one of:
4788 //
4789 // -- for a non-type template-parameter of integral or enumeration
4790 // type, a converted constant expression of the type of the
4791 // template-parameter; or
4792 llvm::APSInt Value;
4793 ExprResult ArgResult =
4794 CheckConvertedConstantExpression(Arg, ParamType, Value,
4795 CCEK_TemplateArg);
4796 if (ArgResult.isInvalid())
4797 return ExprError();
4798
4799 // Widen the argument value to sizeof(parameter type). This is almost
4800 // always a no-op, except when the parameter type is bool. In
4801 // that case, this may extend the argument from 1 bit to 8 bits.
4802 QualType IntegerType = ParamType;
4803 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4804 IntegerType = Enum->getDecl()->getIntegerType();
4805 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4806
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004807 Converted = TemplateArgument(Context, Value,
4808 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00004809 return ArgResult;
4810 }
4811
Richard Smith08b12f12011-10-27 22:11:44 +00004812 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4813 if (ArgResult.isInvalid())
4814 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004815 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00004816
4817 QualType ArgType = Arg->getType();
4818
Douglas Gregor86560402009-02-10 23:36:10 +00004819 // C++ [temp.arg.nontype]p1:
4820 // A template-argument for a non-type, non-template
4821 // template-parameter shall be one of:
4822 //
4823 // -- an integral constant-expression of integral or enumeration
4824 // type; or
4825 // -- the name of a non-type template-parameter; or
4826 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004827 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00004828 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004829 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004830 diag::err_template_arg_not_integral_or_enumeral)
4831 << ArgType << Arg->getSourceRange();
4832 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004833 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00004834 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00004835 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4836 QualType T;
4837
4838 public:
4839 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00004840
4841 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4842 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00004843 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4844 }
4845 } Diagnoser(ArgType);
4846
4847 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004848 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00004849 if (!Arg)
4850 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004851 }
4852
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004853 // From here on out, all we care about are the unqualified forms
4854 // of the parameter and argument types.
4855 ParamType = ParamType.getUnqualifiedType();
4856 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00004857
4858 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00004859 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00004860 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00004861 } else if (ParamType->isBooleanType()) {
4862 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004863 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00004864 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4865 !ParamType->isEnumeralType()) {
4866 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004867 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00004868 } else {
4869 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004870 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004871 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00004872 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00004873 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004874 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004875 }
4876
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004877 // Add the value of this argument to the list of converted
4878 // arguments. We use the bitwidth and signedness of the template
4879 // parameter.
4880 if (Arg->isValueDependent()) {
4881 // The argument is value-dependent. Create a new
4882 // TemplateArgument with the converted expression.
4883 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004884 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004885 }
4886
Douglas Gregor52aba872009-03-14 00:20:21 +00004887 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00004888 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004889 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00004890
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004891 if (ParamType->isBooleanType()) {
4892 // Value must be zero or one.
4893 Value = Value != 0;
4894 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4895 if (Value.getBitWidth() != AllowedBits)
4896 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004897 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004898 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004899 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004900
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004902 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00004903 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00004904 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004905 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004906 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004907
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004908 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004909 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004910 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004911 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004912 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4913 << Arg->getSourceRange();
4914 Diag(Param->getLocation(), diag::note_template_param_here);
4915 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004916
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004917 // Complain if we overflowed the template parameter's type.
4918 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004919 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004920 RequiredBits = OldValue.getActiveBits();
4921 else if (OldValue.isUnsigned())
4922 RequiredBits = OldValue.getActiveBits() + 1;
4923 else
4924 RequiredBits = OldValue.getMinSignedBits();
4925 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004926 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004927 diag::warn_template_arg_too_large)
4928 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4929 << Arg->getSourceRange();
4930 Diag(Param->getLocation(), diag::note_template_param_here);
4931 }
Douglas Gregor52aba872009-03-14 00:20:21 +00004932 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004933
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004934 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00004935 ParamType->isEnumeralType()
4936 ? Context.getCanonicalType(ParamType)
4937 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004938 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00004939 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004940
Richard Smith08b12f12011-10-27 22:11:44 +00004941 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00004942 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4943
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004944 // Handle pointer-to-function, reference-to-function, and
4945 // pointer-to-member-function all in (roughly) the same way.
4946 if (// -- For a non-type template-parameter of type pointer to
4947 // function, only the function-to-pointer conversion (4.3) is
4948 // applied. If the template-argument represents a set of
4949 // overloaded functions (or a pointer to such), the matching
4950 // function is selected from the set (13.4).
4951 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004952 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004953 // -- For a non-type template-parameter of type reference to
4954 // function, no conversions apply. If the template-argument
4955 // represents a set of overloaded functions, the matching
4956 // function is selected from the set (13.4).
4957 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004958 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004959 // -- For a non-type template-parameter of type pointer to
4960 // member function, no conversions apply. If the
4961 // template-argument represents a set of overloaded member
4962 // functions, the matching member function is selected from
4963 // the set (13.4).
4964 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004965 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004966 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004967
Douglas Gregor064fdb22010-04-14 23:11:21 +00004968 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00004970 true,
4971 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004972 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00004973 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00004974
4975 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4976 ArgType = Arg->getType();
4977 } else
John Wiegley01296292011-04-08 18:41:53 +00004978 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
John Wiegley01296292011-04-08 18:41:53 +00004981 if (!ParamType->isMemberPointerType()) {
4982 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4983 ParamType,
4984 Arg, Converted))
4985 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004986 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00004987 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004988
Douglas Gregor20fdef32012-04-10 17:08:25 +00004989 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4990 Converted))
John Wiegley01296292011-04-08 18:41:53 +00004991 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004992 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004993 }
4994
Chris Lattner696197c2009-02-20 21:37:53 +00004995 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004996 // -- for a non-type template-parameter of type pointer to
4997 // object, qualification conversions (4.4) and the
4998 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00004999 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005000 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005001 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005002
John Wiegley01296292011-04-08 18:41:53 +00005003 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5004 ParamType,
5005 Arg, Converted))
5006 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005007 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005008 }
Mike Stump11289f42009-09-09 15:08:12 +00005009
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005010 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005011 // -- For a non-type template-parameter of type reference to
5012 // object, no conversions apply. The type referred to by the
5013 // reference may be more cv-qualified than the (otherwise
5014 // identical) type of the template-argument. The
5015 // template-parameter is bound directly to the
5016 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005017 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005018 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005019
Douglas Gregor064fdb22010-04-14 23:11:21 +00005020 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005021 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5022 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005023 true,
5024 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005025 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005026 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005027
5028 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5029 ArgType = Arg->getType();
5030 } else
John Wiegley01296292011-04-08 18:41:53 +00005031 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033
John Wiegley01296292011-04-08 18:41:53 +00005034 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5035 ParamType,
5036 Arg, Converted))
5037 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005038 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005039 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005040
Douglas Gregor20fdef32012-04-10 17:08:25 +00005041 // Deal with parameters of type std::nullptr_t.
5042 if (ParamType->isNullPtrType()) {
5043 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5044 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005045 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005046 }
5047
5048 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5049 case NPV_NotNullPointer:
5050 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5051 << Arg->getType() << ParamType;
5052 Diag(Param->getLocation(), diag::note_template_param_here);
5053 return ExprError();
5054
5055 case NPV_Error:
5056 return ExprError();
5057
5058 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005059 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00005060 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005061 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005062 }
5063 }
5064
Douglas Gregor0e558532009-02-11 16:16:59 +00005065 // -- For a non-type template-parameter of type pointer to data
5066 // member, qualification conversions (4.4) are applied.
5067 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5068
Douglas Gregor20fdef32012-04-10 17:08:25 +00005069 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5070 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005071 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005072 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005073}
5074
5075/// \brief Check a template argument against its corresponding
5076/// template template parameter.
5077///
5078/// This routine implements the semantics of C++ [temp.arg.template].
5079/// It returns true if an error occurred, and false otherwise.
5080bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005081 const TemplateArgumentLoc &Arg,
5082 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005083 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005084 TemplateDecl *Template = Name.getAsTemplateDecl();
5085 if (!Template) {
5086 // Any dependent template name is fine.
5087 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5088 return false;
5089 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005090
Richard Smith3f1b5d02011-05-05 21:57:07 +00005091 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005092 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005093 // the name of a class template or an alias template, expressed as an
5094 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005095 // primary class templates are considered when matching the
5096 // template template argument with the corresponding parameter;
5097 // partial specializations are not considered even if their
5098 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005099 //
5100 // Note that we also allow template template parameters here, which
5101 // will happen when we are dealing with, e.g., class template
5102 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005103 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005104 !isa<TemplateTemplateParmDecl>(Template) &&
5105 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005106 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005107 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005108 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005109 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005110 << Template;
5111 }
5112
Richard Smith1fde8ec2012-09-07 02:06:42 +00005113 TemplateParameterList *Params = Param->getTemplateParameters();
5114 if (Param->isExpandedParameterPack())
5115 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5116
Douglas Gregor85e0f662009-02-10 00:24:35 +00005117 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005118 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005119 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005120 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005121 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005122}
5123
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005124/// \brief Given a non-type template argument that refers to a
5125/// declaration and the type of its corresponding non-type template
5126/// parameter, produce an expression that properly refers to that
5127/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005128ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005129Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5130 QualType ParamType,
5131 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005132 // C++ [temp.param]p8:
5133 //
5134 // A non-type template-parameter of type "array of T" or
5135 // "function returning T" is adjusted to be of type "pointer to
5136 // T" or "pointer to function returning T", respectively.
5137 if (ParamType->isArrayType())
5138 ParamType = Context.getArrayDecayedType(ParamType);
5139 else if (ParamType->isFunctionType())
5140 ParamType = Context.getPointerType(ParamType);
5141
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005142 // For a NULL non-type template argument, return nullptr casted to the
5143 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005144 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005145 return ImpCastExprToType(
5146 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5147 ParamType,
5148 ParamType->getAs<MemberPointerType>()
5149 ? CK_NullToMemberPointer
5150 : CK_NullToPointer);
5151 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005152 assert(Arg.getKind() == TemplateArgument::Declaration &&
5153 "Only declaration template arguments permitted here");
5154
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005155 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5156
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005158 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5159 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005160 // If the value is a class member, we might have a pointer-to-member.
5161 // Determine whether the non-type template template parameter is of
5162 // pointer-to-member type. If so, we need to build an appropriate
5163 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5164 // would refer to the member itself.
5165 if (ParamType->isMemberPointerType()) {
5166 QualType ClassType
5167 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5168 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005169 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005170 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005171 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005172 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005173
5174 // The actual value-ness of this is unimportant, but for
5175 // internal consistency's sake, references to instance methods
5176 // are r-values.
5177 ExprValueKind VK = VK_LValue;
5178 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5179 VK = VK_RValue;
5180
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005181 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005182 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005183 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005184 Loc,
5185 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005186 if (RefExpr.isInvalid())
5187 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005188
John McCalle3027922010-08-25 11:45:40 +00005189 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005190
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005191 // We might need to perform a trailing qualification conversion, since
5192 // the element type on the parameter could be more qualified than the
5193 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005194 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005195 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005196 ParamType.getUnqualifiedType(), false,
5197 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005198 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005200 assert(!RefExpr.isInvalid() &&
5201 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005202 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005203 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005204 }
5205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005207 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005208
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005209 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005210 // When the non-type template parameter is a pointer, take the
5211 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005212 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005213 if (RefExpr.isInvalid())
5214 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005215
5216 if (T->isFunctionType() || T->isArrayType()) {
5217 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005218 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005219 if (RefExpr.isInvalid())
5220 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005221
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005222 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005224
Douglas Gregorb242683d2010-04-01 18:32:35 +00005225 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005226 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005227 }
5228
John McCall7decc9e2010-11-18 06:31:45 +00005229 ExprValueKind VK = VK_RValue;
5230
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005231 // If the non-type template parameter has reference type, qualify the
5232 // resulting declaration reference with the extra qualifiers on the
5233 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005234 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5235 VK = VK_LValue;
5236 T = Context.getQualifiedType(T,
5237 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005238 } else if (isa<FunctionDecl>(VD)) {
5239 // References to functions are always lvalues.
5240 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005242
John McCall7decc9e2010-11-18 06:31:45 +00005243 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005244}
5245
5246/// \brief Construct a new expression that refers to the given
5247/// integral template argument with the given source-location
5248/// information.
5249///
5250/// This routine takes care of the mapping from an integral template
5251/// argument (which may have any integral type) to the appropriate
5252/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005254Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5255 SourceLocation Loc) {
5256 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005257 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005258 QualType OrigT = Arg.getIntegralType();
5259
5260 // If this is an enum type that we're instantiating, we need to use an integer
5261 // type the same size as the enumerator. We don't want to build an
5262 // IntegerLiteral with enum type. The integer type of an enum type can be of
5263 // any integral type with C++11 enum classes, make sure we create the right
5264 // type of literal for it.
5265 QualType T = OrigT;
5266 if (const EnumType *ET = OrigT->getAs<EnumType>())
5267 T = ET->getDecl()->getIntegerType();
5268
5269 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005270 if (T->isAnyCharacterType()) {
5271 CharacterLiteral::CharacterKind Kind;
5272 if (T->isWideCharType())
5273 Kind = CharacterLiteral::Wide;
5274 else if (T->isChar16Type())
5275 Kind = CharacterLiteral::UTF16;
5276 else if (T->isChar32Type())
5277 Kind = CharacterLiteral::UTF32;
5278 else
5279 Kind = CharacterLiteral::Ascii;
5280
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005281 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5282 Kind, T, Loc);
5283 } else if (T->isBooleanType()) {
5284 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5285 T, Loc);
5286 } else if (T->isNullPtrType()) {
5287 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5288 } else {
5289 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005290 }
5291
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005292 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005293 // FIXME: This is a hack. We need a better way to handle substituted
5294 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005295 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5296 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005297 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005298 Loc, Loc);
5299 }
5300
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005301 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005302}
5303
Douglas Gregor641040a2011-01-12 23:45:44 +00005304/// \brief Match two template parameters within template parameter lists.
5305static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5306 bool Complain,
5307 Sema::TemplateParameterListEqualKind Kind,
5308 SourceLocation TemplateArgLoc) {
5309 // Check the actual kind (type, non-type, template).
5310 if (Old->getKind() != New->getKind()) {
5311 if (Complain) {
5312 unsigned NextDiag = diag::err_template_param_different_kind;
5313 if (TemplateArgLoc.isValid()) {
5314 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5315 NextDiag = diag::note_template_param_different_kind;
5316 }
5317 S.Diag(New->getLocation(), NextDiag)
5318 << (Kind != Sema::TPL_TemplateMatch);
5319 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5320 << (Kind != Sema::TPL_TemplateMatch);
5321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005322
Douglas Gregor641040a2011-01-12 23:45:44 +00005323 return false;
5324 }
5325
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326 // Check that both are parameter packs are neither are parameter packs.
5327 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005328 // template template parameter, the template template parameter can have
5329 // a parameter pack where the template template argument does not.
5330 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5331 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5332 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005333 if (Complain) {
5334 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5335 if (TemplateArgLoc.isValid()) {
5336 S.Diag(TemplateArgLoc,
5337 diag::err_template_arg_template_params_mismatch);
5338 NextDiag = diag::note_template_parameter_pack_non_pack;
5339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005340
Douglas Gregor641040a2011-01-12 23:45:44 +00005341 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5342 : isa<NonTypeTemplateParmDecl>(New)? 1
5343 : 2;
5344 S.Diag(New->getLocation(), NextDiag)
5345 << ParamKind << New->isParameterPack();
5346 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5347 << ParamKind << Old->isParameterPack();
5348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349
Douglas Gregor641040a2011-01-12 23:45:44 +00005350 return false;
5351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Douglas Gregor641040a2011-01-12 23:45:44 +00005353 // For non-type template parameters, check the type of the parameter.
5354 if (NonTypeTemplateParmDecl *OldNTTP
5355 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5356 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005357
Douglas Gregor641040a2011-01-12 23:45:44 +00005358 // If we are matching a template template argument to a template
5359 // template parameter and one of the non-type template parameter types
5360 // is dependent, then we must wait until template instantiation time
5361 // to actually compare the arguments.
5362 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5363 (OldNTTP->getType()->isDependentType() ||
5364 NewNTTP->getType()->isDependentType()))
5365 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005366
Douglas Gregor641040a2011-01-12 23:45:44 +00005367 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5368 if (Complain) {
5369 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5370 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005372 diag::err_template_arg_template_params_mismatch);
5373 NextDiag = diag::note_template_nontype_parm_different_type;
5374 }
5375 S.Diag(NewNTTP->getLocation(), NextDiag)
5376 << NewNTTP->getType()
5377 << (Kind != Sema::TPL_TemplateMatch);
5378 S.Diag(OldNTTP->getLocation(),
5379 diag::note_template_nontype_parm_prev_declaration)
5380 << OldNTTP->getType();
5381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005382
Douglas Gregor641040a2011-01-12 23:45:44 +00005383 return false;
5384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Douglas Gregor641040a2011-01-12 23:45:44 +00005386 return true;
5387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005388
Douglas Gregor641040a2011-01-12 23:45:44 +00005389 // For template template parameters, check the template parameter types.
5390 // The template parameter lists of template template
5391 // parameters must agree.
5392 if (TemplateTemplateParmDecl *OldTTP
5393 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005394 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005395 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5396 OldTTP->getTemplateParameters(),
5397 Complain,
5398 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005399 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005400 : Kind),
5401 TemplateArgLoc);
5402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005403
Douglas Gregor641040a2011-01-12 23:45:44 +00005404 return true;
5405}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005406
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005407/// \brief Diagnose a known arity mismatch when comparing template argument
5408/// lists.
5409static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005410void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005411 TemplateParameterList *New,
5412 TemplateParameterList *Old,
5413 Sema::TemplateParameterListEqualKind Kind,
5414 SourceLocation TemplateArgLoc) {
5415 unsigned NextDiag = diag::err_template_param_list_different_arity;
5416 if (TemplateArgLoc.isValid()) {
5417 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5418 NextDiag = diag::note_template_param_list_different_arity;
5419 }
5420 S.Diag(New->getTemplateLoc(), NextDiag)
5421 << (New->size() > Old->size())
5422 << (Kind != Sema::TPL_TemplateMatch)
5423 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5424 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5425 << (Kind != Sema::TPL_TemplateMatch)
5426 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5427}
5428
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005429/// \brief Determine whether the given template parameter lists are
5430/// equivalent.
5431///
Mike Stump11289f42009-09-09 15:08:12 +00005432/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005433/// source code as part of a new template declaration.
5434///
5435/// \param Old The old template parameter list, typically found via
5436/// name lookup of the template declared with this template parameter
5437/// list.
5438///
5439/// \param Complain If true, this routine will produce a diagnostic if
5440/// the template parameter lists are not equivalent.
5441///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005442/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005443///
5444/// \param TemplateArgLoc If this source location is valid, then we
5445/// are actually checking the template parameter list of a template
5446/// argument (New) against the template parameter list of its
5447/// corresponding template template parameter (Old). We produce
5448/// slightly different diagnostics in this scenario.
5449///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005450/// \returns True if the template parameter lists are equal, false
5451/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005452bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005453Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5454 TemplateParameterList *Old,
5455 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005456 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005457 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005458 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5459 if (Complain)
5460 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5461 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005462
5463 return false;
5464 }
5465
Douglas Gregor641040a2011-01-12 23:45:44 +00005466 // C++0x [temp.arg.template]p3:
5467 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005468 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005469 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005470 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005471 // template-parameter-list of P. [...]
5472 TemplateParameterList::iterator NewParm = New->begin();
5473 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005474 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005475 OldParmEnd = Old->end();
5476 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005477 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5478 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005479 if (NewParm == NewParmEnd) {
5480 if (Complain)
5481 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5482 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005483
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005484 return false;
5485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005486
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005487 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5488 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005489 return false;
5490
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005491 ++NewParm;
5492 continue;
5493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005495 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005496 // [...] When P's template- parameter-list contains a template parameter
5497 // pack (14.5.3), the template parameter pack will match zero or more
5498 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005499 // template-parameter-list of A with the same type and form as the
5500 // template parameter pack in P (ignoring whether those template
5501 // parameters are template parameter packs).
5502 for (; NewParm != NewParmEnd; ++NewParm) {
5503 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5504 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005506 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005509 // Make sure we exhausted all of the arguments.
5510 if (NewParm != NewParmEnd) {
5511 if (Complain)
5512 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5513 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005515 return false;
5516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005518 return true;
5519}
5520
5521/// \brief Check whether a template can be declared within this scope.
5522///
5523/// If the template declaration is valid in this scope, returns
5524/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005525bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005526Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005527 if (!S)
5528 return false;
5529
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005530 // Find the nearest enclosing declaration scope.
5531 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5532 (S->getFlags() & Scope::TemplateParamScope) != 0)
5533 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005534
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005535 // C++ [temp]p4:
5536 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005537 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005538 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005539 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005540 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005541
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005542 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005543 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005544
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005545 // C++ [temp]p2:
5546 // A template-declaration can appear only as a namespace scope or
5547 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005548 if (Ctx) {
5549 if (Ctx->isFileContext())
5550 return false;
5551 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5552 // C++ [temp.mem]p2:
5553 // A local class shall not have member templates.
5554 if (RD->isLocalClass())
5555 return Diag(TemplateParams->getTemplateLoc(),
5556 diag::err_template_inside_local_class)
5557 << TemplateParams->getSourceRange();
5558 else
5559 return false;
5560 }
5561 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005562
Mike Stump11289f42009-09-09 15:08:12 +00005563 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005564 diag::err_template_outside_namespace_or_class_scope)
5565 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005566}
Douglas Gregor67a65642009-02-17 23:15:12 +00005567
Douglas Gregor54888652009-10-07 00:13:32 +00005568/// \brief Determine what kind of template specialization the given declaration
5569/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005570static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005571 if (!D)
5572 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005574 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5575 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005576 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5577 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005578 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5579 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580
Douglas Gregor54888652009-10-07 00:13:32 +00005581 return TSK_Undeclared;
5582}
5583
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005584/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005585/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005586///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005587/// This routine determines whether a template specialization can be declared
5588/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005589///
5590/// \param S the semantic analysis object for which this check is being
5591/// performed.
5592///
5593/// \param Specialized the entity being specialized or instantiated, which
5594/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005595/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005596/// member class).
5597///
5598/// \param PrevDecl the previous declaration of this entity, if any.
5599///
5600/// \param Loc the location of the explicit specialization or instantiation of
5601/// this entity.
5602///
5603/// \param IsPartialSpecialization whether this is a partial specialization of
5604/// a class template.
5605///
Douglas Gregor54888652009-10-07 00:13:32 +00005606/// \returns true if there was an error that we cannot recover from, false
5607/// otherwise.
5608static bool CheckTemplateSpecializationScope(Sema &S,
5609 NamedDecl *Specialized,
5610 NamedDecl *PrevDecl,
5611 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005612 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005613 // Keep these "kind" numbers in sync with the %select statements in the
5614 // various diagnostics emitted by this routine.
5615 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005616 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005617 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005618 else if (isa<VarTemplateDecl>(Specialized))
5619 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005620 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005621 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005622 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005623 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005624 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005625 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005626 else if (isa<RecordDecl>(Specialized))
5627 EntityKind = 7;
5628 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5629 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005630 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005631 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005632 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005633 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005634 return true;
5635 }
5636
Douglas Gregorf47b9112009-02-25 22:02:03 +00005637 // C++ [temp.expl.spec]p2:
5638 // An explicit specialization shall be declared in the namespace
5639 // of which the template is a member, or, for member templates, in
5640 // the namespace of which the enclosing class or enclosing class
5641 // template is a member. An explicit specialization of a member
5642 // function, member class or static data member of a class
5643 // template shall be declared in the namespace of which the class
5644 // template is a member. Such a declaration may also be a
5645 // definition. If the declaration is not a definition, the
5646 // specialization may be defined later in the name- space in which
5647 // the explicit specialization was declared, or in a namespace
5648 // that encloses the one in which the explicit specialization was
5649 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005650 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005651 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005652 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005653 return true;
5654 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005655
Douglas Gregor40fb7442009-10-07 17:30:37 +00005656 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005657 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005658 // Do not warn for class scope explicit specialization during
5659 // instantiation, warning was already emitted during pattern
5660 // semantic analysis.
5661 if (!S.ActiveTemplateInstantiations.size())
5662 S.Diag(Loc, diag::ext_function_specialization_in_class)
5663 << Specialized;
5664 } else {
5665 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5666 << Specialized;
5667 return true;
5668 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005671 if (S.CurContext->isRecord() &&
5672 !S.CurContext->Equals(Specialized->getDeclContext())) {
5673 // Make sure that we're specializing in the right record context.
5674 // Otherwise, things can go horribly wrong.
5675 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5676 << Specialized;
5677 return true;
5678 }
5679
Douglas Gregore4b05162009-10-07 17:21:34 +00005680 // C++ [temp.class.spec]p6:
5681 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005682 // in any namespace scope in which its definition may be defined (14.5.1
5683 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005684 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005685 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005686 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005687
5688 // Make sure that this redeclaration (or definition) occurs in an enclosing
5689 // namespace.
5690 // Note that HandleDeclarator() performs this check for explicit
5691 // specializations of function templates, static data members, and member
5692 // functions, so we skip the check here for those kinds of entities.
5693 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5694 // Should we refactor that check, so that it occurs later?
5695 if (!DC->Encloses(SpecializedContext) &&
5696 !(isa<FunctionTemplateDecl>(Specialized) ||
5697 isa<FunctionDecl>(Specialized) ||
5698 isa<VarTemplateDecl>(Specialized) ||
5699 isa<VarDecl>(Specialized))) {
5700 if (isa<TranslationUnitDecl>(SpecializedContext))
5701 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5702 << EntityKind << Specialized;
5703 else if (isa<NamespaceDecl>(SpecializedContext))
5704 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5705 << EntityKind << Specialized
5706 << cast<NamedDecl>(SpecializedContext);
5707 else
5708 llvm_unreachable("unexpected namespace context for specialization");
5709
5710 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5711 } else if ((!PrevDecl ||
5712 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5713 getTemplateSpecializationKind(PrevDecl) ==
5714 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005715 // C++ [temp.exp.spec]p2:
5716 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005718 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719 // An explicit specialization of a member function, member class or
5720 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005721 // namespace of which the class template is a member.
5722 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005723 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005725 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005726 // C++11 [temp.explicit]p3:
5727 // An explicit instantiation shall appear in an enclosing namespace of its
5728 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005729 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005730 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005731 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005732 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005733 "DC encloses TU but isn't in enclosing namespace set");
5734 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005735 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005736 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5737 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005738 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005739 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005740 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005741 Diag = diag::ext_template_spec_decl_out_of_scope;
5742 else
5743 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5744 S.Diag(Loc, Diag)
5745 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005747
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005748 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005749 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751
Douglas Gregorf47b9112009-02-25 22:02:03 +00005752 return false;
5753}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005754
Richard Smith6056d5e2014-02-09 00:54:43 +00005755static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5756 if (!E->isInstantiationDependent())
5757 return SourceLocation();
5758 DependencyChecker Checker(Depth);
5759 Checker.TraverseStmt(E);
5760 if (Checker.Match && Checker.MatchLoc.isInvalid())
5761 return E->getSourceRange();
5762 return Checker.MatchLoc;
5763}
5764
5765static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5766 if (!TL.getType()->isDependentType())
5767 return SourceLocation();
5768 DependencyChecker Checker(Depth);
5769 Checker.TraverseTypeLoc(TL);
5770 if (Checker.Match && Checker.MatchLoc.isInvalid())
5771 return TL.getSourceRange();
5772 return Checker.MatchLoc;
5773}
5774
Larisse Voufo39a1e502013-08-06 01:03:05 +00005775/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005776/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005777static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005778 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5779 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005780 for (unsigned I = 0; I != NumArgs; ++I) {
5781 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005782 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005783 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5784 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005785 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005786
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005787 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005789
Eli Friedmanb826a002012-09-26 02:36:12 +00005790 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005791 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005792
5793 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005794
Douglas Gregor98318c22011-01-03 21:37:45 +00005795 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005796 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5797 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005798
5799 // Strip off any implicit casts we added as part of type checking.
5800 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5801 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005802
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005803 // C++ [temp.class.spec]p8:
5804 // A non-type argument is non-specialized if it is the name of a
5805 // non-type parameter. All other non-type arguments are
5806 // specialized.
5807 //
5808 // Below, we check the two conditions that only apply to
5809 // specialized non-type arguments, so skip any non-specialized
5810 // arguments.
5811 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00005812 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005813 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005814
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005815 // C++ [temp.class.spec]p9:
5816 // Within the argument list of a class template partial
5817 // specialization, the following restrictions apply:
5818 // -- A partially specialized non-type argument expression
5819 // shall not involve a template parameter of the partial
5820 // specialization except when the argument expression is a
5821 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00005822 SourceRange ParamUseRange =
5823 findTemplateParameter(Param->getDepth(), ArgExpr);
5824 if (ParamUseRange.isValid()) {
5825 if (IsDefaultArgument) {
5826 S.Diag(TemplateNameLoc,
5827 diag::err_dependent_non_type_arg_in_partial_spec);
5828 S.Diag(ParamUseRange.getBegin(),
5829 diag::note_dependent_non_type_default_arg_in_partial_spec)
5830 << ParamUseRange;
5831 } else {
5832 S.Diag(ParamUseRange.getBegin(),
5833 diag::err_dependent_non_type_arg_in_partial_spec)
5834 << ParamUseRange;
5835 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005836 return true;
5837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005838
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005839 // -- The type of a template parameter corresponding to a
5840 // specialized non-type argument shall not be dependent on a
5841 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00005842 //
5843 // FIXME: We need to delay this check until instantiation in some cases:
5844 //
5845 // template<template<typename> class X> struct A {
5846 // template<typename T, X<T> N> struct B;
5847 // template<typename T> struct B<T, 0>;
5848 // };
5849 // template<typename> using X = int;
5850 // A<X>::B<int, 0> b;
5851 ParamUseRange = findTemplateParameter(
5852 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
5853 if (ParamUseRange.isValid()) {
5854 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
5855 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5856 << Param->getType() << ParamUseRange;
5857 S.Diag(Param->getLocation(), diag::note_template_param_here)
5858 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005859 return true;
5860 }
5861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005863 return false;
5864}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005865
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005866/// \brief Check the non-type template arguments of a class template
5867/// partial specialization according to C++ [temp.class.spec]p9.
5868///
Richard Smith6056d5e2014-02-09 00:54:43 +00005869/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005870/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00005871/// template.
5872/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00005873/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00005874/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005875///
Richard Smith6056d5e2014-02-09 00:54:43 +00005876/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005877static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005878 Sema &S, SourceLocation TemplateNameLoc,
5879 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005880 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005881 const TemplateArgument *ArgList = TemplateArgs.data();
5882
5883 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5884 NonTypeTemplateParmDecl *Param
5885 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5886 if (!Param)
5887 continue;
5888
Richard Smith6056d5e2014-02-09 00:54:43 +00005889 if (CheckNonTypeTemplatePartialSpecializationArgs(
5890 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005891 return true;
5892 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005893
5894 return false;
5895}
5896
John McCall48871652010-08-21 09:40:31 +00005897DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00005898Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5899 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00005900 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005901 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00005902 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00005903 AttributeList *Attr,
5904 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00005905 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00005906
Richard Smith4b55a9c2014-04-17 03:29:33 +00005907 CXXScopeSpec &SS = TemplateId.SS;
5908
Abramo Bagnara60804e12011-03-18 15:16:37 +00005909 // NOTE: KWLoc is the location of the tag keyword. This will instead
5910 // store the location of the outermost template keyword in the declaration.
5911 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00005912 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
5913 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
5914 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
5915 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00005916
Douglas Gregor67a65642009-02-17 23:15:12 +00005917 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00005918 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00005919 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00005920 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5921
5922 if (!ClassTemplate) {
5923 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005924 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00005925 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5926 return true;
5927 }
Douglas Gregor67a65642009-02-17 23:15:12 +00005928
Douglas Gregor5c0405d2009-10-07 22:35:40 +00005929 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00005930 bool isPartialSpecialization = false;
5931
Douglas Gregorf47b9112009-02-25 22:02:03 +00005932 // Check the validity of the template headers that introduce this
5933 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00005934 // FIXME: We probably shouldn't complain about these headers for
5935 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005936 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00005937 TemplateParameterList *TemplateParams =
5938 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00005939 KWLoc, TemplateNameLoc, SS, &TemplateId,
5940 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
5941 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005942 if (Invalid)
5943 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005944
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005945 if (TemplateParams && TemplateParams->size() > 0) {
5946 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005947
Douglas Gregorec9518b2010-12-21 08:14:57 +00005948 if (TUK == TUK_Friend) {
5949 Diag(KWLoc, diag::err_partial_specialization_friend)
5950 << SourceRange(LAngleLoc, RAngleLoc);
5951 return true;
5952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005953
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005954 // C++ [temp.class.spec]p10:
5955 // The template parameter list of a specialization shall not
5956 // contain default template argument values.
5957 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5958 Decl *Param = TemplateParams->getParam(I);
5959 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5960 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00005961 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005962 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00005963 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005964 }
5965 } else if (NonTypeTemplateParmDecl *NTTP
5966 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5967 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00005968 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005969 diag::err_default_arg_in_partial_spec)
5970 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00005971 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005972 }
5973 } else {
5974 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005975 if (TTP->hasDefaultArgument()) {
5976 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005977 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005978 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00005979 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00005980 }
5981 }
5982 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005983 } else if (TemplateParams) {
5984 if (TUK == TUK_Friend)
5985 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00005986 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005987 SourceRange(TemplateParams->getTemplateLoc(),
5988 TemplateParams->getRAngleLoc()))
5989 << SourceRange(LAngleLoc, RAngleLoc);
5990 else
5991 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00005992 } else {
5993 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00005994 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005995
Douglas Gregor67a65642009-02-17 23:15:12 +00005996 // Check that the specialization uses the same tag kind as the
5997 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00005998 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5999 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006000 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006001 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00006002 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006003 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006004 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006005 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006006 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006007 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006008 diag::note_previous_use);
6009 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6010 }
6011
Douglas Gregorc40290e2009-03-09 23:48:35 +00006012 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006013 TemplateArgumentListInfo TemplateArgs =
6014 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006015
Douglas Gregor14406932011-01-03 20:35:03 +00006016 // Check for unexpanded parameter packs in any of the template arguments.
6017 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006019 UPPC_PartialSpecialization))
6020 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021
Douglas Gregor67a65642009-02-17 23:15:12 +00006022 // Check that the template argument list is well-formed for this
6023 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006024 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006025 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6026 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006027 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006028
Douglas Gregor2373c592009-05-31 09:31:02 +00006029 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006030 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006031 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006032 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006033 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6034 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006035 return true;
6036
Douglas Gregor678d76c2011-07-01 01:22:09 +00006037 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006038 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006039 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006041 TemplateArgs.size(),
6042 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006043 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6044 << ClassTemplate->getDeclName();
6045 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006046 }
6047 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006048
Craig Topperc3ec1492014-05-26 06:22:03 +00006049 void *InsertPos = nullptr;
6050 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006051
6052 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006053 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00006054 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006055 = ClassTemplate->findPartialSpecialization(Converted.data(),
6056 Converted.size(),
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006057 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006058 else
6059 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006060 = ClassTemplate->findSpecialization(Converted.data(),
6061 Converted.size(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006062
Craig Topperc3ec1492014-05-26 06:22:03 +00006063 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006064
Douglas Gregorf47b9112009-02-25 22:02:03 +00006065 // Check whether we can declare a class template specialization in
6066 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006067 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006068 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6069 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006070 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006071 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006072
Douglas Gregor15301382009-07-30 17:40:51 +00006073 // The canonical type
6074 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006075 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006076 // Build the canonical type that describes the converted template
6077 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006078 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6079 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006080 Converted.data(),
6081 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006082
6083 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006084 ClassTemplate->getInjectedClassNameSpecialization())) {
6085 // C++ [temp.class.spec]p9b3:
6086 //
6087 // -- The argument list of the specialization shall not be identical
6088 // to the implicit argument list of the primary template.
6089 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006090 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006091 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006092 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6093 ClassTemplate->getIdentifier(),
6094 TemplateNameLoc,
6095 Attr,
6096 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006097 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006098 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006099 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006100 }
Douglas Gregor15301382009-07-30 17:40:51 +00006101
Douglas Gregor2373c592009-05-31 09:31:02 +00006102 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006103 ClassTemplatePartialSpecializationDecl *PrevPartial
6104 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006105 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006106 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006107 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006108 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006109 TemplateParams,
6110 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006111 Converted.data(),
6112 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006113 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006114 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006115 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006116 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006117 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006118 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006119 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006120 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006121 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006122
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006123 if (!PrevPartial)
6124 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006125 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006126
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006127 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006128 // template specialization, make a note of that.
6129 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6130 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006131
Douglas Gregor91772d12009-06-13 00:26:55 +00006132 // Check that all of the template parameters of the class template
6133 // partial specialization are deducible from the template
6134 // arguments. If not, this class template partial specialization
6135 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006136 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006137 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006138 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006139 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006140
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006141 if (!DeducibleParams.all()) {
6142 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006143 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006144 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006145 << SourceRange(TemplateNameLoc, RAngleLoc);
6146 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6147 if (!DeducibleParams[I]) {
6148 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6149 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006150 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006151 diag::note_partial_spec_unused_parameter)
6152 << Param->getDeclName();
6153 else
Mike Stump11289f42009-09-09 15:08:12 +00006154 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006155 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006156 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006157 }
6158 }
6159 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006160 } else {
6161 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006162 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006163 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006164 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006165 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006166 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006167 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006168 Converted.data(),
6169 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006170 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006171 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006172 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006173 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006174 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006175 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006176 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006177
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006178 if (!PrevDecl)
6179 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006180
6181 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006182 }
6183
Douglas Gregor06db9f52009-10-12 20:18:28 +00006184 // C++ [temp.expl.spec]p6:
6185 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006186 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006187 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006188 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006189 // use occurs; no diagnostic is required.
6190 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006191 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006192 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006193 // Is there any previous explicit specialization declaration?
6194 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6195 Okay = true;
6196 break;
6197 }
6198 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006199
Douglas Gregorc854c662010-02-26 06:03:23 +00006200 if (!Okay) {
6201 SourceRange Range(TemplateNameLoc, RAngleLoc);
6202 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6203 << Context.getTypeDeclType(Specialization) << Range;
6204
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006205 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006206 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006207 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006208 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006209 return true;
6210 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006212
Douglas Gregor2208a292009-09-26 20:57:03 +00006213 // If this is not a friend, note that this is an explicit specialization.
6214 if (TUK != TUK_Friend)
6215 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006216
6217 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006218 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00006219 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006220 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006221 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006222 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006223 Diag(Def->getLocation(), diag::note_previous_definition);
6224 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006225 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006226 }
6227 }
6228
John McCall659a3372010-12-18 03:30:47 +00006229 if (Attr)
6230 ProcessDeclAttributeList(S, Specialization, Attr);
6231
Richard Smith034b94a2012-08-17 03:20:55 +00006232 // Add alignment attributes if necessary; these attributes are checked when
6233 // the ASTContext lays out the structure.
6234 if (TUK == TUK_Definition) {
6235 AddAlignmentAttributesForRecord(Specialization);
6236 AddMsStructLayoutForRecord(Specialization);
6237 }
6238
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006239 if (ModulePrivateLoc.isValid())
6240 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6241 << (isPartialSpecialization? 1 : 0)
6242 << FixItHint::CreateRemoval(ModulePrivateLoc);
6243
Douglas Gregord56a91e2009-02-26 22:19:44 +00006244 // Build the fully-sugared type for this class template
6245 // specialization as the user wrote in the specialization
6246 // itself. This means that we'll pretty-print the type retrieved
6247 // from the specialization's declaration the way that the user
6248 // actually wrote the specialization, rather than formatting the
6249 // name based on the "canonical" representation used to store the
6250 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006251 TypeSourceInfo *WrittenTy
6252 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6253 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006254 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006255 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006256 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006257 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006258
Douglas Gregor1e249f82009-02-25 22:18:32 +00006259 // C++ [temp.expl.spec]p9:
6260 // A template explicit specialization is in the scope of the
6261 // namespace in which the template was defined.
6262 //
6263 // We actually implement this paragraph where we set the semantic
6264 // context (in the creation of the ClassTemplateSpecializationDecl),
6265 // but we also maintain the lexical context where the actual
6266 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006267 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006268
Douglas Gregor67a65642009-02-17 23:15:12 +00006269 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006270 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006271 Specialization->startDefinition();
6272
Douglas Gregor2208a292009-09-26 20:57:03 +00006273 if (TUK == TUK_Friend) {
6274 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6275 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006276 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006277 /*FIXME:*/KWLoc);
6278 Friend->setAccess(AS_public);
6279 CurContext->addDecl(Friend);
6280 } else {
6281 // Add the specialization into its lexical context, so that it can
6282 // be seen when iterating through the list of declarations in that
6283 // context. However, specializations are not found by name lookup.
6284 CurContext->addDecl(Specialization);
6285 }
John McCall48871652010-08-21 09:40:31 +00006286 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006287}
Douglas Gregor333489b2009-03-27 23:10:48 +00006288
John McCall48871652010-08-21 09:40:31 +00006289Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006290 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006291 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006292 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006293 ActOnDocumentableDecl(NewDecl);
6294 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006295}
6296
John McCall48871652010-08-21 09:40:31 +00006297Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006298 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006299 Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006300 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006301 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006302
Douglas Gregor17a7c122009-06-24 00:54:41 +00006303 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006304 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006305 }
Mike Stump11289f42009-09-09 15:08:12 +00006306
Douglas Gregor17a7c122009-06-24 00:54:41 +00006307 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006308
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006309 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006310 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006311 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006312 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006313}
6314
John McCall4f7ced62010-02-11 01:33:53 +00006315/// \brief Strips various properties off an implicit instantiation
6316/// that has just been explicitly specialized.
6317static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006318 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00006319
6320 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6321 FD->setInlineSpecified(false);
Jordan Rosea0a86be2013-03-08 22:25:36 +00006322
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006323 for (auto I : FD->params())
6324 I->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00006325 }
6326}
6327
Nico Webera8f80b32012-01-09 19:52:25 +00006328/// \brief Compute the diagnostic location for an explicit instantiation
6329// declaration or definition.
6330static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006331 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006332 // Explicit instantiations following a specialization have no effect and
6333 // hence no PointOfInstantiation. In that case, walk decl backwards
6334 // until a valid name loc is found.
6335 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006336 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6337 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006338 PrevDiagLoc = Prev->getLocation();
6339 }
6340 assert(PrevDiagLoc.isValid() &&
6341 "Explicit instantiation without point of instantiation?");
6342 return PrevDiagLoc;
6343}
6344
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006345/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006346/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006347/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006348/// new specialization/instantiation will have any effect.
6349///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006350/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006351/// instantiation.
6352///
6353/// \param NewTSK the kind of the new explicit specialization or instantiation.
6354///
6355/// \param PrevDecl the previous declaration of the entity.
6356///
6357/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6358///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006359/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006360/// declaration was instantiated (either implicitly or explicitly).
6361///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006362/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006363/// specialization or instantiation has no effect and should be ignored.
6364///
6365/// \returns true if there was an error that should prevent the introduction of
6366/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006367bool
6368Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6369 TemplateSpecializationKind NewTSK,
6370 NamedDecl *PrevDecl,
6371 TemplateSpecializationKind PrevTSK,
6372 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006373 bool &HasNoEffect) {
6374 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006375
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006376 switch (NewTSK) {
6377 case TSK_Undeclared:
6378 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006379 assert(
6380 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6381 "previous declaration must be implicit!");
6382 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006383
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006384 case TSK_ExplicitSpecialization:
6385 switch (PrevTSK) {
6386 case TSK_Undeclared:
6387 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006388 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006389 // explicitly specialized or has merely been mentioned without any
6390 // instantiation.
6391 return false;
6392
6393 case TSK_ImplicitInstantiation:
6394 if (PrevPointOfInstantiation.isInvalid()) {
6395 // The declaration itself has not actually been instantiated, so it is
6396 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006397 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006398 return false;
6399 }
6400 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006402 case TSK_ExplicitInstantiationDeclaration:
6403 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404 assert((PrevTSK == TSK_ImplicitInstantiation ||
6405 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006406 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006407
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006408 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006409 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006410 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006411 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006412 // implicit instantiation to take place, in every translation unit in
6413 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006414 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006415 // Is there any previous explicit specialization declaration?
6416 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6417 return false;
6418 }
6419
Douglas Gregor1d957a32009-10-27 18:42:08 +00006420 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006421 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006422 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006423 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006424
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006425 return true;
6426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006427
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006428 case TSK_ExplicitInstantiationDeclaration:
6429 switch (PrevTSK) {
6430 case TSK_ExplicitInstantiationDeclaration:
6431 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006432 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006433 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006434
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006435 case TSK_Undeclared:
6436 case TSK_ImplicitInstantiation:
6437 // We're explicitly instantiating something that may have already been
6438 // implicitly instantiated; that's fine.
6439 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006440
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006441 case TSK_ExplicitSpecialization:
6442 // C++0x [temp.explicit]p4:
6443 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006445 // specialization for that template, the explicit instantiation has no
6446 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006447 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006448 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006450 case TSK_ExplicitInstantiationDefinition:
6451 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452 // If an entity is the subject of both an explicit instantiation
6453 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006454 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006455 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006456 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006457
6458 // Explicit instantiations following a specialization have no effect and
6459 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6460 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006461 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6462 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006463 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006464 return false;
6465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006466
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006467 case TSK_ExplicitInstantiationDefinition:
6468 switch (PrevTSK) {
6469 case TSK_Undeclared:
6470 case TSK_ImplicitInstantiation:
6471 // We're explicitly instantiating something that may have already been
6472 // implicitly instantiated; that's fine.
6473 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006474
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006475 case TSK_ExplicitSpecialization:
6476 // C++ DR 259, C++0x [temp.explicit]p4:
6477 // For a given set of template parameters, if an explicit
6478 // instantiation of a template appears after a declaration of
6479 // an explicit specialization for that template, the explicit
6480 // instantiation has no effect.
6481 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006482 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006483 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006484 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006485 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006486 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6487 diag::ext_explicit_instantiation_after_specialization)
6488 << PrevDecl;
6489 Diag(PrevDecl->getLocation(),
6490 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006491 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006492 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006493
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006494 case TSK_ExplicitInstantiationDeclaration:
6495 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006496 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006497
6498 // C++0x [temp.explicit]p4:
6499 // For a given set of template parameters, if an explicit instantiation
6500 // of a template appears after a declaration of an explicit
6501 // specialization for that template, the explicit instantiation has no
6502 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006503 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006504 // Is there any previous explicit specialization declaration?
6505 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6506 HasNoEffect = true;
6507 break;
6508 }
6509 }
6510
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006511 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006513 case TSK_ExplicitInstantiationDefinition:
6514 // C++0x [temp.spec]p5:
6515 // For a given template and a given set of template-arguments,
6516 // - an explicit instantiation definition shall appear at most once
6517 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006518
6519 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6520 Diag(NewLoc, (getLangOpts().MSVCCompat)
6521 ? diag::warn_explicit_instantiation_duplicate
6522 : diag::err_explicit_instantiation_duplicate)
6523 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006524 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006525 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006526 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006528 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006530
David Blaikie83d382b2011-09-23 05:06:16 +00006531 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006532}
6533
John McCallb9c78482010-04-08 09:05:18 +00006534/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006535/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006536///
James Dennettf14a6e52012-06-15 22:23:43 +00006537/// The only possible way to get a dependent function template specialization
6538/// is with a friend declaration, like so:
6539///
6540/// \code
6541/// template \<class T> void foo(T);
6542/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006543/// friend void foo<>(T);
6544/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006545/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006546///
6547/// There really isn't any useful analysis we can do here, so we
6548/// just store the information.
6549bool
6550Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6551 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6552 LookupResult &Previous) {
6553 // Remove anything from Previous that isn't a function template in
6554 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006555 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006556 LookupResult::Filter F = Previous.makeFilter();
6557 while (F.hasNext()) {
6558 NamedDecl *D = F.next()->getUnderlyingDecl();
6559 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006560 !FDLookupContext->InEnclosingNamespaceSetOf(
6561 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006562 F.erase();
6563 }
6564 F.done();
6565
6566 // Should this be diagnosed here?
6567 if (Previous.empty()) return true;
6568
6569 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6570 ExplicitTemplateArgs);
6571 return false;
6572}
6573
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006574/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006575/// specialization.
6576///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006577/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006578/// explicit function template specialization. On successful completion,
6579/// the function declaration \p FD will become a function template
6580/// specialization.
6581///
6582/// \param FD the function declaration, which will be updated to become a
6583/// function template specialization.
6584///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006585/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6586/// if any. Note that this may be valid info even when 0 arguments are
6587/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6588/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006589///
Francois Pichet3a44e432011-07-08 06:21:47 +00006590/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006591/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006592bool Sema::CheckFunctionTemplateSpecialization(
6593 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6594 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006595 // The set of function template specializations that could match this
6596 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006597 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006598 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599
Sebastian Redl50c68252010-08-31 00:36:30 +00006600 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006601 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6602 I != E; ++I) {
6603 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6604 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006606 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006607 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6608 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006609 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610
Richard Smith574f4f62013-01-14 05:37:29 +00006611 // When matching a constexpr member function template specialization
6612 // against the primary template, we don't yet know whether the
6613 // specialization has an implicit 'const' (because we don't know whether
6614 // it will be a static member function until we know which template it
6615 // specializes), so adjust it now assuming it specializes this template.
6616 QualType FT = FD->getType();
6617 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006618 CXXMethodDecl *OldMD =
6619 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006620 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006621 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006622 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6623 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006624 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006625 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006626 }
6627 }
6628
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006629 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006630 // A trailing template-argument can be left unspecified in the
6631 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006632 // provided it can be deduced from the function argument type.
6633 // Perform template argument deduction to determine whether we may be
6634 // specializing this template.
6635 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006636 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006637 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006638 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6639 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6640 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006641 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006642 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006643 FailedCandidates.addCandidate()
6644 .set(FunTmpl->getTemplatedDecl(),
6645 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006646 (void)TDK;
6647 continue;
6648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006649
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006650 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006651 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006652 }
6653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006654
Douglas Gregor5de279c2009-09-26 03:41:46 +00006655 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006656 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006657 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006658 FD->getLocation(),
6659 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6660 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006661 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006662 PDiag(diag::note_function_template_spec_matched));
6663
John McCall58cc69d2010-01-27 01:50:18 +00006664 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006665 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006666
6667 // Ignore access information; it doesn't figure into redeclaration checking.
6668 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006669
6670 FunctionTemplateSpecializationInfo *SpecInfo
6671 = Specialization->getTemplateSpecializationInfo();
6672 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006673
6674 // Note: do not overwrite location info if previous template
6675 // specialization kind was explicit.
6676 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006677 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006678 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006679 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6680 // function can differ from the template declaration with respect to
6681 // the constexpr specifier.
6682 Specialization->setConstexpr(FD->isConstexpr());
6683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006684
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006685 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006686 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006687
6688 // If this is a friend declaration, then we're not really declaring
6689 // an explicit specialization.
6690 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006691
Douglas Gregor54888652009-10-07 00:13:32 +00006692 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006693 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006695 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006697 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006698 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006699
6700 // C++ [temp.expl.spec]p6:
6701 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006703 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006704 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006705 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006706 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006707 if (!isFriend &&
6708 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006709 TSK_ExplicitSpecialization,
6710 Specialization,
6711 SpecInfo->getTemplateSpecializationKind(),
6712 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006713 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006714 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006715
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006716 // Mark the prior declaration as an explicit specialization, so that later
6717 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006718 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006719 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006720 MarkUnusedFileScopedDecl(Specialization);
6721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006722
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006723 // Turn the given function declaration into a function template
6724 // specialization, with the template arguments from the previous
6725 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006726 // Take copies of (semantic and syntactic) template argument lists.
6727 const TemplateArgumentList* TemplArgs = new (Context)
6728 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006729 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006730 TemplArgs, /*InsertPos=*/nullptr,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006731 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006732 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006733
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006734 // The "previous declaration" for this function template specialization is
6735 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006736 Previous.clear();
6737 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006738 return false;
6739}
6740
Douglas Gregor86d142a2009-10-08 07:24:58 +00006741/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006742/// specialization.
6743///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006744/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006745/// explicit member function specialization. On successful completion,
6746/// the function declaration \p FD will become a member function
6747/// specialization.
6748///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006749/// \param Member the member declaration, which will be updated to become a
6750/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006751///
John McCall1f82f242009-11-18 22:49:29 +00006752/// \param Previous the set of declarations, one of which may be specialized
6753/// by this function specialization; the set will be modified to contain the
6754/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755bool
John McCall1f82f242009-11-18 22:49:29 +00006756Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006757 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006758
Douglas Gregor86d142a2009-10-08 07:24:58 +00006759 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00006760 NamedDecl *Instantiation = nullptr;
6761 NamedDecl *InstantiatedFrom = nullptr;
6762 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006763
John McCall1f82f242009-11-18 22:49:29 +00006764 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006765 // Nowhere to look anyway.
6766 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006767 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6768 I != E; ++I) {
6769 NamedDecl *D = (*I)->getUnderlyingDecl();
6770 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006771 QualType Adjusted = Function->getType();
6772 if (!hasExplicitCallingConv(Adjusted))
6773 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6774 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006775 Instantiation = Method;
6776 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006777 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006778 break;
6779 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006780 }
6781 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006782 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006783 VarDecl *PrevVar;
6784 if (Previous.isSingleResult() &&
6785 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006786 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006787 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006788 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006789 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006790 }
6791 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006792 CXXRecordDecl *PrevRecord;
6793 if (Previous.isSingleResult() &&
6794 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6795 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006796 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006797 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006798 }
Richard Smith7d137e32012-03-23 03:33:32 +00006799 } else if (isa<EnumDecl>(Member)) {
6800 EnumDecl *PrevEnum;
6801 if (Previous.isSingleResult() &&
6802 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6803 Instantiation = PrevEnum;
6804 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6805 MSInfo = PrevEnum->getMemberSpecializationInfo();
6806 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006808
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006809 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006810 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006811 // specializations are always out-of-line, the caller will complain about
6812 // this mismatch later.
6813 return false;
6814 }
John McCalle820e5e2010-04-13 20:37:33 +00006815
6816 // If this is a friend, just bail out here before we start turning
6817 // things into explicit specializations.
6818 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6819 // Preserve instantiation information.
6820 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6821 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6822 cast<CXXMethodDecl>(InstantiatedFrom),
6823 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6824 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6825 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6826 cast<CXXRecordDecl>(InstantiatedFrom),
6827 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6828 }
6829
6830 Previous.clear();
6831 Previous.addDecl(Instantiation);
6832 return false;
6833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006834
Douglas Gregor86d142a2009-10-08 07:24:58 +00006835 // Make sure that this is a specialization of a member.
6836 if (!InstantiatedFrom) {
6837 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6838 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006839 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6840 return true;
6841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006842
Douglas Gregor06db9f52009-10-12 20:18:28 +00006843 // C++ [temp.expl.spec]p6:
6844 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00006845 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006846 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006847 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006848 // use occurs; no diagnostic is required.
6849 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00006850
Abramo Bagnara8075c852010-06-12 07:44:57 +00006851 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00006852 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6853 TSK_ExplicitSpecialization,
6854 Instantiation,
6855 MSInfo->getTemplateSpecializationKind(),
6856 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006857 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006858 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006859
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006860 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00006862 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006863 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006864 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006865 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00006866
Douglas Gregor86d142a2009-10-08 07:24:58 +00006867 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006868 // the original declaration to note that it is an explicit specialization
6869 // (if it was previously an implicit instantiation). This latter step
6870 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00006871 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006872 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6873 if (InstantiationFunction->getTemplateSpecializationKind() ==
6874 TSK_ImplicitInstantiation) {
6875 InstantiationFunction->setTemplateSpecializationKind(
6876 TSK_ExplicitSpecialization);
6877 InstantiationFunction->setLocation(Member->getLocation());
6878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006879
Douglas Gregor86d142a2009-10-08 07:24:58 +00006880 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6881 cast<CXXMethodDecl>(InstantiatedFrom),
6882 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006883 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00006884 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006885 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6886 if (InstantiationVar->getTemplateSpecializationKind() ==
6887 TSK_ImplicitInstantiation) {
6888 InstantiationVar->setTemplateSpecializationKind(
6889 TSK_ExplicitSpecialization);
6890 InstantiationVar->setLocation(Member->getLocation());
6891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Larisse Voufo39a1e502013-08-06 01:03:05 +00006893 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
6894 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006895 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00006896 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006897 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6898 if (InstantiationClass->getTemplateSpecializationKind() ==
6899 TSK_ImplicitInstantiation) {
6900 InstantiationClass->setTemplateSpecializationKind(
6901 TSK_ExplicitSpecialization);
6902 InstantiationClass->setLocation(Member->getLocation());
6903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006904
Douglas Gregor86d142a2009-10-08 07:24:58 +00006905 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006906 cast<CXXRecordDecl>(InstantiatedFrom),
6907 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00006908 } else {
6909 assert(isa<EnumDecl>(Member) && "Only member enums remain");
6910 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6911 if (InstantiationEnum->getTemplateSpecializationKind() ==
6912 TSK_ImplicitInstantiation) {
6913 InstantiationEnum->setTemplateSpecializationKind(
6914 TSK_ExplicitSpecialization);
6915 InstantiationEnum->setLocation(Member->getLocation());
6916 }
6917
6918 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6919 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00006920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006921
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006922 // Save the caller the trouble of having to figure out which declaration
6923 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00006924 Previous.clear();
6925 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006926 return false;
6927}
6928
Douglas Gregore47f5a72009-10-14 23:41:34 +00006929/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006930///
6931/// \returns true if a serious error occurs, false otherwise.
6932static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00006933 SourceLocation InstLoc,
6934 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006935 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6936 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006938 if (CurContext->isRecord()) {
6939 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6940 << D;
6941 return true;
6942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Richard Smith050d2612011-10-18 02:28:33 +00006944 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006945 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00006946 // template. If the name declared in the explicit instantiation is an
6947 // unqualified name, the explicit instantiation shall appear in the
6948 // namespace where its template is declared or, if that namespace is inline
6949 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00006950 //
6951 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00006952 if (WasQualifiedName) {
6953 if (CurContext->Encloses(OrigContext))
6954 return false;
6955 } else {
6956 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6957 return false;
6958 }
6959
6960 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6961 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006963 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006964 diag::err_explicit_instantiation_out_of_scope :
6965 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00006966 << D << NS;
6967 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006969 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006970 diag::err_explicit_instantiation_unqualified_wrong_namespace :
6971 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6972 << D << NS;
6973 } else
6974 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006975 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006976 diag::err_explicit_instantiation_must_be_global :
6977 diag::warn_explicit_instantiation_must_be_global_0x)
6978 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00006979 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006980 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00006981}
6982
6983/// \brief Determine whether the given scope specifier has a template-id in it.
6984static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6985 if (!SS.isSet())
6986 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006987
Richard Smith050d2612011-10-18 02:28:33 +00006988 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00006990 // or a static data member of a class template specialization, the name of
6991 // the class template specialization in the qualified-id for the member
6992 // name shall be a simple-template-id.
6993 //
6994 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00006995 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
6996 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00006997 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00006998 if (isa<TemplateSpecializationType>(T))
6999 return true;
7000
7001 return false;
7002}
7003
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007004// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007005DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007006Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007007 SourceLocation ExternLoc,
7008 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007009 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007010 SourceLocation KWLoc,
7011 const CXXScopeSpec &SS,
7012 TemplateTy TemplateD,
7013 SourceLocation TemplateNameLoc,
7014 SourceLocation LAngleLoc,
7015 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007016 SourceLocation RAngleLoc,
7017 AttributeList *Attr) {
7018 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007019 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007020 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007021 // Check that the specialization uses the same tag kind as the
7022 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007023 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7024 assert(Kind != TTK_Enum &&
7025 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007026
7027 if (isa<TypeAliasTemplateDecl>(TD)) {
7028 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7029 Diag(TD->getTemplatedDecl()->getLocation(),
7030 diag::note_previous_use);
7031 return true;
7032 }
7033
7034 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7035
Douglas Gregord9034f02009-05-14 16:41:31 +00007036 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007037 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00007038 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007039 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007040 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007041 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007042 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007043 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007044 diag::note_previous_use);
7045 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7046 }
7047
Douglas Gregore47f5a72009-10-14 23:41:34 +00007048 // C++0x [temp.explicit]p2:
7049 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007050 // definition and an explicit instantiation declaration. An explicit
7051 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00007052 TemplateSpecializationKind TSK
7053 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7054 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007055
Douglas Gregora1f49972009-05-13 00:25:59 +00007056 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007057 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007058 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007059
7060 // Check that the template argument list is well-formed for this
7061 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007062 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007063 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7064 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007065 return true;
7066
Douglas Gregora1f49972009-05-13 00:25:59 +00007067 // Find the class template specialization declaration that
7068 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007069 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007070 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007071 = ClassTemplate->findSpecialization(Converted.data(),
7072 Converted.size(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007073
Abramo Bagnara8075c852010-06-12 07:44:57 +00007074 TemplateSpecializationKind PrevDecl_TSK
7075 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7076
Douglas Gregor54888652009-10-07 00:13:32 +00007077 // C++0x [temp.explicit]p2:
7078 // [...] An explicit instantiation shall appear in an enclosing
7079 // namespace of its template. [...]
7080 //
7081 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007082 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7083 SS.isSet()))
7084 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007085
Craig Topperc3ec1492014-05-26 06:22:03 +00007086 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007087
Abramo Bagnara8075c852010-06-12 07:44:57 +00007088 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007089 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007090 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007091 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007092 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007093 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007094 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007095
Abramo Bagnara8075c852010-06-12 07:44:57 +00007096 // Even though HasNoEffect == true means that this explicit instantiation
7097 // has no effect on semantics, we go on to put its syntax in the AST.
7098
7099 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7100 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007101 // Since the only prior class template specialization with these
7102 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007103 // declaration node as our own, updating the source location
7104 // for the template name to reflect our new declaration.
7105 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007106 Specialization = PrevDecl;
7107 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007108 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007109 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007110 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007111
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007112 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007113 // Create a new class template specialization declaration node for
7114 // this explicit specialization.
7115 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007116 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007117 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007118 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007119 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007120 Converted.data(),
7121 Converted.size(),
7122 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007123 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007124
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007125 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007126 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007127 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007128 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007129 }
7130
7131 // Build the fully-sugared type for this explicit instantiation as
7132 // the user wrote in the explicit instantiation itself. This means
7133 // that we'll pretty-print the type retrieved from the
7134 // specialization's declaration the way that the user actually wrote
7135 // the explicit instantiation, rather than formatting the name based
7136 // on the "canonical" representation used to store the template
7137 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007138 TypeSourceInfo *WrittenTy
7139 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7140 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007141 Context.getTypeDeclType(Specialization));
7142 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007143
Abramo Bagnara8075c852010-06-12 07:44:57 +00007144 // Set source locations for keywords.
7145 Specialization->setExternLoc(ExternLoc);
7146 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007147 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007148
Rafael Espindola0b062072012-01-03 06:04:21 +00007149 if (Attr)
7150 ProcessDeclAttributeList(S, Specialization, Attr);
7151
Abramo Bagnara8075c852010-06-12 07:44:57 +00007152 // Add the explicit instantiation into its lexical context. However,
7153 // since explicit instantiations are never found by name lookup, we
7154 // just put it into the declaration context directly.
7155 Specialization->setLexicalDeclContext(CurContext);
7156 CurContext->addDecl(Specialization);
7157
7158 // Syntax is now OK, so return if it has no other effect on semantics.
7159 if (HasNoEffect) {
7160 // Set the template specialization kind.
7161 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007162 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007163 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007164
7165 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007166 // A definition of a class template or class member template
7167 // shall be in scope at the point of the explicit instantiation of
7168 // the class template or class member template.
7169 //
7170 // This check comes when we actually try to perform the
7171 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007172 ClassTemplateSpecializationDecl *Def
7173 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007174 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007175 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007176 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007177 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007178 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007179 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7180 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007181
Douglas Gregor1d957a32009-10-27 18:42:08 +00007182 // Instantiate the members of this class template specialization.
7183 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007184 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007185 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007186 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7187
7188 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7189 // TSK_ExplicitInstantiationDefinition
7190 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7191 TSK == TSK_ExplicitInstantiationDefinition)
Richard Smitheb36ddf2014-04-24 22:45:46 +00007192 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007193 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007194
Douglas Gregor12e49d32009-10-15 22:53:21 +00007195 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007196 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007197
Abramo Bagnara8075c852010-06-12 07:44:57 +00007198 // Set the template specialization kind.
7199 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007200 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007201}
7202
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007203// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007204DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007205Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007206 SourceLocation ExternLoc,
7207 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007208 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007209 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007210 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007211 IdentifierInfo *Name,
7212 SourceLocation NameLoc,
7213 AttributeList *Attr) {
7214
Douglas Gregord6ab8742009-05-28 23:31:59 +00007215 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007216 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007217 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007218 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007219 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007220 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007221 SourceLocation(), false, TypeResult(),
7222 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007223 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7224
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007225 if (!TagD)
7226 return true;
7227
John McCall48871652010-08-21 09:40:31 +00007228 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007229 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007230
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007231 if (Tag->isInvalidDecl())
7232 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007233
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007234 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7235 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7236 if (!Pattern) {
7237 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7238 << Context.getTypeDeclType(Record);
7239 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7240 return true;
7241 }
7242
Douglas Gregore47f5a72009-10-14 23:41:34 +00007243 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007244 // If the explicit instantiation is for a class or member class, the
7245 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007246 // simple-template-id.
7247 //
7248 // C++98 has the same restriction, just worded differently.
7249 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007250 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007251 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007252
Douglas Gregore47f5a72009-10-14 23:41:34 +00007253 // C++0x [temp.explicit]p2:
7254 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007255 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007256 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007257 TemplateSpecializationKind TSK
7258 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7259 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007260
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007261 // C++0x [temp.explicit]p2:
7262 // [...] An explicit instantiation shall appear in an enclosing
7263 // namespace of its template. [...]
7264 //
7265 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007266 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007267
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007268 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007269 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007270 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007271 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007272 PrevDecl = Record;
7273 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007274 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007275 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007276 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007277 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007278 PrevDecl,
7279 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007280 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007281 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007282 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007283 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007284 return TagD;
7285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007286
Douglas Gregor12e49d32009-10-15 22:53:21 +00007287 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007288 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007289 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007290 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007291 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007292 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007293 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007294 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007295 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007296 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7297 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007298 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7299 << Pattern;
7300 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007301 } else {
7302 if (InstantiateClass(NameLoc, Record, Def,
7303 getTemplateInstantiationArgs(Record),
7304 TSK))
7305 return true;
7306
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007307 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007308 if (!RecordDef)
7309 return true;
7310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007311 }
7312
Douglas Gregor1d957a32009-10-27 18:42:08 +00007313 // Instantiate all of the members of the class.
7314 InstantiateClassMembers(NameLoc, RecordDef,
7315 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007316
Douglas Gregor88d292c2010-05-13 16:44:06 +00007317 if (TSK == TSK_ExplicitInstantiationDefinition)
7318 MarkVTableUsed(NameLoc, RecordDef, true);
7319
Mike Stump87c57ac2009-05-16 07:39:55 +00007320 // FIXME: We don't have any representation for explicit instantiations of
7321 // member classes. Such a representation is not needed for compilation, but it
7322 // should be available for clients that want to see all of the declarations in
7323 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007324 return TagD;
7325}
7326
John McCallfaf5fb42010-08-26 23:41:50 +00007327DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7328 SourceLocation ExternLoc,
7329 SourceLocation TemplateLoc,
7330 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007331 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007332 // TODO: check if/when DNInfo should replace Name.
7333 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7334 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007335 if (!Name) {
7336 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007337 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007338 diag::err_explicit_instantiation_requires_name)
7339 << D.getDeclSpec().getSourceRange()
7340 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007341
Douglas Gregor450f00842009-09-25 18:43:00 +00007342 return true;
7343 }
7344
7345 // The scope passed in may not be a decl scope. Zip up the scope tree until
7346 // we find one that is.
7347 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7348 (S->getFlags() & Scope::TemplateParamScope) != 0)
7349 S = S->getParent();
7350
7351 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007352 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7353 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007354 if (R.isNull())
7355 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007356
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007357 // C++ [dcl.stc]p1:
7358 // A storage-class-specifier shall not be specified in [...] an explicit
7359 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007360 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007361 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7362 << Name;
7363 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007364 } else if (D.getDeclSpec().getStorageClassSpec()
7365 != DeclSpec::SCS_unspecified) {
7366 // Complain about then remove the storage class specifier.
7367 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7368 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7369
7370 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007371 }
7372
Douglas Gregor3c74d412009-10-14 20:14:33 +00007373 // C++0x [temp.explicit]p1:
7374 // [...] An explicit instantiation of a function template shall not use the
7375 // inline or constexpr specifiers.
7376 // Presumably, this also applies to member functions of class templates as
7377 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007378 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007379 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007380 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007381 diag::err_explicit_instantiation_inline :
7382 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007383 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007384 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007385 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7386 // not already specified.
7387 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7388 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007389
Douglas Gregore47f5a72009-10-14 23:41:34 +00007390 // C++0x [temp.explicit]p2:
7391 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007392 // definition and an explicit instantiation declaration. An explicit
7393 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007394 TemplateSpecializationKind TSK
7395 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7396 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007397
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007398 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007399 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007400
7401 if (!R->isFunctionType()) {
7402 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007403 // A [...] static data member of a class template can be explicitly
7404 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007405 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007406 // C++1y [temp.explicit]p1:
7407 // A [...] variable [...] template specialization can be explicitly
7408 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007409 if (Previous.isAmbiguous())
7410 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007411
John McCall67c00872009-12-02 08:25:40 +00007412 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007413 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007414
Larisse Voufo39a1e502013-08-06 01:03:05 +00007415 if (!PrevTemplate) {
7416 if (!Prev || !Prev->isStaticDataMember()) {
7417 // We expect to see a data data member here.
7418 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7419 << Name;
7420 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7421 P != PEnd; ++P)
7422 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7423 return true;
7424 }
7425
7426 if (!Prev->getInstantiatedFromStaticDataMember()) {
7427 // FIXME: Check for explicit specialization?
7428 Diag(D.getIdentifierLoc(),
7429 diag::err_explicit_instantiation_data_member_not_instantiated)
7430 << Prev;
7431 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7432 // FIXME: Can we provide a note showing where this was declared?
7433 return true;
7434 }
7435 } else {
7436 // Explicitly instantiate a variable template.
7437
7438 // C++1y [dcl.spec.auto]p6:
7439 // ... A program that uses auto or decltype(auto) in a context not
7440 // explicitly allowed in this section is ill-formed.
7441 //
7442 // This includes auto-typed variable template instantiations.
7443 if (R->isUndeducedType()) {
7444 Diag(T->getTypeLoc().getLocStart(),
7445 diag::err_auto_not_allowed_var_inst);
7446 return true;
7447 }
7448
Richard Smithef985ac2013-09-18 02:10:12 +00007449 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7450 // C++1y [temp.explicit]p3:
7451 // If the explicit instantiation is for a variable, the unqualified-id
7452 // in the declaration shall be a template-id.
7453 Diag(D.getIdentifierLoc(),
7454 diag::err_explicit_instantiation_without_template_id)
7455 << PrevTemplate;
7456 Diag(PrevTemplate->getLocation(),
7457 diag::note_explicit_instantiation_here);
7458 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007459 }
7460
Richard Smithef985ac2013-09-18 02:10:12 +00007461 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007462 TemplateArgumentListInfo TemplateArgs =
7463 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007464
Larisse Voufo39a1e502013-08-06 01:03:05 +00007465 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7466 D.getIdentifierLoc(), TemplateArgs);
7467 if (Res.isInvalid())
7468 return true;
7469
7470 // Ignore access control bits, we don't need them for redeclaration
7471 // checking.
7472 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474
Douglas Gregore47f5a72009-10-14 23:41:34 +00007475 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007476 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007477 // or a static data member of a class template specialization, the name of
7478 // the class template specialization in the qualified-id for the member
7479 // name shall be a simple-template-id.
7480 //
7481 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007482 //
Richard Smith5977d872013-09-18 21:55:14 +00007483 // This does not apply to variable template specializations, where the
7484 // template-id is in the unqualified-id instead.
7485 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007487 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007488 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007489
Douglas Gregore47f5a72009-10-14 23:41:34 +00007490 // Check the scope of this explicit instantiation.
7491 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007493 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007494 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7495 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007496 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007497 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007498 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007499 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007500
Larisse Voufo39a1e502013-08-06 01:03:05 +00007501 if (!HasNoEffect) {
7502 // Instantiate static data member or variable template.
7503
7504 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7505 if (PrevTemplate) {
7506 // Merge attributes.
7507 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7508 ProcessDeclAttributeList(S, Prev, Attr);
7509 }
7510 if (TSK == TSK_ExplicitInstantiationDefinition)
7511 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7512 }
7513
7514 // Check the new variable specialization against the parsed input.
7515 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7516 Diag(T->getTypeLoc().getLocStart(),
7517 diag::err_invalid_var_template_spec_type)
7518 << 0 << PrevTemplate << R << Prev->getType();
7519 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7520 << 2 << PrevTemplate->getDeclName();
7521 return true;
7522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007523
Douglas Gregor450f00842009-09-25 18:43:00 +00007524 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007525 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007527
7528 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007529 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007530 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007531 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007532 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007533 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007534 HasExplicitTemplateArgs = true;
7535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007536
Douglas Gregor450f00842009-09-25 18:43:00 +00007537 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007538 // A [...] function [...] can be explicitly instantiated from its template.
7539 // A member function [...] of a class template can be explicitly
7540 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007541 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007542 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007543 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007544 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7545 P != PEnd; ++P) {
7546 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007547 if (!HasExplicitTemplateArgs) {
7548 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007549 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7550 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007551 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007552
John McCall58cc69d2010-01-27 01:50:18 +00007553 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007554 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7555 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007556 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007557 }
7558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007559
Douglas Gregor450f00842009-09-25 18:43:00 +00007560 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7561 if (!FunTmpl)
7562 continue;
7563
Larisse Voufo98b20f12013-07-19 23:00:19 +00007564 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007565 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007566 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007567 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007568 (HasExplicitTemplateArgs ? &TemplateArgs
7569 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007570 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007571 // Keep track of almost-matches.
7572 FailedCandidates.addCandidate()
7573 .set(FunTmpl->getTemplatedDecl(),
7574 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007575 (void)TDK;
7576 continue;
7577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578
John McCall58cc69d2010-01-27 01:50:18 +00007579 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581
Douglas Gregor450f00842009-09-25 18:43:00 +00007582 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007583 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007584 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007585 D.getIdentifierLoc(),
7586 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7587 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7588 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007589
John McCall58cc69d2010-01-27 01:50:18 +00007590 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007591 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007592
7593 // Ignore access control bits, we don't need them for redeclaration checking.
7594 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007595
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007596 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007597 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007598 diag::err_explicit_instantiation_member_function_not_instantiated)
7599 << Specialization
7600 << (Specialization->getTemplateSpecializationKind() ==
7601 TSK_ExplicitSpecialization);
7602 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7603 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007604 }
7605
Douglas Gregorec9fd132012-01-14 16:38:05 +00007606 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007607 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7608 PrevDecl = Specialization;
7609
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007610 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007611 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007612 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007613 PrevDecl,
7614 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007615 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007616 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007617 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007618
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007619 // FIXME: We may still want to build some representation of this
7620 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007621 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007622 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007623 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007624
7625 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007626 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7627 if (Attr)
7628 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007629
Richard Smitheb36ddf2014-04-24 22:45:46 +00007630 if (Specialization->isDefined()) {
7631 // Let the ASTConsumer know that this function has been explicitly
7632 // instantiated now, and its linkage might have changed.
7633 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7634 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007635 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007636
Douglas Gregore47f5a72009-10-14 23:41:34 +00007637 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007638 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007639 // or a static data member of a class template specialization, the name of
7640 // the class template specialization in the qualified-id for the member
7641 // name shall be a simple-template-id.
7642 //
7643 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007644 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007645 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007646 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007647 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007649 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007650 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007651
Douglas Gregore47f5a72009-10-14 23:41:34 +00007652 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007653 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007654 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007655 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007656 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007657
Douglas Gregor450f00842009-09-25 18:43:00 +00007658 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007659 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007660}
7661
John McCallfaf5fb42010-08-26 23:41:50 +00007662TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007663Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7664 const CXXScopeSpec &SS, IdentifierInfo *Name,
7665 SourceLocation TagLoc, SourceLocation NameLoc) {
7666 // This has to hold, because SS is expected to be defined.
7667 assert(Name && "Expected a name in a dependent tag");
7668
Aaron Ballman4a979672014-01-03 13:56:08 +00007669 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007670 if (!NNS)
7671 return true;
7672
Abramo Bagnara6150c882010-05-11 21:36:43 +00007673 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007674
Douglas Gregorba41d012010-04-24 16:38:41 +00007675 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7676 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007677 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007678 return true;
7679 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007680
Douglas Gregore7c20652011-03-02 00:47:37 +00007681 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007682 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007683 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7684
7685 // Create type-source location information for this type.
7686 TypeLocBuilder TLB;
7687 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007688 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007689 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7690 TL.setNameLoc(NameLoc);
7691 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007692}
7693
John McCallfaf5fb42010-08-26 23:41:50 +00007694TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007695Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7696 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007697 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007698 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007699 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007700
Richard Smith0bf8a4922011-10-18 20:49:44 +00007701 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7702 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007703 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007704 diag::warn_cxx98_compat_typename_outside_of_template :
7705 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007706 << FixItHint::CreateRemoval(TypenameLoc);
7707
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007708 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007709 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7710 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007711 if (T.isNull())
7712 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007713
7714 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7715 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007716 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007717 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007718 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007719 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007720 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007721 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007722 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007723 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007724 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007726
John McCallba7bf592010-08-24 05:47:05 +00007727 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007728}
7729
John McCallfaf5fb42010-08-26 23:41:50 +00007730TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007731Sema::ActOnTypenameType(Scope *S,
7732 SourceLocation TypenameLoc,
7733 const CXXScopeSpec &SS,
7734 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007735 TemplateTy TemplateIn,
7736 SourceLocation TemplateNameLoc,
7737 SourceLocation LAngleLoc,
7738 ASTTemplateArgsPtr TemplateArgsIn,
7739 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007740 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7741 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007742 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007743 diag::warn_cxx98_compat_typename_outside_of_template :
7744 diag::ext_typename_outside_of_template)
7745 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007746
7747 // Translate the parser's template argument list in our AST format.
7748 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7749 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7750
7751 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007752 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7753 // Construct a dependent template specialization type.
7754 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00007755 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007756 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7757 DTN->getQualifier(),
7758 DTN->getIdentifier(),
7759 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007760
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007761 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00007762 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007763 DependentTemplateSpecializationTypeLoc SpecTL
7764 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007765 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7766 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00007767 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007768 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007769 SpecTL.setLAngleLoc(LAngleLoc);
7770 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007771 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7772 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007773 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00007774 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00007775
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007776 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7777 if (T.isNull())
7778 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00007779
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007780 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00007781 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007782 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007783 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007784 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7785 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007786 SpecTL.setLAngleLoc(LAngleLoc);
7787 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007788 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7789 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7790
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007791 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7792 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007793 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007794 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7795
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007796 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7797 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00007798}
7799
Douglas Gregorb09518c2011-02-27 22:46:49 +00007800
Richard Smith6f8d2c62012-05-09 05:17:00 +00007801/// Determine whether this failed name lookup should be treated as being
7802/// disabled by a usage of std::enable_if.
7803static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7804 SourceRange &CondRange) {
7805 // We must be looking for a ::type...
7806 if (!II.isStr("type"))
7807 return false;
7808
7809 // ... within an explicitly-written template specialization...
7810 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7811 return false;
7812 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007813 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7814 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7815 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00007816 return false;
7817 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00007818 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00007819
7820 // ... which names a complete class template declaration...
7821 const TemplateDecl *EnableIfDecl =
7822 EnableIfTST->getTemplateName().getAsTemplateDecl();
7823 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7824 return false;
7825
7826 // ... called "enable_if".
7827 const IdentifierInfo *EnableIfII =
7828 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7829 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7830 return false;
7831
7832 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00007833 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00007834 return true;
7835}
7836
Douglas Gregor333489b2009-03-27 23:10:48 +00007837/// \brief Build the type that describes a C++ typename specifier,
7838/// e.g., "typename T::type".
7839QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007840Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7841 SourceLocation KeywordLoc,
7842 NestedNameSpecifierLoc QualifierLoc,
7843 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00007844 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00007845 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007846 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00007847
John McCall0b66eb32010-05-01 00:40:08 +00007848 DeclContext *Ctx = computeDeclContext(SS);
7849 if (!Ctx) {
7850 // If the nested-name-specifier is dependent and couldn't be
7851 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007852 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7853 return Context.getDependentNameType(Keyword,
7854 QualifierLoc.getNestedNameSpecifier(),
7855 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007856 }
Douglas Gregor333489b2009-03-27 23:10:48 +00007857
John McCall0b66eb32010-05-01 00:40:08 +00007858 // If the nested-name-specifier refers to the current instantiation,
7859 // the "typename" keyword itself is superfluous. In C++03, the
7860 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7861 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00007862 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007863
John McCall0b66eb32010-05-01 00:40:08 +00007864 if (RequireCompleteDeclContext(SS, Ctx))
7865 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00007866
7867 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00007868 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007869 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00007870 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00007871 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007872 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00007873 case LookupResult::NotFound: {
7874 // If we're looking up 'type' within a template named 'enable_if', produce
7875 // a more specific diagnostic.
7876 SourceRange CondRange;
7877 if (isEnableIf(QualifierLoc, II, CondRange)) {
7878 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7879 << Ctx << CondRange;
7880 return QualType();
7881 }
7882
Douglas Gregore40876a2009-10-13 21:16:44 +00007883 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00007884 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00007885 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007886
7887 case LookupResult::FoundUnresolvedValue: {
7888 // We found a using declaration that is a value. Most likely, the using
7889 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007890 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007891 IILoc);
7892 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7893 << Name << Ctx << FullRange;
7894 if (UnresolvedUsingValueDecl *Using
7895 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007896 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007897 Diag(Loc, diag::note_using_value_decl_missing_typename)
7898 << FixItHint::CreateInsertion(Loc, "typename ");
7899 }
7900 }
7901 // Fall through to create a dependent typename type, from which we can recover
7902 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007903
Douglas Gregord0d2ee02010-01-15 01:44:47 +00007904 case LookupResult::NotFoundInCurrentInstantiation:
7905 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007906 return Context.getDependentNameType(Keyword,
7907 QualifierLoc.getNestedNameSpecifier(),
7908 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00007909
7910 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00007912 // We found a type. Build an ElaboratedType, since the
7913 // typename-specifier was just sugar.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007914 return Context.getElaboratedType(ETK_Typename,
7915 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00007916 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00007917 }
7918
7919 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00007920 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00007921 break;
7922
7923 case LookupResult::FoundOverloaded:
7924 DiagID = diag::err_typename_nested_not_type;
7925 Referenced = *Result.begin();
7926 break;
7927
John McCall6538c932009-10-10 05:48:19 +00007928 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00007929 return QualType();
7930 }
7931
7932 // If we get here, it's because name lookup did not find a
7933 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007934 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00007935 IILoc);
7936 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00007937 if (Referenced)
7938 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7939 << Name;
7940 return QualType();
7941}
Douglas Gregor15acfb92009-08-06 16:20:37 +00007942
7943namespace {
7944 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00007945 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00007946 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00007947 SourceLocation Loc;
7948 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00007949
Douglas Gregor15acfb92009-08-06 16:20:37 +00007950 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00007951 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007952
Mike Stump11289f42009-09-09 15:08:12 +00007953 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00007954 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00007955 DeclarationName Entity)
7956 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00007957 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00007958
7959 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00007960 /// transformed.
7961 ///
7962 /// For the purposes of type reconstruction, a type has already been
7963 /// transformed if it is NULL or if it is not dependent.
7964 bool AlreadyTransformed(QualType T) {
7965 return T.isNull() || !T->isDependentType();
7966 }
Mike Stump11289f42009-09-09 15:08:12 +00007967
7968 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00007969 /// rebuilt.
7970 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00007971
Douglas Gregor15acfb92009-08-06 16:20:37 +00007972 /// \brief Returns the name of the entity whose type is being rebuilt.
7973 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00007974
Douglas Gregoref6ab412009-10-27 06:26:26 +00007975 /// \brief Sets the "base" location and entity when that
7976 /// information is known based on another transformation.
7977 void setBase(SourceLocation Loc, DeclarationName Entity) {
7978 this->Loc = Loc;
7979 this->Entity = Entity;
7980 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00007981
7982 ExprResult TransformLambdaExpr(LambdaExpr *E) {
7983 // Lambdas never need to be transformed.
7984 return E;
7985 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00007986 };
7987}
7988
Douglas Gregor15acfb92009-08-06 16:20:37 +00007989/// \brief Rebuilds a type within the context of the current instantiation.
7990///
Mike Stump11289f42009-09-09 15:08:12 +00007991/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00007992/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00007993/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00007994/// partial specialization thereof). This routine will rebuild that type now
7995/// that we have entered the declarator's scope, which may produce different
7996/// canonical types, e.g.,
7997///
7998/// \code
7999/// template<typename T>
8000/// struct X {
8001/// typedef T* pointer;
8002/// pointer data();
8003/// };
8004///
8005/// template<typename T>
8006/// typename X<T>::pointer X<T>::data() { ... }
8007/// \endcode
8008///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008009/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008010/// since we do not know that we can look into X<T> when we parsed the type.
8011/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008012/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008013/// as the canonical type of T*, allowing the return types of the out-of-line
8014/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008015TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8016 SourceLocation Loc,
8017 DeclarationName Name) {
8018 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008019 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008020
Douglas Gregor15acfb92009-08-06 16:20:37 +00008021 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8022 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008023}
Douglas Gregorbe999392009-09-15 16:23:51 +00008024
John McCalldadc5752010-08-24 06:29:42 +00008025ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008026 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8027 DeclarationName());
8028 return Rebuilder.TransformExpr(E);
8029}
8030
John McCall99b2fe52010-04-29 23:50:39 +00008031bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008032 if (SS.isInvalid())
8033 return true;
John McCall2408e322010-04-27 00:57:59 +00008034
Douglas Gregor10176412011-02-25 16:07:42 +00008035 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008036 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8037 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008038 NestedNameSpecifierLoc Rebuilt
8039 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8040 if (!Rebuilt)
8041 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008042
Douglas Gregor10176412011-02-25 16:07:42 +00008043 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008044 return false;
John McCall2408e322010-04-27 00:57:59 +00008045}
8046
Douglas Gregor041b0842011-10-14 15:31:12 +00008047/// \brief Rebuild the template parameters now that we know we're in a current
8048/// instantiation.
8049bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8050 TemplateParameterList *Params) {
8051 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8052 Decl *Param = Params->getParam(I);
8053
8054 // There is nothing to rebuild in a type parameter.
8055 if (isa<TemplateTypeParmDecl>(Param))
8056 continue;
8057
8058 // Rebuild the template parameter list of a template template parameter.
8059 if (TemplateTemplateParmDecl *TTP
8060 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8061 if (RebuildTemplateParamsInCurrentInstantiation(
8062 TTP->getTemplateParameters()))
8063 return true;
8064
8065 continue;
8066 }
8067
8068 // Rebuild the type of a non-type template parameter.
8069 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8070 TypeSourceInfo *NewTSI
8071 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8072 NTTP->getLocation(),
8073 NTTP->getDeclName());
8074 if (!NewTSI)
8075 return true;
8076
8077 if (NewTSI != NTTP->getTypeSourceInfo()) {
8078 NTTP->setTypeSourceInfo(NewTSI);
8079 NTTP->setType(NewTSI->getType());
8080 }
8081 }
8082
8083 return false;
8084}
8085
Douglas Gregorbe999392009-09-15 16:23:51 +00008086/// \brief Produces a formatted string that describes the binding of
8087/// template parameters to template arguments.
8088std::string
8089Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8090 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008091 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008092}
8093
8094std::string
8095Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8096 const TemplateArgument *Args,
8097 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008098 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008099 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008100
Douglas Gregore62e6a02009-11-11 19:13:48 +00008101 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008102 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008103
Douglas Gregorbe999392009-09-15 16:23:51 +00008104 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008105 if (I >= NumArgs)
8106 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008107
Douglas Gregorbe999392009-09-15 16:23:51 +00008108 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008109 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008110 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008111 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008112
Douglas Gregorbe999392009-09-15 16:23:51 +00008113 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008114 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008115 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008116 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008118
Douglas Gregor0192c232010-12-20 16:52:59 +00008119 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008120 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008121 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008122
8123 Out << ']';
8124 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008125}
Francois Pichet1c229c02011-04-22 22:18:13 +00008126
Richard Smithe40f2ba2013-08-07 21:41:30 +00008127void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8128 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008129 if (!FD)
8130 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008131
8132 LateParsedTemplate *LPT = new LateParsedTemplate;
8133
8134 // Take tokens to avoid allocations
8135 LPT->Toks.swap(Toks);
8136 LPT->D = FnD;
8137 LateParsedTemplateMap[FD] = LPT;
8138
8139 FD->setLateTemplateParsed(true);
8140}
8141
8142void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8143 if (!FD)
8144 return;
8145 FD->setLateTemplateParsed(false);
8146}
Francois Pichet1c229c02011-04-22 22:18:13 +00008147
8148bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8149 DeclContext *DC = CurContext;
8150
8151 while (DC) {
8152 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8153 const FunctionDecl *FD = RD->isLocalClass();
8154 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8155 } else if (DC->isTranslationUnit() || DC->isNamespace())
8156 return false;
8157
8158 DC = DC->getParent();
8159 }
8160 return false;
8161}