blob: 2f3309b059365253d899622bb65b135179a0d748 [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"
David Majnemerd9b1a4f2015-11-04 03:40:30 +000021#include "clang/Basic/Builtins.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000032#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000035using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000036using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000037
John McCall9b72f892010-11-10 02:40:36 +000038// Exported for use by Parser.
39SourceRange
40clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
41 unsigned N) {
42 if (!N) return SourceRange();
43 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
44}
45
Douglas Gregorb7bfe792009-09-02 22:59:36 +000046/// \brief Determine whether the declaration found is acceptable as the name
47/// of a template and, if so, return that template declaration. Otherwise,
48/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000049static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000050 NamedDecl *Orig,
51 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000052 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000054 if (isa<TemplateDecl>(D)) {
55 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000056 return nullptr;
57
John McCalle9cccd82010-06-16 08:42:20 +000058 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000059 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregorb7bfe792009-09-02 22:59:36 +000061 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
62 // C++ [temp.local]p1:
63 // Like normal (non-template) classes, class templates have an
64 // injected-class-name (Clause 9). The injected-class-name
65 // can be used with or without a template-argument-list. When
66 // it is used without a template-argument-list, it is
67 // equivalent to the injected-class-name followed by the
68 // template-parameters of the class template enclosed in
69 // <>. When it is used with a template-argument-list, it
70 // refers to the specified class template specialization,
71 // which could be the current specialization or another
72 // specialization.
73 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000074 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000075 if (Record->getDescribedClassTemplate())
76 return Record->getDescribedClassTemplate();
77
78 if (ClassTemplateSpecializationDecl *Spec
79 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
80 return Spec->getSpecializedTemplate();
81 }
Mike Stump11289f42009-09-09 15:08:12 +000082
Craig Topperc3ec1492014-05-26 06:22:03 +000083 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000084 }
Mike Stump11289f42009-09-09 15:08:12 +000085
Craig Topperc3ec1492014-05-26 06:22:03 +000086 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000087}
88
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000089void Sema::FilterAcceptableTemplateNames(LookupResult &R,
90 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000091 // The set of class templates we've already seen.
92 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000093 LookupResult::Filter filter = R.makeFilter();
94 while (filter.hasNext()) {
95 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000096 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
97 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +000098 if (!Repl)
99 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000100 else if (Repl != Orig) {
101
102 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000103 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000104 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105 // one base class). If all of the injected-class-names that are found
106 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000107 // is used as a template-name, the reference refers to the class
108 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000109 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000110 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000111 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000112 filter.erase();
113 continue;
114 }
John McCallbd8062d2010-08-13 07:02:08 +0000115
116 // FIXME: we promote access to public here as a workaround to
117 // the fact that LookupResult doesn't let us remember that we
118 // found this template through a particular injected class name,
119 // which means we end up doing nasty things to the invariants.
120 // Pretending that access is public is *much* safer.
121 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000122 }
John McCalle66edc12009-11-24 19:00:30 +0000123 }
124 filter.done();
125}
126
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000127bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
128 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000129 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000130 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000131 return true;
132
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000133 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000134}
135
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000136TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000137 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000138 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000139 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000140 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000141 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000142 TemplateTy &TemplateResult,
143 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000144 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000145
Douglas Gregor3cf81312009-11-03 23:16:33 +0000146 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000147 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000148
Douglas Gregor3cf81312009-11-03 23:16:33 +0000149 switch (Name.getKind()) {
150 case UnqualifiedId::IK_Identifier:
151 TName = DeclarationName(Name.Identifier);
152 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000153
Douglas Gregor3cf81312009-11-03 23:16:33 +0000154 case UnqualifiedId::IK_OperatorFunctionId:
155 TName = Context.DeclarationNames.getCXXOperatorName(
156 Name.OperatorFunctionId.Operator);
157 break;
158
Alexis Hunted0530f2009-11-28 08:58:14 +0000159 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000160 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
161 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000162
Douglas Gregor3cf81312009-11-03 23:16:33 +0000163 default:
164 return TNK_Non_template;
165 }
Mike Stump11289f42009-09-09 15:08:12 +0000166
John McCallba7bf592010-08-24 05:47:05 +0000167 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000168
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000169 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000170 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
171 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000172 if (R.empty()) return TNK_Non_template;
173 if (R.isAmbiguous()) {
174 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000175 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000176
177 // FIXME: we might have ambiguous templates, in which case we
178 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000179 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000180 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000181
John McCalld28ae272009-12-02 08:04:21 +0000182 TemplateName Template;
183 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000184
John McCalld28ae272009-12-02 08:04:21 +0000185 unsigned ResultCount = R.end() - R.begin();
186 if (ResultCount > 1) {
187 // We assume that we'll preserve the qualifier from a function
188 // template name in other ways.
189 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
190 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000191
192 // We'll do this lookup again later.
193 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000194 } else {
John McCalld28ae272009-12-02 08:04:21 +0000195 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
196
197 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000198 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000199 Template = Context.getQualifiedTemplateName(Qualifier,
200 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000201 } else {
202 Template = TemplateName(TD);
203 }
204
John McCalldcc71402010-08-13 02:23:42 +0000205 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000206 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000207
208 // We'll do this lookup again later.
209 R.suppressDiagnostics();
210 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000211 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000212 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
213 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000214 TemplateKind =
215 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000216 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000217 }
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCalld28ae272009-12-02 08:04:21 +0000219 TemplateResult = TemplateTy::make(Template);
220 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000221}
222
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000223bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000224 SourceLocation IILoc,
225 Scope *S,
226 const CXXScopeSpec *SS,
227 TemplateTy &SuggestedTemplate,
228 TemplateNameKind &SuggestedKind) {
229 // We can't recover unless there's a dependent scope specifier preceding the
230 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000231 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000232 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
233 computeDeclContext(*SS))
234 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000235
Douglas Gregor18473f32010-01-12 21:28:44 +0000236 // The code is missing a 'template' keyword prior to the dependent template
237 // name.
238 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
239 Diag(IILoc, diag::err_template_kw_missing)
240 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000241 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000242 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000243 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
244 SuggestedKind = TNK_Dependent_template_name;
245 return true;
246}
247
John McCalle66edc12009-11-24 19:00:30 +0000248void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000249 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000250 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000251 bool EnteringContext,
252 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000253 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000254 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000255 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000256 bool isDependent = false;
257 if (!ObjectType.isNull()) {
258 // This nested-name-specifier occurs in a member access expression, e.g.,
259 // x->B::f, and we are looking into the type of the object.
260 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
261 LookupCtx = computeDeclContext(ObjectType);
262 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000263 assert((isDependent || !ObjectType->isIncompleteType() ||
264 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000265 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000266
267 // Template names cannot appear inside an Objective-C class or object type.
268 if (ObjectType->isObjCObjectOrInterfaceType()) {
269 Found.clear();
270 return;
271 }
John McCalle66edc12009-11-24 19:00:30 +0000272 } else if (SS.isSet()) {
273 // This nested-name-specifier occurs after another nested-name-specifier,
274 // so long into the context associated with the prior nested-name-specifier.
275 LookupCtx = computeDeclContext(SS, EnteringContext);
276 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277
John McCalle66edc12009-11-24 19:00:30 +0000278 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000279 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000280 return;
281 }
282
283 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000284 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000285 if (LookupCtx) {
286 // Perform "qualified" name lookup into the declaration context we
287 // computed, which is either the type of the base of a member access
288 // expression or the declaration context associated with a prior
289 // nested-name-specifier.
290 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000291 if (!ObjectType.isNull() && Found.empty()) {
292 // C++ [basic.lookup.classref]p1:
293 // In a class member access expression (5.2.5), if the . or -> token is
294 // immediately followed by an identifier followed by a <, the
295 // identifier must be looked up to determine whether the < is the
296 // beginning of a template argument list (14.2) or a less-than operator.
297 // The identifier is first looked up in the class of the object
298 // expression. If the identifier is not found, it is then looked up in
299 // the context of the entire postfix-expression and shall name a class
300 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000301 if (S) LookupName(Found, S);
302 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000303 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000304 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000305 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000306 // We cannot look into a dependent object type or nested nme
307 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000308 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000309 return;
310 } else {
311 // Perform unqualified name lookup in the current scope.
312 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000313
314 if (!ObjectType.isNull())
315 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000316 }
317
Douglas Gregorc119dd52010-01-12 17:06:20 +0000318 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000319 // If we did not find any names, attempt to correct any typos.
320 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000321 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000322 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000323 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
324 FilterCCC->WantTypeSpecifiers = false;
325 FilterCCC->WantExpressionKeywords = false;
326 FilterCCC->WantRemainingKeywords = false;
327 FilterCCC->WantCXXNamedCasts = true;
328 if (TypoCorrection Corrected = CorrectTypo(
329 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
330 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000331 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000332 if (auto *ND = Corrected.getFoundDecl())
333 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000334 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000335 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000336 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000337 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
338 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000339 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000340 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
341 << Name << LookupCtx << DroppedSpecifier
342 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000343 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000344 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000345 }
John McCalle9cccd82010-06-16 08:42:20 +0000346 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000347 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000348 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000349 }
350 }
351
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000352 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000353 if (Found.empty()) {
354 if (isDependent)
355 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000356 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000357 }
John McCalle66edc12009-11-24 19:00:30 +0000358
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000359 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000360 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000361 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000362 // [...] If the lookup in the class of the object expression finds a
363 // template, the name is also looked up in the context of the entire
364 // postfix-expression and [...]
365 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000366 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000367 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
368 LookupOrdinaryName);
369 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000370 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
John McCalle66edc12009-11-24 19:00:30 +0000372 if (FoundOuter.empty()) {
373 // - if the name is not found, the name found in the class of the
374 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000375 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
376 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000377 // - if the name is found in the context of the entire
378 // postfix-expression and does not name a class template, the name
379 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000380 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000381 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000382 // - if the name found is a class template, it must refer to the same
383 // entity as the one found in the class of the object expression,
384 // otherwise the program is ill-formed.
385 if (!Found.isSingleResult() ||
386 Found.getFoundDecl()->getCanonicalDecl()
387 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000389 diag::ext_nested_name_member_ref_lookup_ambiguous)
390 << Found.getLookupName()
391 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000392 Diag(Found.getRepresentativeDecl()->getLocation(),
393 diag::note_ambig_member_ref_object_type)
394 << ObjectType;
395 Diag(FoundOuter.getFoundDecl()->getLocation(),
396 diag::note_ambig_member_ref_scope);
397
398 // Recover by taking the template that we found in the object
399 // expression's type.
400 }
401 }
402 }
403}
404
John McCallcd4b4772009-12-02 03:53:29 +0000405/// ActOnDependentIdExpression - Handle a dependent id-expression that
406/// was just parsed. This is only possible with an explicit scope
407/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000408ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000409Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000410 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000411 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000412 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000413 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000414 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
John McCallcd4b4772009-12-02 03:53:29 +0000416 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000417 isa<CXXMethodDecl>(DC) &&
418 cast<CXXMethodDecl>(DC)->isInstance()) {
419 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420
John McCalle66edc12009-11-24 19:00:30 +0000421 // Since the 'this' expression is synthesized, we don't need to
422 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000423 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000424
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000425 return CXXDependentScopeMemberExpr::Create(
426 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
427 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
428 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000429 }
430
Abramo Bagnara7945c982012-01-27 09:46:47 +0000431 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000432}
433
John McCalldadc5752010-08-24 06:29:42 +0000434ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000435Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000436 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000437 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000438 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000439 return DependentScopeDeclRefExpr::Create(
440 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
441 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000442}
443
Douglas Gregor5101c242008-12-05 18:15:24 +0000444/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
445/// that the template parameter 'PrevDecl' is being shadowed by a new
446/// declaration at location Loc. Returns true to indicate that this is
447/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000448void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000449 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000450
451 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000452 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000453 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000454
455 // C++ [temp.local]p4:
456 // A template-parameter shall not be redeclared within its
457 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000458 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000459 << cast<NamedDecl>(PrevDecl)->getDeclName();
460 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000461 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000462}
463
Douglas Gregor463421d2009-03-03 04:44:36 +0000464/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000465/// the parameter D to reference the templated declaration and return a pointer
466/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000467TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
468 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
469 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000470 return Temp;
471 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000472 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000473}
474
Douglas Gregoreb29d182011-01-05 17:40:24 +0000475ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
476 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000478 "Only template template arguments can be pack expansions here");
479 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
480 "Template template argument pack expansion without packs");
481 ParsedTemplateArgument Result(*this);
482 Result.EllipsisLoc = EllipsisLoc;
483 return Result;
484}
485
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000486static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
487 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000489 switch (Arg.getKind()) {
490 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000491 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000492 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000494 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000495 return TemplateArgumentLoc(TemplateArgument(T), DI);
496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000498 case ParsedTemplateArgument::NonType: {
499 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
500 return TemplateArgumentLoc(TemplateArgument(E), E);
501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000503 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000504 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000505 TemplateArgument TArg;
506 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000507 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000508 else
509 TArg = Template;
510 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000511 Arg.getScopeSpec().getWithLocInContext(
512 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000513 Arg.getLocation(),
514 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000515 }
516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000517
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000518 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000519}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000520
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000521/// \brief Translates template arguments as provided by the parser
522/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000523void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
524 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000525 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000526 TemplateArgs.addArgument(translateTemplateArgument(*this,
527 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000528}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Richard Smithb80d5402013-06-25 22:21:36 +0000530static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
531 SourceLocation Loc,
532 IdentifierInfo *Name) {
533 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
534 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
535 if (PrevDecl && PrevDecl->isTemplateParameter())
536 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
537}
538
Douglas Gregor5101c242008-12-05 18:15:24 +0000539/// ActOnTypeParameter - Called when a C++ template type parameter
540/// (e.g., "typename T") has been parsed. Typename specifies whether
541/// the keyword "typename" was used to declare the type parameter
542/// (otherwise, "class" was used), and KeyLoc is the location of the
543/// "class" or "typename" keyword. ParamName is the name of the
544/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000545/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000546/// If the type parameter has a default argument, it will be added
547/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000548Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000549 SourceLocation EllipsisLoc,
550 SourceLocation KeyLoc,
551 IdentifierInfo *ParamName,
552 SourceLocation ParamNameLoc,
553 unsigned Depth, unsigned Position,
554 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000555 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000556 assert(S->isTemplateParamScope() &&
557 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000558 bool Invalid = false;
559
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000560 SourceLocation Loc = ParamNameLoc;
561 if (!ParamName)
562 Loc = KeyLoc;
563
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000564 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000565 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000566 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000567 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000568 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000569 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000570 if (Invalid)
571 Param->setInvalidDecl();
572
573 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000574 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
575
Douglas Gregor5101c242008-12-05 18:15:24 +0000576 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000577 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000578 IdResolver.AddDecl(Param);
579 }
580
Douglas Gregorf5500772011-01-05 15:48:55 +0000581 // C++0x [temp.param]p9:
582 // A default template-argument may be specified for any kind of
583 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000584 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000585 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000586 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000587 }
588
Douglas Gregordc13ded2010-07-01 00:00:45 +0000589 // Handle the default argument, if provided.
590 if (DefaultArg) {
591 TypeSourceInfo *DefaultTInfo;
592 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregordc13ded2010-07-01 00:00:45 +0000594 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000596 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000598 UPPC_DefaultArgument))
599 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregordc13ded2010-07-01 00:00:45 +0000601 // Check the template argument itself.
602 if (CheckTemplateArgument(Param, DefaultTInfo)) {
603 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000604 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smith1469b912015-06-10 00:29:03 +0000607 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
John McCall48871652010-08-21 09:40:31 +0000610 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000611}
612
Douglas Gregor463421d2009-03-03 04:44:36 +0000613/// \brief Check that the type of a non-type template parameter is
614/// well-formed.
615///
616/// \returns the (possibly-promoted) parameter type if valid;
617/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000618QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000619Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000620 // We don't allow variably-modified types as the type of non-type template
621 // parameters.
622 if (T->isVariablyModifiedType()) {
623 Diag(Loc, diag::err_variably_modified_nontype_template_param)
624 << T;
625 return QualType();
626 }
627
Douglas Gregor463421d2009-03-03 04:44:36 +0000628 // C++ [temp.param]p4:
629 //
630 // A non-type template-parameter shall have one of the following
631 // (optionally cv-qualified) types:
632 //
633 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000634 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000635 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000636 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000637 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000639 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000640 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000641 // -- std::nullptr_t.
642 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000643 // If T is a dependent type, we can't do the check now, so we
644 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000645 T->isDependentType()) {
646 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
647 // are ignored when determining its type.
648 return T.getUnqualifiedType();
649 }
650
Douglas Gregor463421d2009-03-03 04:44:36 +0000651 // C++ [temp.param]p8:
652 //
653 // A non-type template-parameter of type "array of T" or
654 // "function returning T" is adjusted to be of type "pointer to
655 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000656 else if (T->isArrayType() || T->isFunctionType())
657 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor463421d2009-03-03 04:44:36 +0000659 Diag(Loc, diag::err_template_nontype_parm_bad_type)
660 << T;
661
662 return QualType();
663}
664
John McCall48871652010-08-21 09:40:31 +0000665Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
666 unsigned Depth,
667 unsigned Position,
668 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000669 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000670 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
671 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000672
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000673 assert(S->isTemplateParamScope() &&
674 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000675 bool Invalid = false;
676
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000677 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
678 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000679 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000680 Invalid = true;
681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Richard Smithb80d5402013-06-25 22:21:36 +0000683 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000684 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000685 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000686 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000687 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000688 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000689 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000690 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000691 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000692
Douglas Gregor5101c242008-12-05 18:15:24 +0000693 if (Invalid)
694 Param->setInvalidDecl();
695
Richard Smithb80d5402013-06-25 22:21:36 +0000696 if (ParamName) {
697 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
698 ParamName);
699
Douglas Gregor5101c242008-12-05 18:15:24 +0000700 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000701 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000702 IdResolver.AddDecl(Param);
703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Douglas Gregorf5500772011-01-05 15:48:55 +0000705 // C++0x [temp.param]p9:
706 // A default template-argument may be specified for any kind of
707 // template-parameter that is not a template parameter pack.
708 if (Default && IsParameterPack) {
709 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000710 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000711 }
712
Douglas Gregordc13ded2010-07-01 00:00:45 +0000713 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000714 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000715 // Check for unexpanded parameter packs.
716 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
717 return Param;
718
Douglas Gregordc13ded2010-07-01 00:00:45 +0000719 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000720 ExprResult DefaultRes =
721 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000722 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000724 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000725 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000726 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Richard Smith1469b912015-06-10 00:29:03 +0000728 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
John McCall48871652010-08-21 09:40:31 +0000731 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000732}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000733
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000734/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000735/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000736/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000737Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
738 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000739 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000740 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000741 IdentifierInfo *Name,
742 SourceLocation NameLoc,
743 unsigned Depth,
744 unsigned Position,
745 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000746 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000747 assert(S->isTemplateParamScope() &&
748 "Template template parameter not in template parameter scope!");
749
750 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000751 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000752 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000753 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754 NameLoc.isInvalid()? TmpLoc : NameLoc,
755 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000756 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000757 Param->setAccess(AS_public);
758
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000760 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000761 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000762 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
763
John McCall48871652010-08-21 09:40:31 +0000764 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000765 IdResolver.AddDecl(Param);
766 }
767
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000768 if (Params->size() == 0) {
769 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
770 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
771 Param->setInvalidDecl();
772 }
773
Douglas Gregorf5500772011-01-05 15:48:55 +0000774 // C++0x [temp.param]p9:
775 // A default template-argument may be specified for any kind of
776 // template-parameter that is not a template parameter pack.
777 if (IsParameterPack && !Default.isInvalid()) {
778 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
779 Default = ParsedTemplateArgument();
780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000781
Douglas Gregordc13ded2010-07-01 00:00:45 +0000782 if (!Default.isInvalid()) {
783 // Check only that we have a template template argument. We don't want to
784 // try to check well-formedness now, because our template template parameter
785 // might have dependent types in its template parameters, which we wouldn't
786 // be able to match now.
787 //
788 // If none of the template template parameter's template arguments mention
789 // other template parameters, we could actually perform more checking here.
790 // However, it isn't worth doing.
791 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
792 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
793 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
794 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000795 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000798 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000800 DefaultArg.getArgument().getAsTemplate(),
801 UPPC_DefaultArgument))
802 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803
Richard Smith1469b912015-06-10 00:29:03 +0000804 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000806
John McCall48871652010-08-21 09:40:31 +0000807 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000808}
809
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000810/// ActOnTemplateParameterList - Builds a TemplateParameterList that
811/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000812TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000813Sema::ActOnTemplateParameterList(unsigned Depth,
814 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000815 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000816 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000817 ArrayRef<Decl *> Params,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000818 SourceLocation RAngleLoc) {
819 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000820 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000821
David Majnemer902f8c62015-12-27 07:16:27 +0000822 return TemplateParameterList::Create(
823 Context, TemplateLoc, LAngleLoc,
824 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
825 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000826}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000827
John McCall3e11ebe2010-03-15 10:12:16 +0000828static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
829 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000830 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000831}
832
John McCallfaf5fb42010-08-26 23:41:50 +0000833DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000834Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000835 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000836 IdentifierInfo *Name, SourceLocation NameLoc,
837 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000838 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000839 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000840 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000841 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000842 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000843 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000844 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000845 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000846 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000847 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848
849 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000850 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000851 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852
Abramo Bagnara6150c882010-05-11 21:36:43 +0000853 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
854 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000855
856 // There is no such thing as an unnamed class template.
857 if (!Name) {
858 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000859 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000860 }
861
Richard Smith6483d222012-04-21 01:27:54 +0000862 // Find any previous declaration with this name. For a friend with no
863 // scope explicitly specified, we only look for tag declarations (per
864 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000865 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000866 LookupResult Previous(*this, Name, NameLoc,
867 (SS.isEmpty() && TUK == TUK_Friend)
868 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000869 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000870 if (SS.isNotEmpty() && !SS.isInvalid()) {
871 SemanticContext = computeDeclContext(SS, true);
872 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000873 // FIXME: Horrible, horrible hack! We can't currently represent this
874 // in the AST, and historically we have just ignored such friend
875 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000876 Diag(NameLoc, TUK == TUK_Friend
877 ? diag::warn_template_qualified_friend_ignored
878 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000879 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000880 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000881 }
Mike Stump11289f42009-09-09 15:08:12 +0000882
John McCall0b66eb32010-05-01 00:40:08 +0000883 if (RequireCompleteDeclContext(SS, SemanticContext))
884 return true;
885
Douglas Gregor041b0842011-10-14 15:31:12 +0000886 // If we're adding a template to a dependent context, we may need to
887 // rebuilding some of the types used within the template parameter list,
888 // now that we know what the current instantiation is.
889 if (SemanticContext->isDependentContext()) {
890 ContextRAII SavedContext(*this, SemanticContext);
891 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
892 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000893 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
894 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000895
John McCall27b18f82009-11-17 02:14:36 +0000896 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000897 } else {
898 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000899
900 // C++14 [class.mem]p14:
901 // If T is the name of a class, then each of the following shall have a
902 // name different from T:
903 // -- every member template of class T
904 if (TUK != TUK_Friend &&
905 DiagnoseClassNameShadow(SemanticContext,
906 DeclarationNameInfo(Name, NameLoc)))
907 return true;
908
John McCall27b18f82009-11-17 02:14:36 +0000909 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000910 }
Mike Stump11289f42009-09-09 15:08:12 +0000911
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000912 if (Previous.isAmbiguous())
913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914
Craig Topperc3ec1492014-05-26 06:22:03 +0000915 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000916 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000917 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000918
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000919 // If there is a previous declaration with the same name, check
920 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000921 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000922 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000923
924 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000925 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000926 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000928 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
929 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000930 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000931 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
932 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
933 PrevClassTemplate
934 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
935 ->getSpecializedTemplate();
936 }
937 }
938
John McCalld43784f2009-12-18 11:25:59 +0000939 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000940 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941 // [...] When looking for a prior declaration of a class or a function
942 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000943 // function is neither a qualified name nor a template-id, scopes outside
944 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000945 if (!SS.isSet()) {
946 DeclContext *OutermostContext = CurContext;
947 while (!OutermostContext->isFileContext())
948 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000949
Richard Smith61e582f2012-04-20 07:12:26 +0000950 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000951 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
952 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
953 SemanticContext = PrevDecl->getDeclContext();
954 } else {
955 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000957 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000958 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000959 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000960
961 // Check that the chosen semantic context doesn't already contain a
962 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000963 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000964 DeclContext *LookupContext = SemanticContext;
965 while (LookupContext->isTransparentContext())
966 LookupContext = LookupContext->getLookupParent();
967 LookupQualifiedName(Previous, LookupContext);
968
969 if (Previous.isAmbiguous())
970 return true;
971
972 if (Previous.begin() != Previous.end())
973 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000974 }
John McCall90d3bb92009-12-17 23:21:11 +0000975 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000976 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000977 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
978 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000979 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000980
Richard Smithfc805ca2015-07-06 04:43:58 +0000981 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
982 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
983 if (SS.isEmpty() &&
984 !(PrevClassTemplate &&
985 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
986 SemanticContext->getRedeclContext()))) {
987 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
988 Diag(Shadow->getTargetDecl()->getLocation(),
989 diag::note_using_decl_target);
990 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
991 // Recover by ignoring the old declaration.
992 PrevDecl = PrevClassTemplate = nullptr;
993 }
994 }
995
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000996 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000997 // Ensure that the template parameter lists are compatible. Skip this check
998 // for a friend in a dependent context: the template parameter list itself
999 // could be dependent.
1000 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1001 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001002 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001003 /*Complain=*/true,
1004 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001005 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001006
1007 // C++ [temp.class]p4:
1008 // In a redeclaration, partial specialization, explicit
1009 // specialization or explicit instantiation of a class template,
1010 // the class-key shall agree in kind with the original class
1011 // template declaration (7.1.5.3).
1012 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001013 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001014 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001015 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001016 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001017 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001018 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001019 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001020 }
1021
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001022 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001023 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001024 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001025 // If we have a prior definition that is not visible, treat this as
1026 // simply making that previous definition visible.
1027 NamedDecl *Hidden = nullptr;
1028 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001029 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001030 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1031 assert(Tmpl && "original definition of a class template is not a "
1032 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001033 makeMergedDefinitionVisible(Hidden, KWLoc);
1034 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001035 return Def;
1036 }
1037
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001038 Diag(NameLoc, diag::err_redefinition) << Name;
1039 Diag(Def->getLocation(), diag::note_previous_definition);
1040 // FIXME: Would it make sense to try to "forget" the previous
1041 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001042 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001043 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001044 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001045 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1046 // Maybe we will complain about the shadowed template parameter.
1047 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1048 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001049 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001050 } else if (PrevDecl) {
1051 // C++ [temp]p5:
1052 // A class template shall not have the same name as any other
1053 // template, class, function, object, enumeration, enumerator,
1054 // namespace, or type in the same scope (3.3), except as specified
1055 // in (14.5.4).
1056 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1057 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001058 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001059 }
1060
Douglas Gregordba32632009-02-10 19:49:53 +00001061 // Check the template parameter list of this declaration, possibly
1062 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001063 // template declaration. Skip this check for a friend in a dependent
1064 // context, because the template parameter list might be dependent.
1065 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001066 CheckTemplateParameterList(
1067 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001068 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1069 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001070 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1071 SemanticContext->isDependentContext())
1072 ? TPC_ClassTemplateMember
1073 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1074 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001075 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001076
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001077 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001079 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001080 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1081 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001082 : diag::err_member_decl_does_not_match)
1083 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001084 Invalid = true;
1085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086 }
1087
Mike Stump11289f42009-09-09 15:08:12 +00001088 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001089 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001090 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001091 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001092 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001093 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001094 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001095 NewClass->setTemplateParameterListsInfo(
1096 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1097 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001098
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001099 // Add alignment attributes if necessary; these attributes are checked when
1100 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001101 if (TUK == TUK_Definition) {
1102 AddAlignmentAttributesForRecord(NewClass);
1103 AddMsStructLayoutForRecord(NewClass);
1104 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001105
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001106 ClassTemplateDecl *NewTemplate
1107 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1108 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001109 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001110 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001111
Douglas Gregor21823bf2011-12-20 18:11:52 +00001112 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001113 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001114
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001115 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001116 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001117 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001118 assert(T->isDependentType() && "Class template type is not dependent?");
1119 (void)T;
1120
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001122 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001124 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1125 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001126
Anders Carlsson137108d2009-03-26 01:24:28 +00001127 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001128 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001129 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001130
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001131 // Set the lexical context of these templates
1132 NewClass->setLexicalDeclContext(CurContext);
1133 NewTemplate->setLexicalDeclContext(CurContext);
1134
John McCall9bb74a52009-07-31 02:45:11 +00001135 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001136 NewClass->startDefinition();
1137
1138 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001139 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001140
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001141 if (PrevClassTemplate)
1142 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1143
Rafael Espindola385c0422012-07-13 18:04:45 +00001144 AddPushedVisibilityAttribute(NewClass);
1145
Richard Smith234ff472014-08-23 00:49:01 +00001146 if (TUK != TUK_Friend) {
1147 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1148 Scope *Outer = S;
1149 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1150 Outer = Outer->getParent();
1151 PushOnScopeChains(NewTemplate, Outer);
1152 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001153 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001154 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001155 NewClass->setAccess(PrevClassTemplate->getAccess());
1156 }
John McCall27b5c252009-09-14 21:59:20 +00001157
Richard Smith64017682013-07-17 23:53:16 +00001158 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001159
John McCall27b5c252009-09-14 21:59:20 +00001160 // Friend templates are visible in fairly strange ways.
1161 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001162 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001163 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001164 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1165 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001169 FriendDecl *Friend = FriendDecl::Create(
1170 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001171 Friend->setAccess(AS_public);
1172 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001173 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001174
Douglas Gregordba32632009-02-10 19:49:53 +00001175 if (Invalid) {
1176 NewTemplate->setInvalidDecl();
1177 NewClass->setInvalidDecl();
1178 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001179
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001180 ActOnDocumentableDecl(NewTemplate);
1181
John McCall48871652010-08-21 09:40:31 +00001182 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001183}
1184
Douglas Gregored5731f2009-11-25 17:50:39 +00001185/// \brief Diagnose the presence of a default template argument on a
1186/// template parameter, which is ill-formed in certain contexts.
1187///
1188/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001189static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001190 Sema::TemplateParamListContext TPC,
1191 SourceLocation ParamLoc,
1192 SourceRange DefArgRange) {
1193 switch (TPC) {
1194 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001195 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001196 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001197 return false;
1198
1199 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001200 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001201 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001202 // A default template-argument shall not be specified in a
1203 // function template declaration or a function template
1204 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001205 // If a friend function template declaration specifies a default
1206 // template-argument, that declaration shall be a definition and shall be
1207 // the only declaration of the function template in the translation unit.
1208 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001209 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001210 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1211 : diag::ext_template_parameter_default_in_function_template)
1212 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001213 return false;
1214
1215 case Sema::TPC_ClassTemplateMember:
1216 // C++0x [temp.param]p9:
1217 // A default template-argument shall not be specified in the
1218 // template-parameter-lists of the definition of a member of a
1219 // class template that appears outside of the member's class.
1220 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1221 << DefArgRange;
1222 return true;
1223
David Majnemerba8f17a2013-06-25 22:08:55 +00001224 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001225 case Sema::TPC_FriendFunctionTemplate:
1226 // C++ [temp.param]p9:
1227 // A default template-argument shall not be specified in a
1228 // friend template declaration.
1229 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1230 << DefArgRange;
1231 return true;
1232
1233 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1234 // for friend function templates if there is only a single
1235 // declaration (and it is a definition). Strange!
1236 }
1237
David Blaikie8a40f702012-01-17 06:56:22 +00001238 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001239}
1240
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001241/// \brief Check for unexpanded parameter packs within the template parameters
1242/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001243static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1244 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001245 // A template template parameter which is a parameter pack is also a pack
1246 // expansion.
1247 if (TTP->isParameterPack())
1248 return false;
1249
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001250 TemplateParameterList *Params = TTP->getTemplateParameters();
1251 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1252 NamedDecl *P = Params->getParam(I);
1253 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001254 if (!NTTP->isParameterPack() &&
1255 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001256 NTTP->getTypeSourceInfo(),
1257 Sema::UPPC_NonTypeTemplateParameterType))
1258 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001259
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001260 continue;
1261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262
1263 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001264 = dyn_cast<TemplateTemplateParmDecl>(P))
1265 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1266 return true;
1267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001269 return false;
1270}
1271
Douglas Gregordba32632009-02-10 19:49:53 +00001272/// \brief Checks the validity of a template parameter list, possibly
1273/// considering the template parameter list from a previous
1274/// declaration.
1275///
1276/// If an "old" template parameter list is provided, it must be
1277/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1278/// template parameter list.
1279///
1280/// \param NewParams Template parameter list for a new template
1281/// declaration. This template parameter list will be updated with any
1282/// default arguments that are carried through from the previous
1283/// template parameter list.
1284///
1285/// \param OldParams If provided, template parameter list from a
1286/// previous declaration of the same template. Default template
1287/// arguments will be merged from the old template parameter list to
1288/// the new template parameter list.
1289///
Douglas Gregored5731f2009-11-25 17:50:39 +00001290/// \param TPC Describes the context in which we are checking the given
1291/// template parameter list.
1292///
Douglas Gregordba32632009-02-10 19:49:53 +00001293/// \returns true if an error occurred, false otherwise.
1294bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001295 TemplateParameterList *OldParams,
1296 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001297 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001298
Douglas Gregordba32632009-02-10 19:49:53 +00001299 // C++ [temp.param]p10:
1300 // The set of default template-arguments available for use with a
1301 // template declaration or definition is obtained by merging the
1302 // default arguments from the definition (if in scope) and all
1303 // declarations in scope in the same way default function
1304 // arguments are (8.3.6).
1305 bool SawDefaultArgument = false;
1306 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001307
Mike Stumpc89c8e32009-02-11 23:03:27 +00001308 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001309 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001310 if (OldParams)
1311 OldParam = OldParams->begin();
1312
Douglas Gregor0693def2011-01-27 01:40:17 +00001313 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001314 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1315 NewParamEnd = NewParams->end();
1316 NewParam != NewParamEnd; ++NewParam) {
1317 // Variables used to diagnose redundant default arguments
1318 bool RedundantDefaultArg = false;
1319 SourceLocation OldDefaultLoc;
1320 SourceLocation NewDefaultLoc;
1321
David Blaikie651c73c2011-10-19 05:19:50 +00001322 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001323 bool MissingDefaultArg = false;
1324
David Blaikie651c73c2011-10-19 05:19:50 +00001325 // Variable used to diagnose non-final parameter packs
1326 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001327
Douglas Gregordba32632009-02-10 19:49:53 +00001328 if (TemplateTypeParmDecl *NewTypeParm
1329 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001330 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331 if (NewTypeParm->hasDefaultArgument() &&
1332 DiagnoseDefaultTemplateArgument(*this, TPC,
1333 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001334 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001335 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001336 NewTypeParm->removeDefaultArgument();
1337
1338 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001339 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001340 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001341 if (NewTypeParm->isParameterPack()) {
1342 assert(!NewTypeParm->hasDefaultArgument() &&
1343 "Parameter packs can't have a default argument!");
1344 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001345 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001346 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001347 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1348 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1349 SawDefaultArgument = true;
1350 RedundantDefaultArg = true;
1351 PreviousDefaultArgLoc = NewDefaultLoc;
1352 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1353 // Merge the default argument from the old declaration to the
1354 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001355 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001356 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1357 } else if (NewTypeParm->hasDefaultArgument()) {
1358 SawDefaultArgument = true;
1359 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1360 } else if (SawDefaultArgument)
1361 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001362 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001363 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001364 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001365 if (!NewNonTypeParm->isParameterPack() &&
1366 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001367 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001368 UPPC_NonTypeTemplateParameterType)) {
1369 Invalid = true;
1370 continue;
1371 }
1372
Douglas Gregored5731f2009-11-25 17:50:39 +00001373 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374 if (NewNonTypeParm->hasDefaultArgument() &&
1375 DiagnoseDefaultTemplateArgument(*this, TPC,
1376 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001377 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001378 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001379 }
1380
Mike Stump12b8ce12009-08-04 21:02:39 +00001381 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001382 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001383 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001384 if (NewNonTypeParm->isParameterPack()) {
1385 assert(!NewNonTypeParm->hasDefaultArgument() &&
1386 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001387 if (!NewNonTypeParm->isPackExpansion())
1388 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001389 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001390 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001391 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1392 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1393 SawDefaultArgument = true;
1394 RedundantDefaultArg = true;
1395 PreviousDefaultArgLoc = NewDefaultLoc;
1396 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1397 // Merge the default argument from the old declaration to the
1398 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001399 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001400 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1401 } else if (NewNonTypeParm->hasDefaultArgument()) {
1402 SawDefaultArgument = true;
1403 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1404 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001405 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001406 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001407 TemplateTemplateParmDecl *NewTemplateParm
1408 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001409
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001410 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001411 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001412 Invalid = true;
1413 continue;
1414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001415
David Blaikie651c73c2011-10-19 05:19:50 +00001416 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001417 if (NewTemplateParm->hasDefaultArgument() &&
1418 DiagnoseDefaultTemplateArgument(*this, TPC,
1419 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001420 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001421 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001422
1423 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001424 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001425 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001426 if (NewTemplateParm->isParameterPack()) {
1427 assert(!NewTemplateParm->hasDefaultArgument() &&
1428 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001429 if (!NewTemplateParm->isPackExpansion())
1430 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001431 } else if (OldTemplateParm &&
1432 hasVisibleDefaultArgument(OldTemplateParm) &&
1433 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001434 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1435 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001436 SawDefaultArgument = true;
1437 RedundantDefaultArg = true;
1438 PreviousDefaultArgLoc = NewDefaultLoc;
1439 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1440 // Merge the default argument from the old declaration to the
1441 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001442 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001443 PreviousDefaultArgLoc
1444 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001445 } else if (NewTemplateParm->hasDefaultArgument()) {
1446 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001447 PreviousDefaultArgLoc
1448 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001449 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001450 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001451 }
1452
Richard Smith1fde8ec2012-09-07 02:06:42 +00001453 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001454 // If a template parameter of a primary class template or alias template
1455 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001456 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001457 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1458 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001459 Diag((*NewParam)->getLocation(),
1460 diag::err_template_param_pack_must_be_last_template_parameter);
1461 Invalid = true;
1462 }
1463
Douglas Gregordba32632009-02-10 19:49:53 +00001464 if (RedundantDefaultArg) {
1465 // C++ [temp.param]p12:
1466 // A template-parameter shall not be given default arguments
1467 // by two different declarations in the same scope.
1468 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1469 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1470 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001471 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001472 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473 // If a template-parameter of a class template has a default
1474 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001475 // have a default template-argument supplied or be a template parameter
1476 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001477 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001478 diag::err_template_param_default_arg_missing);
1479 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1480 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001481 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001482 }
1483
1484 // If we have an old template parameter list that we're merging
1485 // in, move on to the next parameter.
1486 if (OldParams)
1487 ++OldParam;
1488 }
1489
Douglas Gregor0693def2011-01-27 01:40:17 +00001490 // We were missing some default arguments at the end of the list, so remove
1491 // all of the default arguments.
1492 if (RemoveDefaultArguments) {
1493 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1494 NewParamEnd = NewParams->end();
1495 NewParam != NewParamEnd; ++NewParam) {
1496 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1497 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001498 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001499 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1500 NTTP->removeDefaultArgument();
1501 else
1502 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1503 }
1504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001505
Douglas Gregordba32632009-02-10 19:49:53 +00001506 return Invalid;
1507}
Douglas Gregord32e0282009-02-09 23:23:08 +00001508
John McCalla020a012010-10-20 05:44:58 +00001509namespace {
1510
1511/// A class which looks for a use of a certain level of template
1512/// parameter.
1513struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1514 typedef RecursiveASTVisitor<DependencyChecker> super;
1515
1516 unsigned Depth;
1517 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001518 SourceLocation MatchLoc;
1519
1520 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001521
1522 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1523 NamedDecl *ND = Params->getParam(0);
1524 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1525 Depth = PD->getDepth();
1526 } else if (NonTypeTemplateParmDecl *PD =
1527 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1528 Depth = PD->getDepth();
1529 } else {
1530 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1531 }
1532 }
1533
Richard Smith6056d5e2014-02-09 00:54:43 +00001534 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001535 if (ParmDepth >= Depth) {
1536 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001537 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001538 return true;
1539 }
1540 return false;
1541 }
1542
Richard Smith6056d5e2014-02-09 00:54:43 +00001543 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1544 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1545 }
1546
John McCalla020a012010-10-20 05:44:58 +00001547 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1548 return !Matches(T->getDepth());
1549 }
1550
1551 bool TraverseTemplateName(TemplateName N) {
1552 if (TemplateTemplateParmDecl *PD =
1553 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001554 if (Matches(PD->getDepth()))
1555 return false;
John McCalla020a012010-10-20 05:44:58 +00001556 return super::TraverseTemplateName(N);
1557 }
1558
1559 bool VisitDeclRefExpr(DeclRefExpr *E) {
1560 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001561 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1562 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001563 return false;
John McCalla020a012010-10-20 05:44:58 +00001564 return super::VisitDeclRefExpr(E);
1565 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001566
1567 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1568 return TraverseType(T->getReplacementType());
1569 }
1570
1571 bool
1572 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1573 return TraverseTemplateArgument(T->getArgumentPack());
1574 }
1575
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001576 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1577 return TraverseType(T->getInjectedSpecializationType());
1578 }
John McCalla020a012010-10-20 05:44:58 +00001579};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001580}
John McCalla020a012010-10-20 05:44:58 +00001581
Douglas Gregor972fe532011-05-10 18:27:06 +00001582/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001583/// list.
1584static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001585DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001586 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001587 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001588 return Checker.Match;
1589}
1590
Douglas Gregor972fe532011-05-10 18:27:06 +00001591// Find the source range corresponding to the named type in the given
1592// nested-name-specifier, if any.
1593static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1594 QualType T,
1595 const CXXScopeSpec &SS) {
1596 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1597 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1598 if (const Type *CurType = NNS->getAsType()) {
1599 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1600 return NNSLoc.getTypeLoc().getSourceRange();
1601 } else
1602 break;
1603
1604 NNSLoc = NNSLoc.getPrefix();
1605 }
1606
1607 return SourceRange();
1608}
1609
Mike Stump11289f42009-09-09 15:08:12 +00001610/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001611/// specifier, returning the template parameter list that applies to the
1612/// name.
1613///
1614/// \param DeclStartLoc the start of the declaration that has a scope
1615/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001616///
Douglas Gregor972fe532011-05-10 18:27:06 +00001617/// \param DeclLoc The location of the declaration itself.
1618///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001619/// \param SS the scope specifier that will be matched to the given template
1620/// parameter lists. This scope specifier precedes a qualified name that is
1621/// being declared.
1622///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001623/// \param TemplateId The template-id following the scope specifier, if there
1624/// is one. Used to check for a missing 'template<>'.
1625///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001626/// \param ParamLists the template parameter lists, from the outermost to the
1627/// innermost template parameter lists.
1628///
John McCalle820e5e2010-04-13 20:37:33 +00001629/// \param IsFriend Whether to apply the slightly different rules for
1630/// matching template parameters to scope specifiers in friend
1631/// declarations.
1632///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001633/// \param IsExplicitSpecialization will be set true if the entity being
1634/// declared is an explicit specialization, false otherwise.
1635///
Mike Stump11289f42009-09-09 15:08:12 +00001636/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001637/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001638/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001639/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001640/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001641/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001642TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1643 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001644 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001645 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1646 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001647 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001648 Invalid = false;
1649
1650 // The sequence of nested types to which we will match up the template
1651 // parameter lists. We first build this list by starting with the type named
1652 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001653 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001654 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001655 if (SS.getScopeRep()) {
1656 if (CXXRecordDecl *Record
1657 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1658 T = Context.getTypeDeclType(Record);
1659 else
1660 T = QualType(SS.getScopeRep()->getAsType(), 0);
1661 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001662
1663 // If we found an explicit specialization that prevents us from needing
1664 // 'template<>' headers, this will be set to the location of that
1665 // explicit specialization.
1666 SourceLocation ExplicitSpecLoc;
1667
1668 while (!T.isNull()) {
1669 NestedTypes.push_back(T);
1670
1671 // Retrieve the parent of a record type.
1672 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1673 // If this type is an explicit specialization, we're done.
1674 if (ClassTemplateSpecializationDecl *Spec
1675 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1676 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1677 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1678 ExplicitSpecLoc = Spec->getLocation();
1679 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001680 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001681 } else if (Record->getTemplateSpecializationKind()
1682 == TSK_ExplicitSpecialization) {
1683 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001684 break;
1685 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001686
1687 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1688 T = Context.getTypeDeclType(Parent);
1689 else
1690 T = QualType();
1691 continue;
1692 }
1693
1694 if (const TemplateSpecializationType *TST
1695 = T->getAs<TemplateSpecializationType>()) {
1696 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1697 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1698 T = Context.getTypeDeclType(Parent);
1699 else
1700 T = QualType();
1701 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001702 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001703 }
1704
1705 // Look one step prior in a dependent template specialization type.
1706 if (const DependentTemplateSpecializationType *DependentTST
1707 = T->getAs<DependentTemplateSpecializationType>()) {
1708 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1709 T = QualType(NNS->getAsType(), 0);
1710 else
1711 T = QualType();
1712 continue;
1713 }
1714
1715 // Look one step prior in a dependent name type.
1716 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1717 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1718 T = QualType(NNS->getAsType(), 0);
1719 else
1720 T = QualType();
1721 continue;
1722 }
1723
1724 // Retrieve the parent of an enumeration type.
1725 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1726 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1727 // check here.
1728 EnumDecl *Enum = EnumT->getDecl();
1729
1730 // Get to the parent type.
1731 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1732 T = Context.getTypeDeclType(Parent);
1733 else
1734 T = QualType();
1735 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Douglas Gregor972fe532011-05-10 18:27:06 +00001738 T = QualType();
1739 }
1740 // Reverse the nested types list, since we want to traverse from the outermost
1741 // to the innermost while checking template-parameter-lists.
1742 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001743
Douglas Gregor972fe532011-05-10 18:27:06 +00001744 // C++0x [temp.expl.spec]p17:
1745 // A member or a member template may be nested within many
1746 // enclosing class templates. In an explicit specialization for
1747 // such a member, the member declaration shall be preceded by a
1748 // template<> for each enclosing class template that is
1749 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001750 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001751
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001752 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001753 if (SawNonEmptyTemplateParameterList) {
1754 Diag(DeclLoc, diag::err_specialize_member_of_template)
1755 << !Recovery << Range;
1756 Invalid = true;
1757 IsExplicitSpecialization = false;
1758 return true;
1759 }
1760
1761 return false;
1762 };
1763
1764 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1765 // Check that we can have an explicit specialization here.
1766 if (CheckExplicitSpecialization(Range, true))
1767 return true;
1768
1769 // We don't have a template header, but we should.
1770 SourceLocation ExpectedTemplateLoc;
1771 if (!ParamLists.empty())
1772 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1773 else
1774 ExpectedTemplateLoc = DeclStartLoc;
1775
1776 Diag(DeclLoc, diag::err_template_spec_needs_header)
1777 << Range
1778 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1779 return false;
1780 };
1781
Douglas Gregor972fe532011-05-10 18:27:06 +00001782 unsigned ParamIdx = 0;
1783 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1784 ++TypeIdx) {
1785 T = NestedTypes[TypeIdx];
1786
1787 // Whether we expect a 'template<>' header.
1788 bool NeedEmptyTemplateHeader = false;
1789
1790 // Whether we expect a template header with parameters.
1791 bool NeedNonemptyTemplateHeader = false;
1792
1793 // For a dependent type, the set of template parameters that we
1794 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001795 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001796
Douglas Gregor373af9b2011-05-11 23:26:17 +00001797 // C++0x [temp.expl.spec]p15:
1798 // A member or a member template may be nested within many enclosing
1799 // class templates. In an explicit specialization for such a member, the
1800 // member declaration shall be preceded by a template<> for each
1801 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001802 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1803 if (ClassTemplatePartialSpecializationDecl *Partial
1804 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1805 ExpectedTemplateParams = Partial->getTemplateParameters();
1806 NeedNonemptyTemplateHeader = true;
1807 } else if (Record->isDependentType()) {
1808 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001809 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001810 ->getTemplateParameters();
1811 NeedNonemptyTemplateHeader = true;
1812 }
1813 } else if (ClassTemplateSpecializationDecl *Spec
1814 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1815 // C++0x [temp.expl.spec]p4:
1816 // Members of an explicitly specialized class template are defined
1817 // in the same manner as members of normal classes, and not using
1818 // the template<> syntax.
1819 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1820 NeedEmptyTemplateHeader = true;
1821 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001822 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001823 } else if (Record->getTemplateSpecializationKind()) {
1824 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001825 != TSK_ExplicitSpecialization &&
1826 TypeIdx == NumTypes - 1)
1827 IsExplicitSpecialization = true;
1828
1829 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001830 }
1831 } else if (const TemplateSpecializationType *TST
1832 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001833 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001834 ExpectedTemplateParams = Template->getTemplateParameters();
1835 NeedNonemptyTemplateHeader = true;
1836 }
1837 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1838 // FIXME: We actually could/should check the template arguments here
1839 // against the corresponding template parameter list.
1840 NeedNonemptyTemplateHeader = false;
1841 }
1842
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001843 // C++ [temp.expl.spec]p16:
1844 // In an explicit specialization declaration for a member of a class
1845 // template or a member template that ap- pears in namespace scope, the
1846 // member template and some of its enclosing class templates may remain
1847 // unspecialized, except that the declaration shall not explicitly
1848 // specialize a class member template if its en- closing class templates
1849 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001850 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001851 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001852 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1853 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001854 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001855 } else
1856 SawNonEmptyTemplateParameterList = true;
1857 }
1858
Douglas Gregor972fe532011-05-10 18:27:06 +00001859 if (NeedEmptyTemplateHeader) {
1860 // If we're on the last of the types, and we need a 'template<>' header
1861 // here, then it's an explicit specialization.
1862 if (TypeIdx == NumTypes - 1)
1863 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001864
1865 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001866 if (ParamLists[ParamIdx]->size() > 0) {
1867 // The header has template parameters when it shouldn't. Complain.
1868 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1869 diag::err_template_param_list_matches_nontemplate)
1870 << T
1871 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1872 ParamLists[ParamIdx]->getRAngleLoc())
1873 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1874 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001875 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001876 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001877
Douglas Gregor972fe532011-05-10 18:27:06 +00001878 // Consume this template header.
1879 ++ParamIdx;
1880 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001881 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001882
1883 if (!IsFriend)
1884 if (DiagnoseMissingExplicitSpecialization(
1885 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001886 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001887
Douglas Gregor972fe532011-05-10 18:27:06 +00001888 continue;
1889 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001890
Douglas Gregor972fe532011-05-10 18:27:06 +00001891 if (NeedNonemptyTemplateHeader) {
1892 // In friend declarations we can have template-ids which don't
1893 // depend on the corresponding template parameter lists. But
1894 // assume that empty parameter lists are supposed to match this
1895 // template-id.
1896 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001897 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001898 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001899 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001900 else
1901 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001902 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001903
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001904 if (ParamIdx < ParamLists.size()) {
1905 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001906 if (ExpectedTemplateParams &&
1907 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1908 ExpectedTemplateParams,
1909 true, TPL_TemplateMatch))
1910 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001911
Douglas Gregor972fe532011-05-10 18:27:06 +00001912 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001913 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001914 TPC_ClassTemplateMember))
1915 Invalid = true;
1916
1917 ++ParamIdx;
1918 continue;
1919 }
1920
1921 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1922 << T
1923 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1924 Invalid = true;
1925 continue;
1926 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001927 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001928
Douglas Gregord8d297c2009-07-21 23:53:31 +00001929 // If there were at least as many template-ids as there were template
1930 // parameter lists, then there are no template parameter lists remaining for
1931 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001932 if (ParamIdx >= ParamLists.size()) {
1933 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001934 // We don't have a template header for the declaration itself, but we
1935 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001936 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001937 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1938 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001939
1940 // Fabricate an empty template parameter list for the invented header.
1941 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00001942 SourceLocation(), None,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001943 SourceLocation());
1944 }
1945
Craig Topperc3ec1492014-05-26 06:22:03 +00001946 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001947 }
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregord8d297c2009-07-21 23:53:31 +00001949 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001950 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001951 bool HasAnyExplicitSpecHeader = false;
1952 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001953 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001954 if (ParamLists[I]->size() == 0)
1955 HasAnyExplicitSpecHeader = true;
1956 else
1957 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001958 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001959
Douglas Gregor972fe532011-05-10 18:27:06 +00001960 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001961 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1962 : diag::err_template_spec_extra_headers)
1963 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1964 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001965
1966 // If there was a specialization somewhere, such that 'template<>' is
1967 // not required, and there were any 'template<>' headers, note where the
1968 // specialization occurred.
1969 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1970 Diag(ExplicitSpecLoc,
1971 diag::note_explicit_template_spec_does_not_need_header)
1972 << NestedTypes.back();
1973
1974 // We have a template parameter list with no corresponding scope, which
1975 // means that the resulting template declaration can't be instantiated
1976 // properly (we'll end up with dependent nodes when we shouldn't).
1977 if (!AllExplicitSpecHeaders)
1978 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001979 }
Mike Stump11289f42009-09-09 15:08:12 +00001980
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001981 // C++ [temp.expl.spec]p16:
1982 // In an explicit specialization declaration for a member of a class
1983 // template or a member template that ap- pears in namespace scope, the
1984 // member template and some of its enclosing class templates may remain
1985 // unspecialized, except that the declaration shall not explicitly
1986 // specialize a class member template if its en- closing class templates
1987 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001988 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001989 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1990 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001991 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001992
Douglas Gregord8d297c2009-07-21 23:53:31 +00001993 // Return the last template parameter list, which corresponds to the
1994 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001995 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001996}
1997
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001998void Sema::NoteAllFoundTemplates(TemplateName Name) {
1999 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2000 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002001 << (isa<FunctionTemplateDecl>(Template)
2002 ? 0
2003 : isa<ClassTemplateDecl>(Template)
2004 ? 1
2005 : isa<VarTemplateDecl>(Template)
2006 ? 2
2007 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2008 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002009 return;
2010 }
2011
2012 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2013 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2014 IEnd = OST->end();
2015 I != IEnd; ++I)
2016 Diag((*I)->getLocation(), diag::note_template_declared_here)
2017 << 0 << (*I)->getDeclName();
2018
2019 return;
2020 }
2021}
2022
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002023static QualType
2024checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2025 const SmallVectorImpl<TemplateArgument> &Converted,
2026 SourceLocation TemplateLoc,
2027 TemplateArgumentListInfo &TemplateArgs) {
2028 ASTContext &Context = SemaRef.getASTContext();
2029 switch (BTD->getBuiltinTemplateKind()) {
2030 case BTK__make_integer_seq:
2031 // Specializations of __make_integer_seq<S, T, N> are treated like
2032 // S<T, 0, ..., N-1>.
2033
2034 // C++14 [inteseq.intseq]p1:
2035 // T shall be an integer type.
2036 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2037 SemaRef.Diag(TemplateArgs[1].getLocation(),
2038 diag::err_integer_sequence_integral_element_type);
2039 return QualType();
2040 }
2041
2042 // C++14 [inteseq.make]p1:
2043 // If N is negative the program is ill-formed.
2044 TemplateArgument NumArgsArg = Converted[2];
2045 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2046 if (NumArgs < 0) {
2047 SemaRef.Diag(TemplateArgs[2].getLocation(),
2048 diag::err_integer_sequence_negative_length);
2049 return QualType();
2050 }
2051
2052 QualType ArgTy = NumArgsArg.getIntegralType();
2053 TemplateArgumentListInfo SyntheticTemplateArgs;
2054 // The type argument gets reused as the first template argument in the
2055 // synthetic template argument list.
2056 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2057 // Expand N into 0 ... N-1.
2058 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2059 I < NumArgs; ++I) {
2060 TemplateArgument TA(Context, I, ArgTy);
2061 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2062 TA, TemplateArgs[2].getLocation())
2063 .getAs<Expr>();
2064 SyntheticTemplateArgs.addArgument(
2065 TemplateArgumentLoc(TemplateArgument(E), E));
2066 }
2067 // The first template argument will be reused as the template decl that
2068 // our synthetic template arguments will be applied to.
2069 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2070 TemplateLoc, SyntheticTemplateArgs);
2071 }
2072 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2073}
2074
Douglas Gregordc572a32009-03-30 22:58:21 +00002075QualType Sema::CheckTemplateIdType(TemplateName Name,
2076 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002077 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002078 DependentTemplateName *DTN
2079 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002080 if (DTN && DTN->isIdentifier())
2081 // When building a template-id where the template-name is dependent,
2082 // assume the template is a type template. Either our assumption is
2083 // correct, or the code is ill-formed and will be diagnosed when the
2084 // dependent name is substituted.
2085 return Context.getDependentTemplateSpecializationType(ETK_None,
2086 DTN->getQualifier(),
2087 DTN->getIdentifier(),
2088 TemplateArgs);
2089
Douglas Gregordc572a32009-03-30 22:58:21 +00002090 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002091 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2092 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002093 // We might have a substituted template template parameter pack. If so,
2094 // build a template specialization type for it.
2095 if (Name.getAsSubstTemplateTemplateParmPack())
2096 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002097
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002098 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2099 << Name;
2100 NoteAllFoundTemplates(Name);
2101 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002102 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002103
Douglas Gregorc40290e2009-03-09 23:48:35 +00002104 // Check that the template argument list is well-formed for this
2105 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002106 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002107 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002108 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002109 return QualType();
2110
Douglas Gregorc40290e2009-03-09 23:48:35 +00002111 QualType CanonType;
2112
Douglas Gregor678d76c2011-07-01 01:22:09 +00002113 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002114 if (TypeAliasTemplateDecl *AliasTemplate =
2115 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002116 // Find the canonical type for this type alias template specialization.
2117 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2118 if (Pattern->isInvalidDecl())
2119 return QualType();
2120
2121 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2122 Converted.data(), Converted.size());
2123
2124 // Only substitute for the innermost template argument list.
2125 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002126 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002127 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2128 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002129 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002130
Richard Smith802c4b72012-08-23 06:16:52 +00002131 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002132 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002133 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002134 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002135
Richard Smith3f1b5d02011-05-05 21:57:07 +00002136 CanonType = SubstType(Pattern->getUnderlyingType(),
2137 TemplateArgLists, AliasTemplate->getLocation(),
2138 AliasTemplate->getDeclName());
2139 if (CanonType.isNull())
2140 return QualType();
2141 } else if (Name.isDependent() ||
2142 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002143 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002144 // This class template specialization is a dependent
2145 // type. Therefore, its canonical type is another class template
2146 // specialization type that contains all of the converted
2147 // arguments in canonical form. This ensures that, e.g., A<T> and
2148 // A<T, T> have identical types when A is declared as:
2149 //
2150 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002151 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002152 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002153 Converted.data(),
2154 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002155
Douglas Gregora8e02e72009-07-28 23:00:59 +00002156 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002157 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002158 // In the future, we need to teach getTemplateSpecializationType to only
2159 // build the canonical type and return that to us.
2160 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002161
2162 // This might work out to be a current instantiation, in which
2163 // case the canonical type needs to be the InjectedClassNameType.
2164 //
2165 // TODO: in theory this could be a simple hashtable lookup; most
2166 // changes to CurContext don't change the set of current
2167 // instantiations.
2168 if (isa<ClassTemplateDecl>(Template)) {
2169 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2170 // If we get out to a namespace, we're done.
2171 if (Ctx->isFileContext()) break;
2172
2173 // If this isn't a record, keep looking.
2174 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2175 if (!Record) continue;
2176
2177 // Look for one of the two cases with InjectedClassNameTypes
2178 // and check whether it's the same template.
2179 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2180 !Record->getDescribedClassTemplate())
2181 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
John McCall2408e322010-04-27 00:57:59 +00002183 // Fetch the injected class name type and check whether its
2184 // injected type is equal to the type we just built.
2185 QualType ICNT = Context.getTypeDeclType(Record);
2186 QualType Injected = cast<InjectedClassNameType>(ICNT)
2187 ->getInjectedSpecializationType();
2188
2189 if (CanonType != Injected->getCanonicalTypeInternal())
2190 continue;
2191
2192 // If so, the canonical type of this TST is the injected
2193 // class name type of the record we just found.
2194 assert(ICNT.isCanonical());
2195 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002196 break;
2197 }
2198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002200 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002201 // Find the class template specialization declaration that
2202 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002203 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002204 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002205 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002206 if (!Decl) {
2207 // This is the first time we have referenced this class template
2208 // specialization. Create the canonical declaration and add it to
2209 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002210 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002211 ClassTemplate->getTemplatedDecl()->getTagKind(),
2212 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002213 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002214 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002215 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002216 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002217 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002218 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002219 if (ClassTemplate->isOutOfLine())
2220 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002221 }
2222
Chandler Carruth2acfb222013-09-27 22:14:40 +00002223 // Diagnose uses of this specialization.
2224 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2225
Douglas Gregorc40290e2009-03-09 23:48:35 +00002226 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002227 assert(isa<RecordType>(CanonType) &&
2228 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002229 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2230 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2231 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregorc40290e2009-03-09 23:48:35 +00002234 // Build the fully-sugared type for this class template
2235 // specialization, which refers back to the class template
2236 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002237 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002238}
2239
John McCallfaf5fb42010-08-26 23:41:50 +00002240TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002241Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002242 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002243 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002244 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002245 SourceLocation RAngleLoc,
2246 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002247 if (SS.isInvalid())
2248 return true;
2249
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002250 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002251
Douglas Gregorc40290e2009-03-09 23:48:35 +00002252 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002253 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002254 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002255
Douglas Gregor5a064722011-02-28 17:23:35 +00002256 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002257 QualType T
2258 = Context.getDependentTemplateSpecializationType(ETK_None,
2259 DTN->getQualifier(),
2260 DTN->getIdentifier(),
2261 TemplateArgs);
2262 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002263 TypeLocBuilder TLB;
2264 DependentTemplateSpecializationTypeLoc SpecTL
2265 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002266 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2267 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002268 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002269 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002270 SpecTL.setLAngleLoc(LAngleLoc);
2271 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002272 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2273 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2274 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2275 }
2276
John McCall6b51f282009-11-23 01:53:49 +00002277 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002278
2279 if (Result.isNull())
2280 return true;
2281
Douglas Gregore7c20652011-03-02 00:47:37 +00002282 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002283 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002284 TemplateSpecializationTypeLoc SpecTL
2285 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002286 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002287 SpecTL.setTemplateNameLoc(TemplateLoc);
2288 SpecTL.setLAngleLoc(LAngleLoc);
2289 SpecTL.setRAngleLoc(RAngleLoc);
2290 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2291 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002292
Abramo Bagnara4244b432012-01-27 08:46:19 +00002293 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2294 // constructor or destructor name (in such a case, the scope specifier
2295 // will be attached to the enclosing Decl or Expr node).
2296 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002297 // Create an elaborated-type-specifier containing the nested-name-specifier.
2298 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2299 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002300 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002301 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2302 }
2303
2304 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002305}
John McCall06f6fe8d2009-09-04 01:14:41 +00002306
Douglas Gregore7c20652011-03-02 00:47:37 +00002307TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002308 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002309 SourceLocation TagLoc,
2310 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002311 SourceLocation TemplateKWLoc,
2312 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002313 SourceLocation TemplateLoc,
2314 SourceLocation LAngleLoc,
2315 ASTTemplateArgsPtr TemplateArgsIn,
2316 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002317 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002318
2319 // Translate the parser's template argument list in our AST format.
2320 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2321 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2322
2323 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002324 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002325 ElaboratedTypeKeyword Keyword
2326 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002327
Douglas Gregore7c20652011-03-02 00:47:37 +00002328 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2329 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2330 DTN->getQualifier(),
2331 DTN->getIdentifier(),
2332 TemplateArgs);
2333
2334 // Build type-source information.
2335 TypeLocBuilder TLB;
2336 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002337 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2338 SpecTL.setElaboratedKeywordLoc(TagLoc);
2339 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002340 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002341 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002342 SpecTL.setLAngleLoc(LAngleLoc);
2343 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002344 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2345 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2346 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2347 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002348
2349 if (TypeAliasTemplateDecl *TAT =
2350 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2351 // C++0x [dcl.type.elab]p2:
2352 // If the identifier resolves to a typedef-name or the simple-template-id
2353 // resolves to an alias template specialization, the
2354 // elaborated-type-specifier is ill-formed.
2355 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2356 Diag(TAT->getLocation(), diag::note_declared_at);
2357 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002358
2359 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2360 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002361 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002362
2363 // Check the tag kind
2364 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002365 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002366
John McCalld8fe9af2009-09-08 17:47:29 +00002367 IdentifierInfo *Id = D->getIdentifier();
2368 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002369
Richard Trieucaa33d32011-06-10 03:11:26 +00002370 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002371 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002372 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002373 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002374 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002375 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002376 }
2377 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002378
Douglas Gregore7c20652011-03-02 00:47:37 +00002379 // Provide source-location information for the template specialization.
2380 TypeLocBuilder TLB;
2381 TemplateSpecializationTypeLoc SpecTL
2382 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002383 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002384 SpecTL.setTemplateNameLoc(TemplateLoc);
2385 SpecTL.setLAngleLoc(LAngleLoc);
2386 SpecTL.setRAngleLoc(RAngleLoc);
2387 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2388 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002389
Douglas Gregore7c20652011-03-02 00:47:37 +00002390 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002391 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002392 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2393 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002394 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002395 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2396 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002397}
2398
Larisse Voufo39a1e502013-08-06 01:03:05 +00002399static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002400 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2401 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002402
2403static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2404 NamedDecl *PrevDecl,
2405 SourceLocation Loc,
2406 bool IsPartialSpecialization);
2407
2408static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002409
Richard Smith300e0c32013-09-24 04:49:23 +00002410static bool isTemplateArgumentTemplateParameter(
2411 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2412 switch (Arg.getKind()) {
2413 case TemplateArgument::Null:
2414 case TemplateArgument::NullPtr:
2415 case TemplateArgument::Integral:
2416 case TemplateArgument::Declaration:
2417 case TemplateArgument::Pack:
2418 case TemplateArgument::TemplateExpansion:
2419 return false;
2420
2421 case TemplateArgument::Type: {
2422 QualType Type = Arg.getAsType();
2423 const TemplateTypeParmType *TPT =
2424 Arg.getAsType()->getAs<TemplateTypeParmType>();
2425 return TPT && !Type.hasQualifiers() &&
2426 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2427 }
2428
2429 case TemplateArgument::Expression: {
2430 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2431 if (!DRE || !DRE->getDecl())
2432 return false;
2433 const NonTypeTemplateParmDecl *NTTP =
2434 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2435 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2436 }
2437
2438 case TemplateArgument::Template:
2439 const TemplateTemplateParmDecl *TTP =
2440 dyn_cast_or_null<TemplateTemplateParmDecl>(
2441 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2442 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2443 }
2444 llvm_unreachable("unexpected kind of template argument");
2445}
2446
2447static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2448 ArrayRef<TemplateArgument> Args) {
2449 if (Params->size() != Args.size())
2450 return false;
2451
2452 unsigned Depth = Params->getDepth();
2453
2454 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2455 TemplateArgument Arg = Args[I];
2456
2457 // If the parameter is a pack expansion, the argument must be a pack
2458 // whose only element is a pack expansion.
2459 if (Params->getParam(I)->isParameterPack()) {
2460 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2461 !Arg.pack_begin()->isPackExpansion())
2462 return false;
2463 Arg = Arg.pack_begin()->getPackExpansionPattern();
2464 }
2465
2466 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2467 return false;
2468 }
2469
2470 return true;
2471}
2472
Richard Smith4b55a9c2014-04-17 03:29:33 +00002473/// Convert the parser's template argument list representation into our form.
2474static TemplateArgumentListInfo
2475makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2476 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2477 TemplateId.RAngleLoc);
2478 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2479 TemplateId.NumArgs);
2480 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2481 return TemplateArgs;
2482}
2483
Larisse Voufo39a1e502013-08-06 01:03:05 +00002484DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002485 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002486 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002487 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002488 // D must be variable template id.
2489 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2490 "Variable template specialization is declared with a template it.");
2491
2492 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002493 TemplateArgumentListInfo TemplateArgs =
2494 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002495 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2496 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2497 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002498
Richard Smithbeef3452014-01-16 23:39:20 +00002499 TemplateName Name = TemplateId->Template.get();
2500
2501 // The template-id must name a variable template.
2502 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002503 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2504 if (!VarTemplate) {
2505 NamedDecl *FnTemplate;
2506 if (auto *OTS = Name.getAsOverloadedTemplate())
2507 FnTemplate = *OTS->begin();
2508 else
2509 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2510 if (FnTemplate)
2511 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2512 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002513 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2514 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002515 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002516
2517 // Check for unexpanded parameter packs in any of the template arguments.
2518 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2519 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2520 UPPC_PartialSpecialization))
2521 return true;
2522
2523 // Check that the template argument list is well-formed for this
2524 // template.
2525 SmallVector<TemplateArgument, 4> Converted;
2526 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2527 false, Converted))
2528 return true;
2529
Larisse Voufo39a1e502013-08-06 01:03:05 +00002530 // Find the variable template (partial) specialization declaration that
2531 // corresponds to these arguments.
2532 if (IsPartialSpecialization) {
2533 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002534 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2535 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002536 return true;
2537
2538 bool InstantiationDependent;
2539 if (!Name.isDependent() &&
2540 !TemplateSpecializationType::anyDependentTemplateArguments(
2541 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2542 InstantiationDependent)) {
2543 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2544 << VarTemplate->getDeclName();
2545 IsPartialSpecialization = false;
2546 }
Richard Smith300e0c32013-09-24 04:49:23 +00002547
2548 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2549 Converted)) {
2550 // C++ [temp.class.spec]p9b3:
2551 //
2552 // -- The argument list of the specialization shall not be identical
2553 // to the implicit argument list of the primary template.
2554 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2555 << /*variable template*/ 1
2556 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2557 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2558 // FIXME: Recover from this by treating the declaration as a redeclaration
2559 // of the primary template.
2560 return true;
2561 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002562 }
2563
Craig Topperc3ec1492014-05-26 06:22:03 +00002564 void *InsertPos = nullptr;
2565 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002566
2567 if (IsPartialSpecialization)
2568 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002569 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002570 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002571 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002572
Craig Topperc3ec1492014-05-26 06:22:03 +00002573 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002574
2575 // Check whether we can declare a variable template specialization in
2576 // the current scope.
2577 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2578 TemplateNameLoc,
2579 IsPartialSpecialization))
2580 return true;
2581
2582 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2583 // Since the only prior variable template specialization with these
2584 // arguments was referenced but not declared, reuse that
2585 // declaration node as our own, updating its source location and
2586 // the list of outer template parameters to reflect our new declaration.
2587 Specialization = PrevDecl;
2588 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002589 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002590 } else if (IsPartialSpecialization) {
2591 // Create a new class template partial specialization declaration node.
2592 VarTemplatePartialSpecializationDecl *PrevPartial =
2593 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002594 VarTemplatePartialSpecializationDecl *Partial =
2595 VarTemplatePartialSpecializationDecl::Create(
2596 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2597 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002598 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002599
2600 if (!PrevPartial)
2601 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2602 Specialization = Partial;
2603
2604 // If we are providing an explicit specialization of a member variable
2605 // template specialization, make a note of that.
2606 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002607 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002608
2609 // Check that all of the template parameters of the variable template
2610 // partial specialization are deducible from the template
2611 // arguments. If not, this variable template partial specialization
2612 // will never be used.
2613 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2614 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2615 TemplateParams->getDepth(), DeducibleParams);
2616
2617 if (!DeducibleParams.all()) {
2618 unsigned NumNonDeducible =
2619 DeducibleParams.size() - DeducibleParams.count();
2620 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002621 << /*variable template*/ 1 << (NumNonDeducible > 1)
2622 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002623 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2624 if (!DeducibleParams[I]) {
2625 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2626 if (Param->getDeclName())
2627 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2628 << Param->getDeclName();
2629 else
2630 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002631 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002632 }
2633 }
2634 }
2635 } else {
2636 // Create a new class template specialization declaration node for
2637 // this explicit specialization or friend declaration.
2638 Specialization = VarTemplateSpecializationDecl::Create(
2639 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2640 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2641 Specialization->setTemplateArgsInfo(TemplateArgs);
2642
2643 if (!PrevDecl)
2644 VarTemplate->AddSpecialization(Specialization, InsertPos);
2645 }
2646
2647 // C++ [temp.expl.spec]p6:
2648 // If a template, a member template or the member of a class template is
2649 // explicitly specialized then that specialization shall be declared
2650 // before the first use of that specialization that would cause an implicit
2651 // instantiation to take place, in every translation unit in which such a
2652 // use occurs; no diagnostic is required.
2653 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2654 bool Okay = false;
2655 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2656 // Is there any previous explicit specialization declaration?
2657 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2658 Okay = true;
2659 break;
2660 }
2661 }
2662
2663 if (!Okay) {
2664 SourceRange Range(TemplateNameLoc, RAngleLoc);
2665 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2666 << Name << Range;
2667
2668 Diag(PrevDecl->getPointOfInstantiation(),
2669 diag::note_instantiation_required_here)
2670 << (PrevDecl->getTemplateSpecializationKind() !=
2671 TSK_ImplicitInstantiation);
2672 return true;
2673 }
2674 }
2675
2676 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2677 Specialization->setLexicalDeclContext(CurContext);
2678
2679 // Add the specialization into its lexical context, so that it can
2680 // be seen when iterating through the list of declarations in that
2681 // context. However, specializations are not found by name lookup.
2682 CurContext->addDecl(Specialization);
2683
2684 // Note that this is an explicit specialization.
2685 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2686
2687 if (PrevDecl) {
2688 // Check that this isn't a redefinition of this specialization,
2689 // merging with previous declarations.
2690 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2691 ForRedeclaration);
2692 PrevSpec.addDecl(PrevDecl);
2693 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002694 } else if (Specialization->isStaticDataMember() &&
2695 Specialization->isOutOfLine()) {
2696 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002697 }
2698
2699 // Link instantiations of static data members back to the template from
2700 // which they were instantiated.
2701 if (Specialization->isStaticDataMember())
2702 Specialization->setInstantiationOfStaticDataMember(
2703 VarTemplate->getTemplatedDecl(),
2704 Specialization->getSpecializationKind());
2705
2706 return Specialization;
2707}
2708
2709namespace {
2710/// \brief A partial specialization whose template arguments have matched
2711/// a given template-id.
2712struct PartialSpecMatchResult {
2713 VarTemplatePartialSpecializationDecl *Partial;
2714 TemplateArgumentList *Args;
2715};
2716}
2717
2718DeclResult
2719Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2720 SourceLocation TemplateNameLoc,
2721 const TemplateArgumentListInfo &TemplateArgs) {
2722 assert(Template && "A variable template id without template?");
2723
2724 // Check that the template argument list is well-formed for this template.
2725 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002726 if (CheckTemplateArgumentList(
2727 Template, TemplateNameLoc,
2728 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002729 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002730 return true;
2731
2732 // Find the variable template specialization declaration that
2733 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002734 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002735 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002736 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002737 // If we already have a variable template specialization, return it.
2738 return Spec;
2739
2740 // This is the first time we have referenced this variable template
2741 // specialization. Create the canonical declaration and add it to
2742 // the set of specializations, based on the closest partial specialization
2743 // that it represents. That is,
2744 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2745 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2746 Converted.data(), Converted.size());
2747 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2748 bool AmbiguousPartialSpec = false;
2749 typedef PartialSpecMatchResult MatchResult;
2750 SmallVector<MatchResult, 4> Matched;
2751 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002752 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2753 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002754
2755 // 1. Attempt to find the closest partial specialization that this
2756 // specializes, if any.
2757 // If any of the template arguments is dependent, then this is probably
2758 // a placeholder for an incomplete declarative context; which must be
2759 // complete by instantiation time. Thus, do not search through the partial
2760 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002761 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2762 // Perhaps better after unification of DeduceTemplateArguments() and
2763 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002764 bool InstantiationDependent = false;
2765 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2766 TemplateArgs, InstantiationDependent)) {
2767
2768 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2769 Template->getPartialSpecializations(PartialSpecs);
2770
2771 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2772 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2773 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2774
2775 if (TemplateDeductionResult Result =
2776 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2777 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002778 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002779 FailedCandidates.addCandidate()
2780 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2781 (void)Result;
2782 } else {
2783 Matched.push_back(PartialSpecMatchResult());
2784 Matched.back().Partial = Partial;
2785 Matched.back().Args = Info.take();
2786 }
2787 }
2788
Larisse Voufo39a1e502013-08-06 01:03:05 +00002789 if (Matched.size() >= 1) {
2790 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2791 if (Matched.size() == 1) {
2792 // -- If exactly one matching specialization is found, the
2793 // instantiation is generated from that specialization.
2794 // We don't need to do anything for this.
2795 } else {
2796 // -- If more than one matching specialization is found, the
2797 // partial order rules (14.5.4.2) are used to determine
2798 // whether one of the specializations is more specialized
2799 // than the others. If none of the specializations is more
2800 // specialized than all of the other matching
2801 // specializations, then the use of the variable template is
2802 // ambiguous and the program is ill-formed.
2803 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2804 PEnd = Matched.end();
2805 P != PEnd; ++P) {
2806 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2807 PointOfInstantiation) ==
2808 P->Partial)
2809 Best = P;
2810 }
2811
2812 // Determine if the best partial specialization is more specialized than
2813 // the others.
2814 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2815 PEnd = Matched.end();
2816 P != PEnd; ++P) {
2817 if (P != Best && getMoreSpecializedPartialSpecialization(
2818 P->Partial, Best->Partial,
2819 PointOfInstantiation) != Best->Partial) {
2820 AmbiguousPartialSpec = true;
2821 break;
2822 }
2823 }
2824 }
2825
2826 // Instantiate using the best variable template partial specialization.
2827 InstantiationPattern = Best->Partial;
2828 InstantiationArgs = Best->Args;
2829 } else {
2830 // -- If no match is found, the instantiation is generated
2831 // from the primary template.
2832 // InstantiationPattern = Template->getTemplatedDecl();
2833 }
2834 }
2835
Larisse Voufo39a1e502013-08-06 01:03:05 +00002836 // 2. Create the canonical declaration.
2837 // Note that we do not instantiate the variable just yet, since
2838 // instantiation is handled in DoMarkVarDeclReferenced().
2839 // FIXME: LateAttrs et al.?
2840 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2841 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2842 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2843 if (!Decl)
2844 return true;
2845
2846 if (AmbiguousPartialSpec) {
2847 // Partial ordering did not produce a clear winner. Complain.
2848 Decl->setInvalidDecl();
2849 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2850 << Decl;
2851
2852 // Print the matching partial specializations.
2853 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2854 PEnd = Matched.end();
2855 P != PEnd; ++P)
2856 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2857 << getTemplateArgumentBindingsText(
2858 P->Partial->getTemplateParameters(), *P->Args);
2859 return true;
2860 }
2861
2862 if (VarTemplatePartialSpecializationDecl *D =
2863 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2864 Decl->setInstantiationOf(D, InstantiationArgs);
2865
2866 assert(Decl && "No variable template specialization?");
2867 return Decl;
2868}
2869
2870ExprResult
2871Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2872 const DeclarationNameInfo &NameInfo,
2873 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2874 const TemplateArgumentListInfo *TemplateArgs) {
2875
2876 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2877 *TemplateArgs);
2878 if (Decl.isInvalid())
2879 return ExprError();
2880
2881 VarDecl *Var = cast<VarDecl>(Decl.get());
2882 if (!Var->getTemplateSpecializationKind())
2883 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2884 NameInfo.getLoc());
2885
2886 // Build an ordinary singleton decl ref.
2887 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002888 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002889}
2890
John McCalldadc5752010-08-24 06:29:42 +00002891ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002892 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002893 LookupResult &R,
2894 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002895 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002896 // FIXME: Can we do any checking at this point? I guess we could check the
2897 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002898 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002899 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002900 // foo<int> could identify a single function unambiguously
2901 // This approach does NOT work, since f<int>(1);
2902 // gets resolved prior to resorting to overload resolution
2903 // i.e., template<class T> void f(double);
2904 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002905
2906 // These should be filtered out by our callers.
2907 assert(!R.empty() && "empty lookup results when building templateid");
2908 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2909
Larisse Voufo39a1e502013-08-06 01:03:05 +00002910 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002911 bool InstantiationDependent;
2912 if (R.getAsSingle<VarTemplateDecl>() &&
2913 !TemplateSpecializationType::anyDependentTemplateArguments(
2914 *TemplateArgs, InstantiationDependent)) {
2915 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2916 R.getAsSingle<VarTemplateDecl>(),
2917 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002918 }
2919
John McCall58cc69d2010-01-27 01:50:18 +00002920 // We don't want lookup warnings at this point.
2921 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002922
John McCalle66edc12009-11-24 19:00:30 +00002923 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002924 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002925 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002926 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002927 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002928 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002929 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002930
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002931 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002932}
2933
John McCalle66edc12009-11-24 19:00:30 +00002934// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002935ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002936Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002937 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002938 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002939 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002940
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002941 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002942 DeclContext *DC;
2943 if (!(DC = computeDeclContext(SS, false)) ||
2944 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002945 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002946 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregor786123d2010-05-21 23:18:07 +00002948 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002949 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002950 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002951 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002952
John McCalle66edc12009-11-24 19:00:30 +00002953 if (R.isAmbiguous())
2954 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002955
John McCalle66edc12009-11-24 19:00:30 +00002956 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002957 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2958 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002959 return ExprError();
2960 }
2961
2962 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002963 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002964 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002965 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002966 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2967 return ExprError();
2968 }
2969
Abramo Bagnara7945c982012-01-27 09:46:47 +00002970 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002971}
2972
Douglas Gregorb67535d2009-03-31 00:43:58 +00002973/// \brief Form a dependent template name.
2974///
2975/// This action forms a dependent template name given the template
2976/// name and its (presumably dependent) scope specifier. For
2977/// example, given "MetaFun::template apply", the scope specifier \p
2978/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2979/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002981 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002982 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002983 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002984 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002985 bool EnteringContext,
2986 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002987 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2988 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002989 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002990 diag::warn_cxx98_compat_template_outside_of_template :
2991 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002992 << FixItHint::CreateRemoval(TemplateKWLoc);
2993
Craig Topperc3ec1492014-05-26 06:22:03 +00002994 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002995 if (SS.isSet())
2996 LookupCtx = computeDeclContext(SS, EnteringContext);
2997 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002998 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002999 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003000 // C++0x [temp.names]p5:
3001 // If a name prefixed by the keyword template is not the name of
3002 // a template, the program is ill-formed. [Note: the keyword
3003 // template may not be applied to non-template members of class
3004 // templates. -end note ] [ Note: as is the case with the
3005 // typename prefix, the template prefix is allowed in cases
3006 // where it is not strictly necessary; i.e., when the
3007 // nested-name-specifier or the expression on the left of the ->
3008 // or . is not dependent on a template-parameter, or the use
3009 // does not appear in the scope of a template. -end note]
3010 //
3011 // Note: C++03 was more strict here, because it banned the use of
3012 // the "template" keyword prior to a template-name that was not a
3013 // dependent name. C++ DR468 relaxed this requirement (the
3014 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003015 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003016 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003017 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003018 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003019 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003020 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3021 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003022 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3023 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003024 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003025 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003026 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003027 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003028 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003029 << Name.getSourceRange()
3030 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003031 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003032 } else {
3033 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003034 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003035 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003036 }
3037
Aaron Ballman4a979672014-01-03 13:56:08 +00003038 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039
Douglas Gregor3cf81312009-11-03 23:16:33 +00003040 switch (Name.getKind()) {
3041 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003042 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003043 Name.Identifier));
3044 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045
Douglas Gregor71395fa2009-11-04 00:56:37 +00003046 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003047 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003048 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003049 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003050
3051 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003052 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003053
Douglas Gregor3cf81312009-11-03 23:16:33 +00003054 default:
3055 break;
3056 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003058 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003059 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003060 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003061 << Name.getSourceRange()
3062 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003063 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003064}
3065
Mike Stump11289f42009-09-09 15:08:12 +00003066bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003067 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003068 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003069 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003070 QualType ArgType;
3071 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003072
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003073 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003074 switch(Arg.getKind()) {
3075 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003076 // C++ [temp.arg.type]p1:
3077 // A template-argument for a template-parameter which is a
3078 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003079 ArgType = Arg.getAsType();
3080 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003081 break;
3082 case TemplateArgument::Template: {
3083 // We have a template type parameter but the template argument
3084 // is a template without any arguments.
3085 SourceRange SR = AL.getSourceRange();
3086 TemplateName Name = Arg.getAsTemplate();
3087 Diag(SR.getBegin(), diag::err_template_missing_args)
3088 << Name << SR;
3089 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3090 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003091
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003092 return true;
3093 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003094 case TemplateArgument::Expression: {
3095 // We have a template type parameter but the template argument is an
3096 // expression; see if maybe it is missing the "typename" keyword.
3097 CXXScopeSpec SS;
3098 DeclarationNameInfo NameInfo;
3099
3100 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3101 SS.Adopt(ArgExpr->getQualifierLoc());
3102 NameInfo = ArgExpr->getNameInfo();
3103 } else if (DependentScopeDeclRefExpr *ArgExpr =
3104 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3105 SS.Adopt(ArgExpr->getQualifierLoc());
3106 NameInfo = ArgExpr->getNameInfo();
3107 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3108 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003109 if (ArgExpr->isImplicitAccess()) {
3110 SS.Adopt(ArgExpr->getQualifierLoc());
3111 NameInfo = ArgExpr->getMemberNameInfo();
3112 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003113 }
3114
Reid Kleckner377c1592014-06-10 23:29:48 +00003115 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003116 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3117 LookupParsedName(Result, CurScope, &SS);
3118
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003119 if (Result.getAsSingle<TypeDecl>() ||
3120 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003121 LookupResult::NotFoundInCurrentInstantiation) {
3122 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003123 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003124 Diag(Loc, getLangOpts().MSVCCompat
3125 ? diag::ext_ms_template_type_arg_missing_typename
3126 : diag::err_template_arg_must_be_type_suggest)
3127 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003128 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003129
3130 // Recover by synthesizing a type using the location information that we
3131 // already have.
3132 ArgType =
3133 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3134 TypeLocBuilder TLB;
3135 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3136 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3137 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3138 TL.setNameLoc(NameInfo.getLoc());
3139 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3140
3141 // Overwrite our input TemplateArgumentLoc so that we can recover
3142 // properly.
3143 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3144 TemplateArgumentLocInfo(TSI));
3145
3146 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003147 }
3148 }
3149 // fallthrough
3150 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003151 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003152 // We have a template type parameter but the template argument
3153 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003154 SourceRange SR = AL.getSourceRange();
3155 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003156 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003157
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003158 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003159 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003160 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003161
Reid Kleckner377c1592014-06-10 23:29:48 +00003162 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003163 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003164
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003165 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003166 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003167
3168 // Objective-C ARC:
3169 // If an explicitly-specified template argument type is a lifetime type
3170 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003171 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003172 ArgType->isObjCLifetimeType() &&
3173 !ArgType.getObjCLifetime()) {
3174 Qualifiers Qs;
3175 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3176 ArgType = Context.getQualifiedType(ArgType, Qs);
3177 }
3178
3179 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003180 return false;
3181}
3182
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003183/// \brief Substitute template arguments into the default template argument for
3184/// the given template type parameter.
3185///
3186/// \param SemaRef the semantic analysis object for which we are performing
3187/// the substitution.
3188///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003190/// for.
3191///
3192/// \param TemplateLoc the location of the template name that started the
3193/// template-id we are checking.
3194///
3195/// \param RAngleLoc the location of the right angle bracket ('>') that
3196/// terminates the template-id.
3197///
3198/// \param Param the template template parameter whose default we are
3199/// substituting into.
3200///
3201/// \param Converted the list of template arguments provided for template
3202/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003203/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003204static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003205SubstDefaultTemplateArgument(Sema &SemaRef,
3206 TemplateDecl *Template,
3207 SourceLocation TemplateLoc,
3208 SourceLocation RAngleLoc,
3209 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003210 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003211 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003212
3213 // If the argument type is dependent, instantiate it now based
3214 // on the previously-computed template arguments.
3215 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003216 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003217 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003218 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003219 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003220 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221
David Majnemer89189202013-08-28 23:48:32 +00003222 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3223 Converted.data(), Converted.size());
3224
3225 // Only substitute for the innermost template argument list.
3226 MultiLevelTemplateArgumentList TemplateArgLists;
3227 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3228 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3229 TemplateArgLists.addOuterTemplateArguments(None);
3230
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003231 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003232 ArgType =
3233 SemaRef.SubstType(ArgType, TemplateArgLists,
3234 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003235 }
3236
3237 return ArgType;
3238}
3239
3240/// \brief Substitute template arguments into the default template argument for
3241/// the given non-type template parameter.
3242///
3243/// \param SemaRef the semantic analysis object for which we are performing
3244/// the substitution.
3245///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003247/// for.
3248///
3249/// \param TemplateLoc the location of the template name that started the
3250/// template-id we are checking.
3251///
3252/// \param RAngleLoc the location of the right angle bracket ('>') that
3253/// terminates the template-id.
3254///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003255/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003256/// substituting into.
3257///
3258/// \param Converted the list of template arguments provided for template
3259/// parameters that precede \p Param in the template parameter list.
3260///
3261/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003262static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003263SubstDefaultTemplateArgument(Sema &SemaRef,
3264 TemplateDecl *Template,
3265 SourceLocation TemplateLoc,
3266 SourceLocation RAngleLoc,
3267 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003268 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003269 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003270 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003271 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003272 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003273 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003274
David Majnemer89189202013-08-28 23:48:32 +00003275 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3276 Converted.data(), Converted.size());
3277
3278 // Only substitute for the innermost template argument list.
3279 MultiLevelTemplateArgumentList TemplateArgLists;
3280 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3281 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3282 TemplateArgLists.addOuterTemplateArguments(None);
3283
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003284 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Faisal Vali48401eb2015-11-19 19:20:17 +00003285 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3286 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003287 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003288}
3289
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003290/// \brief Substitute template arguments into the default template argument for
3291/// the given template template parameter.
3292///
3293/// \param SemaRef the semantic analysis object for which we are performing
3294/// the substitution.
3295///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003296/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003297/// for.
3298///
3299/// \param TemplateLoc the location of the template name that started the
3300/// template-id we are checking.
3301///
3302/// \param RAngleLoc the location of the right angle bracket ('>') that
3303/// terminates the template-id.
3304///
3305/// \param Param the template template parameter whose default we are
3306/// substituting into.
3307///
3308/// \param Converted the list of template arguments provided for template
3309/// parameters that precede \p Param in the template parameter list.
3310///
Douglas Gregordf846d12011-03-02 18:46:51 +00003311/// \param QualifierLoc Will be set to the nested-name-specifier (with
3312/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003313///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003314/// \returns the substituted template argument, or NULL if an error occurred.
3315static TemplateName
3316SubstDefaultTemplateArgument(Sema &SemaRef,
3317 TemplateDecl *Template,
3318 SourceLocation TemplateLoc,
3319 SourceLocation RAngleLoc,
3320 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003321 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003322 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003323 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003324 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003325 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003326 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327
David Majnemer89189202013-08-28 23:48:32 +00003328 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3329 Converted.data(), Converted.size());
3330
3331 // Only substitute for the innermost template argument list.
3332 MultiLevelTemplateArgumentList TemplateArgLists;
3333 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3334 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3335 TemplateArgLists.addOuterTemplateArguments(None);
3336
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003337 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003338 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003339 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003340 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003341 QualifierLoc =
3342 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003343 if (!QualifierLoc)
3344 return TemplateName();
3345 }
David Majnemer89189202013-08-28 23:48:32 +00003346
3347 return SemaRef.SubstTemplateName(
3348 QualifierLoc,
3349 Param->getDefaultArgument().getArgument().getAsTemplate(),
3350 Param->getDefaultArgument().getTemplateNameLoc(),
3351 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003352}
3353
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003354/// \brief If the given template parameter has a default template
3355/// argument, substitute into that default template argument and
3356/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003358Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3359 SourceLocation TemplateLoc,
3360 SourceLocation RAngleLoc,
3361 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003362 SmallVectorImpl<TemplateArgument>
3363 &Converted,
3364 bool &HasDefaultArg) {
3365 HasDefaultArg = false;
3366
3367 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003368 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003369 return TemplateArgumentLoc();
3370
Richard Smithc87b9382013-07-04 01:01:24 +00003371 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003372 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003373 TemplateLoc,
3374 RAngleLoc,
3375 TypeParm,
3376 Converted);
3377 if (DI)
3378 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3379
3380 return TemplateArgumentLoc();
3381 }
3382
3383 if (NonTypeTemplateParmDecl *NonTypeParm
3384 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003385 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003386 return TemplateArgumentLoc();
3387
Richard Smithc87b9382013-07-04 01:01:24 +00003388 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003389 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003390 TemplateLoc,
3391 RAngleLoc,
3392 NonTypeParm,
3393 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003394 if (Arg.isInvalid())
3395 return TemplateArgumentLoc();
3396
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003397 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003398 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3399 }
3400
3401 TemplateTemplateParmDecl *TempTempParm
3402 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003403 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003404 return TemplateArgumentLoc();
3405
Richard Smithc87b9382013-07-04 01:01:24 +00003406 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003407 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003408 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003410 RAngleLoc,
3411 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003412 Converted,
3413 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003414 if (TName.isNull())
3415 return TemplateArgumentLoc();
3416
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003418 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003419 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3420}
3421
Douglas Gregorda0fb532009-11-11 19:31:23 +00003422/// \brief Check that the given template argument corresponds to the given
3423/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003424///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003426/// checked.
3427///
Richard Trieu15b66532015-01-24 02:48:32 +00003428/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003429///
3430/// \param Template The template in which the template argument resides.
3431///
3432/// \param TemplateLoc The location of the template name for the template
3433/// whose argument list we're matching.
3434///
3435/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3436/// the template argument list.
3437///
3438/// \param ArgumentPackIndex The index into the argument pack where this
3439/// argument will be placed. Only valid if the parameter is a parameter pack.
3440///
3441/// \param Converted The checked, converted argument will be added to the
3442/// end of this small vector.
3443///
3444/// \param CTAK Describes how we arrived at this particular template argument:
3445/// explicitly written, deduced, etc.
3446///
3447/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003448bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003449 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003450 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003451 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003452 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003453 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003454 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003455 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003456 // Check template type parameters.
3457 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003458 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459
Douglas Gregoreebed722009-11-11 19:41:09 +00003460 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003462 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003463 // with the template arguments we've seen thus far. But if the
3464 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003465 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003466 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3467 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
Peter Collingbourne01687632010-12-10 17:08:53 +00003469 if (NTTPType->isDependentType() &&
3470 !isa<TemplateTemplateParmDecl>(Template) &&
3471 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003472 // Do substitution on the type of the non-type template parameter.
3473 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003474 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003475 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003476 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003477 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478
3479 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003480 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003481 NTTPType = SubstType(NTTPType,
3482 MultiLevelTemplateArgumentList(TemplateArgs),
3483 NTTP->getLocation(),
3484 NTTP->getDeclName());
3485 // If that worked, check the non-type template parameter type
3486 // for validity.
3487 if (!NTTPType.isNull())
3488 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3489 NTTP->getLocation());
3490 if (NTTPType.isNull())
3491 return true;
3492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493
Douglas Gregorda0fb532009-11-11 19:31:23 +00003494 switch (Arg.getArgument().getKind()) {
3495 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003496 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497
Douglas Gregorda0fb532009-11-11 19:31:23 +00003498 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003499 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003500 ExprResult Res =
3501 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3502 Result, CTAK);
3503 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003504 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505
Richard Trieu15b66532015-01-24 02:48:32 +00003506 // If the resulting expression is new, then use it in place of the
3507 // old expression in the template argument.
3508 if (Res.get() != Arg.getArgument().getAsExpr()) {
3509 TemplateArgument TA(Res.get());
3510 Arg = TemplateArgumentLoc(TA, Res.get());
3511 }
3512
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003513 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003514 break;
3515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
Douglas Gregorda0fb532009-11-11 19:31:23 +00003517 case TemplateArgument::Declaration:
3518 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003519 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003520 // We've already checked this template argument, so just copy
3521 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003522 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003523 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregorda0fb532009-11-11 19:31:23 +00003525 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003526 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003527 // We were given a template template argument. It may not be ill-formed;
3528 // see below.
3529 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003530 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3531 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003532 // We have a template argument such as \c T::template X, which we
3533 // parsed as a template template argument. However, since we now
3534 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003535 // template name into an expression.
3536
3537 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3538 Arg.getTemplateNameLoc());
3539
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003540 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003541 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003542 // FIXME: the template-template arg was a DependentTemplateName,
3543 // so it was provided with a template keyword. However, its source
3544 // location is not stored in the template argument structure.
3545 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003546 ExprResult E = DependentScopeDeclRefExpr::Create(
3547 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3548 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003550 // If we parsed the template argument as a pack expansion, create a
3551 // pack expansion expression.
3552 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003553 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003554 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003555 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557
Douglas Gregorda0fb532009-11-11 19:31:23 +00003558 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003559 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003560 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003561 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003563 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003564 break;
3565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregorda0fb532009-11-11 19:31:23 +00003567 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003568 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003569 // therefore cannot be a non-type template argument.
3570 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3571 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Douglas Gregorda0fb532009-11-11 19:31:23 +00003573 Diag(Param->getLocation(), diag::note_template_param_here);
3574 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Douglas Gregorda0fb532009-11-11 19:31:23 +00003576 case TemplateArgument::Type: {
3577 // We have a non-type template parameter but the template
3578 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579
Douglas Gregorda0fb532009-11-11 19:31:23 +00003580 // C++ [temp.arg]p2:
3581 // In a template-argument, an ambiguity between a type-id and
3582 // an expression is resolved to a type-id, regardless of the
3583 // form of the corresponding template-parameter.
3584 //
3585 // We warn specifically about this case, since it can be rather
3586 // confusing for users.
3587 QualType T = Arg.getArgument().getAsType();
3588 SourceRange SR = Arg.getSourceRange();
3589 if (T->isFunctionType())
3590 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3591 else
3592 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3593 Diag(Param->getLocation(), diag::note_template_param_here);
3594 return true;
3595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregorda0fb532009-11-11 19:31:23 +00003597 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003598 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregorda0fb532009-11-11 19:31:23 +00003601 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602 }
3603
3604
Douglas Gregorda0fb532009-11-11 19:31:23 +00003605 // Check template template parameters.
3606 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607
Douglas Gregorda0fb532009-11-11 19:31:23 +00003608 // Substitute into the template parameter list of the template
3609 // template parameter, since previously-supplied template arguments
3610 // may appear within the template template parameter.
3611 {
3612 // Set up a template instantiation context.
3613 LocalInstantiationScope Scope(*this);
3614 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003615 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003616 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003617 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003618 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619
3620 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003621 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003622 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003624 MultiLevelTemplateArgumentList(TemplateArgs)));
3625 if (!TempParm)
3626 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregorda0fb532009-11-11 19:31:23 +00003629 switch (Arg.getArgument().getKind()) {
3630 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003631 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632
Douglas Gregorda0fb532009-11-11 19:31:23 +00003633 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003634 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003635 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003636 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003638 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003639 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregorda0fb532009-11-11 19:31:23 +00003641 case TemplateArgument::Expression:
3642 case TemplateArgument::Type:
3643 // We have a template template parameter but the template
3644 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003645 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003646 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003647 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
Douglas Gregorda0fb532009-11-11 19:31:23 +00003649 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003650 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003651 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003652 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003653 case TemplateArgument::NullPtr:
3654 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Douglas Gregorda0fb532009-11-11 19:31:23 +00003656 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003657 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659
Douglas Gregorda0fb532009-11-11 19:31:23 +00003660 return false;
3661}
3662
Douglas Gregor8e072612012-02-03 07:34:46 +00003663/// \brief Diagnose an arity mismatch in the
3664static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3665 SourceLocation TemplateLoc,
3666 TemplateArgumentListInfo &TemplateArgs) {
3667 TemplateParameterList *Params = Template->getTemplateParameters();
3668 unsigned NumParams = Params->size();
3669 unsigned NumArgs = TemplateArgs.size();
3670
3671 SourceRange Range;
3672 if (NumArgs > NumParams)
3673 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3674 TemplateArgs.getRAngleLoc());
3675 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3676 << (NumArgs > NumParams)
3677 << (isa<ClassTemplateDecl>(Template)? 0 :
3678 isa<FunctionTemplateDecl>(Template)? 1 :
3679 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3680 << Template << Range;
3681 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3682 << Params->getSourceRange();
3683 return true;
3684}
3685
Richard Smith1fde8ec2012-09-07 02:06:42 +00003686/// \brief Check whether the template parameter is a pack expansion, and if so,
3687/// determine the number of parameters produced by that expansion. For instance:
3688///
3689/// \code
3690/// template<typename ...Ts> struct A {
3691/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3692/// };
3693/// \endcode
3694///
3695/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3696/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003697static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003698 if (NonTypeTemplateParmDecl *NTTP
3699 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3700 if (NTTP->isExpandedParameterPack())
3701 return NTTP->getNumExpansionTypes();
3702 }
3703
3704 if (TemplateTemplateParmDecl *TTP
3705 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3706 if (TTP->isExpandedParameterPack())
3707 return TTP->getNumExpansionTemplateParameters();
3708 }
3709
David Blaikie7a30dc52013-02-21 01:47:18 +00003710 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003711}
3712
Richard Smith35c1df52015-06-17 20:16:32 +00003713/// Diagnose a missing template argument.
3714template<typename TemplateParmDecl>
3715static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3716 TemplateDecl *TD,
3717 const TemplateParmDecl *D,
3718 TemplateArgumentListInfo &Args) {
3719 // Dig out the most recent declaration of the template parameter; there may be
3720 // declarations of the template that are more recent than TD.
3721 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3722 ->getTemplateParameters()
3723 ->getParam(D->getIndex()));
3724
3725 // If there's a default argument that's not visible, diagnose that we're
3726 // missing a module import.
3727 llvm::SmallVector<Module*, 8> Modules;
3728 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3729 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3730 D->getDefaultArgumentLoc(), Modules,
3731 Sema::MissingImportKind::DefaultArgument,
3732 /*Recover*/ true);
3733 return true;
3734 }
3735
3736 // FIXME: If there's a more recent default argument that *is* visible,
3737 // diagnose that it was declared too late.
3738
3739 return diagnoseArityMismatch(S, TD, Loc, Args);
3740}
3741
Douglas Gregord32e0282009-02-09 23:23:08 +00003742/// \brief Check that the given template argument list is well-formed
3743/// for specializing the given template.
3744bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3745 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003746 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003747 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003748 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003749 // Make a copy of the template arguments for processing. Only make the
3750 // changes at the end when successful in matching the arguments to the
3751 // template.
3752 TemplateArgumentListInfo NewArgs = TemplateArgs;
3753
Douglas Gregord32e0282009-02-09 23:23:08 +00003754 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003755
Richard Trieu15b66532015-01-24 02:48:32 +00003756 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003757
Mike Stump11289f42009-09-09 15:08:12 +00003758 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003759 // [...] The type and form of each template-argument specified in
3760 // a template-id shall match the type and form specified for the
3761 // corresponding parameter declared by the template in its
3762 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003763 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003764 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003765 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003766 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003767 for (TemplateParameterList::iterator Param = Params->begin(),
3768 ParamEnd = Params->end();
3769 Param != ParamEnd; /* increment in loop */) {
3770 // If we have an expanded parameter pack, make sure we don't have too
3771 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003772 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003773 if (*Expansions == ArgumentPack.size()) {
3774 // We're done with this parameter pack. Pack up its arguments and add
3775 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003776 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003777 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003778 ArgumentPack.clear();
3779
Richard Smith1fde8ec2012-09-07 02:06:42 +00003780 // This argument is assigned to the next parameter.
3781 ++Param;
3782 continue;
3783 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3784 // Not enough arguments for this parameter pack.
3785 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3786 << false
3787 << (isa<ClassTemplateDecl>(Template)? 0 :
3788 isa<FunctionTemplateDecl>(Template)? 1 :
3789 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3790 << Template;
3791 Diag(Template->getLocation(), diag::note_template_decl_here)
3792 << Params->getSourceRange();
3793 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003794 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796
Richard Smith1fde8ec2012-09-07 02:06:42 +00003797 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003798 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003799 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003801 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003802 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Richard Smith96d71c32014-11-12 23:38:38 +00003804 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003805 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003806 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3807 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003808 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003809 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003810 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003811 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003812 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003813 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003814 Diag((*Param)->getLocation(), diag::note_template_param_here);
3815 return true;
3816 }
3817
Richard Smith1fde8ec2012-09-07 02:06:42 +00003818 // We're now done with this argument.
3819 ++ArgIdx;
3820
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003821 if ((*Param)->isTemplateParameterPack()) {
3822 // The template parameter was a template parameter pack, so take the
3823 // deduced argument and place it on the argument pack. Note that we
3824 // stay on the same template parameter so that we can deduce more
3825 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003826 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003827 } else {
3828 // Move to the next template parameter.
3829 ++Param;
3830 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003831
Richard Smith96d71c32014-11-12 23:38:38 +00003832 // If we just saw a pack expansion into a non-pack, then directly convert
3833 // the remaining arguments, because we don't know what parameters they'll
3834 // match up with.
3835 if (PackExpansionIntoNonPack) {
3836 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003837 // If we were part way through filling in an expanded parameter pack,
3838 // fall back to just producing individual arguments.
3839 Converted.insert(Converted.end(),
3840 ArgumentPack.begin(), ArgumentPack.end());
3841 ArgumentPack.clear();
3842 }
3843
3844 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003845 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003846 ++ArgIdx;
3847 }
3848
Richard Smith1fde8ec2012-09-07 02:06:42 +00003849 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003850 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003851
Douglas Gregor84d49a22009-11-11 21:54:23 +00003852 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003853 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854
Douglas Gregor2f157c92011-06-03 02:59:40 +00003855 // If we're checking a partial template argument list, we're done.
3856 if (PartialTemplateArgs) {
3857 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003858 Converted.push_back(
3859 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3860
Richard Smith1fde8ec2012-09-07 02:06:42 +00003861 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003862 }
3863
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003865 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003866 if ((*Param)->isTemplateParameterPack()) {
3867 assert(!getExpandedPackSize(*Param) &&
3868 "Should have dealt with this already");
3869
3870 // A non-expanded parameter pack before the end of the parameter list
3871 // only occurs for an ill-formed template parameter list, unless we've
3872 // got a partial argument list for a function template, so just bail out.
3873 if (Param + 1 != ParamEnd)
3874 return true;
3875
Benjamin Kramercce63472015-08-05 09:40:22 +00003876 Converted.push_back(
3877 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003878 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003879
3880 ++Param;
3881 continue;
3882 }
3883
Douglas Gregor8e072612012-02-03 07:34:46 +00003884 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003885 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
Douglas Gregor84d49a22009-11-11 21:54:23 +00003887 // Retrieve the default template argument from the template
3888 // parameter. For each kind of template parameter, we substitute the
3889 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003891 // the default argument.
3892 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003893 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003894 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3895 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003898 Template,
3899 TemplateLoc,
3900 RAngleLoc,
3901 TTP,
3902 Converted);
3903 if (!ArgType)
3904 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Douglas Gregor84d49a22009-11-11 21:54:23 +00003906 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3907 ArgType);
3908 } else if (NonTypeTemplateParmDecl *NTTP
3909 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003910 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003911 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3912 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003913
John McCalldadc5752010-08-24 06:29:42 +00003914 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915 TemplateLoc,
3916 RAngleLoc,
3917 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003918 Converted);
3919 if (E.isInvalid())
3920 return true;
3921
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003922 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003923 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3924 } else {
3925 TemplateTemplateParmDecl *TempParm
3926 = cast<TemplateTemplateParmDecl>(*Param);
3927
Richard Smith95d83952015-06-10 20:36:34 +00003928 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003929 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3930 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003931
Douglas Gregordf846d12011-03-02 18:46:51 +00003932 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003933 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934 TemplateLoc,
3935 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003936 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003937 Converted,
3938 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003939 if (Name.isNull())
3940 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941
Douglas Gregor9d802122011-03-02 17:09:35 +00003942 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3943 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003944 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945
Douglas Gregor84d49a22009-11-11 21:54:23 +00003946 // Introduce an instantiation record that describes where we are using
3947 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003948 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3949 SourceRange(TemplateLoc, RAngleLoc));
3950 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003951 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952
Douglas Gregor84d49a22009-11-11 21:54:23 +00003953 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003954 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003955 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003956 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957
Richard Trieu15b66532015-01-24 02:48:32 +00003958 // Core issue 150 (assumed resolution): if this is a template template
3959 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003960 // template definition.
3961 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003962 NewArgs.addArgument(Arg);
3963
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003964 // Move to the next template parameter and argument.
3965 ++Param;
3966 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968
Richard Smith07f79912014-06-06 16:00:50 +00003969 // If we're performing a partial argument substitution, allow any trailing
3970 // pack expansions; they might be empty. This can happen even if
3971 // PartialTemplateArgs is false (the list of arguments is complete but
3972 // still dependent).
3973 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3974 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003975 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3976 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003977 }
3978
Douglas Gregor8e072612012-02-03 07:34:46 +00003979 // If we have any leftover arguments, then there were too many arguments.
3980 // Complain and fail.
3981 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003982 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3983
3984 // No problems found with the new argument list, propagate changes back
3985 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00003986 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003987
Richard Smith1fde8ec2012-09-07 02:06:42 +00003988 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003989}
3990
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003991namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992 class UnnamedLocalNoLinkageFinder
3993 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003994 {
3995 Sema &S;
3996 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003998 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004000 public:
4001 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4002
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003 bool Visit(QualType T) {
4004 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004007#define TYPE(Class, Parent) \
4008 bool Visit##Class##Type(const Class##Type *);
4009#define ABSTRACT_TYPE(Class, Parent) \
4010 bool Visit##Class##Type(const Class##Type *) { return false; }
4011#define NON_CANONICAL_TYPE(Class, Parent) \
4012 bool Visit##Class##Type(const Class##Type *) { return false; }
4013#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004015 bool VisitTagDecl(const TagDecl *Tag);
4016 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4017 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004018}
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004019
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004021 return false;
4022}
4023
4024bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4025 return Visit(T->getElementType());
4026}
4027
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004029 return Visit(T->getPointeeType());
4030}
4031
4032bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004034 return Visit(T->getPointeeType());
4035}
4036
4037bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004038 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004039 return Visit(T->getPointeeType());
4040}
4041
4042bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004044 return Visit(T->getPointeeType());
4045}
4046
4047bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004048 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004049 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4050}
4051
4052bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004054 return Visit(T->getElementType());
4055}
4056
4057bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004059 return Visit(T->getElementType());
4060}
4061
4062bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004064 return Visit(T->getElementType());
4065}
4066
4067bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004068 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004069 return Visit(T->getElementType());
4070}
4071
4072bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004073 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004074 return Visit(T->getElementType());
4075}
4076
4077bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4078 return Visit(T->getElementType());
4079}
4080
4081bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4082 return Visit(T->getElementType());
4083}
4084
4085bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4086 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004087 for (const auto &A : T->param_types()) {
4088 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004089 return true;
4090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004091
Alp Toker314cc812014-01-25 16:55:45 +00004092 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004093}
4094
4095bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4096 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004097 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004098}
4099
4100bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4101 const UnresolvedUsingType*) {
4102 return false;
4103}
4104
4105bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4106 return false;
4107}
4108
4109bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4110 return Visit(T->getUnderlyingType());
4111}
4112
4113bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4114 return false;
4115}
4116
Alexis Hunte852b102011-05-24 22:41:36 +00004117bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4118 const UnaryTransformType*) {
4119 return false;
4120}
4121
Richard Smith30482bc2011-02-20 03:19:35 +00004122bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4123 return Visit(T->getDeducedType());
4124}
4125
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004126bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4127 return VisitTagDecl(T->getDecl());
4128}
4129
4130bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4131 return VisitTagDecl(T->getDecl());
4132}
4133
4134bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4135 const TemplateTypeParmType*) {
4136 return false;
4137}
4138
Douglas Gregorada4b792011-01-14 02:55:32 +00004139bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4140 const SubstTemplateTypeParmPackType *) {
4141 return false;
4142}
4143
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004144bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4145 const TemplateSpecializationType*) {
4146 return false;
4147}
4148
4149bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4150 const InjectedClassNameType* T) {
4151 return VisitTagDecl(T->getDecl());
4152}
4153
4154bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4155 const DependentNameType* T) {
4156 return VisitNestedNameSpecifier(T->getQualifier());
4157}
4158
4159bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4160 const DependentTemplateSpecializationType* T) {
4161 return VisitNestedNameSpecifier(T->getQualifier());
4162}
4163
Douglas Gregord2fa7662010-12-20 02:24:11 +00004164bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4165 const PackExpansionType* T) {
4166 return Visit(T->getPattern());
4167}
4168
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004169bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4170 return false;
4171}
4172
4173bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4174 const ObjCInterfaceType *) {
4175 return false;
4176}
4177
4178bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4179 const ObjCObjectPointerType *) {
4180 return false;
4181}
4182
Eli Friedman0dfb8892011-10-06 23:00:33 +00004183bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4184 return Visit(T->getValueType());
4185}
4186
Xiuli Pan9c14e282016-01-09 12:53:17 +00004187bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4188 return false;
4189}
4190
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004191bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4192 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004193 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004194 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004195 diag::warn_cxx98_compat_template_arg_local_type :
4196 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004197 << S.Context.getTypeDeclType(Tag) << SR;
4198 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004199 }
4200
John McCall5ea95772013-03-09 00:54:27 +00004201 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004202 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004203 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004204 diag::warn_cxx98_compat_template_arg_unnamed_type :
4205 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004206 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4207 return true;
4208 }
4209
4210 return false;
4211}
4212
4213bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4214 NestedNameSpecifier *NNS) {
4215 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4216 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004218 switch (NNS->getKind()) {
4219 case NestedNameSpecifier::Identifier:
4220 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004221 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004222 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004223 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004224 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004226 case NestedNameSpecifier::TypeSpec:
4227 case NestedNameSpecifier::TypeSpecWithTemplate:
4228 return Visit(QualType(NNS->getAsType(), 0));
4229 }
David Blaikie8a40f702012-01-17 06:56:22 +00004230 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004231}
4232
4233
Douglas Gregord32e0282009-02-09 23:23:08 +00004234/// \brief Check a template argument against its corresponding
4235/// template type parameter.
4236///
4237/// This routine implements the semantics of C++ [temp.arg.type]. It
4238/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004239bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004240 TypeSourceInfo *ArgInfo) {
4241 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004242 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004243 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004244
4245 if (Arg->isVariablyModifiedType()) {
4246 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004247 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004248 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004249 }
4250
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004251 // C++03 [temp.arg.type]p2:
4252 // A local type, a type with no linkage, an unnamed type or a type
4253 // compounded from any of these types shall not be used as a
4254 // template-argument for a template type-parameter.
4255 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004256 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004257 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004258 bool NeedsCheck;
4259 if (LangOpts.CPlusPlus11)
4260 NeedsCheck =
4261 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4262 SR.getBegin()) ||
4263 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4264 SR.getBegin());
4265 else
4266 NeedsCheck = Arg->hasUnnamedOrLocalType();
4267
4268 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004269 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4270 (void)Finder.Visit(Context.getCanonicalType(Arg));
4271 }
4272
Douglas Gregord32e0282009-02-09 23:23:08 +00004273 return false;
4274}
4275
Douglas Gregor20fdef32012-04-10 17:08:25 +00004276enum NullPointerValueKind {
4277 NPV_NotNullPointer,
4278 NPV_NullPointer,
4279 NPV_Error
4280};
4281
4282/// \brief Determine whether the given template argument is a null pointer
4283/// value of the appropriate type.
4284static NullPointerValueKind
4285isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4286 QualType ParamType, Expr *Arg) {
4287 if (Arg->isValueDependent() || Arg->isTypeDependent())
4288 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004289
Richard Smithdb0ac552015-12-18 22:40:25 +00004290 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004291 llvm_unreachable(
4292 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004293
David Majnemer5c734ad2014-08-14 00:49:23 +00004294 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004295 return NPV_NotNullPointer;
4296
4297 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004298 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4299 if (ArgRV.isInvalid())
4300 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004301 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004302
Douglas Gregor20fdef32012-04-10 17:08:25 +00004303 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004304 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004305 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004306 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004307 EvalResult.HasSideEffects) {
4308 SourceLocation DiagLoc = Arg->getExprLoc();
4309
4310 // If our only note is the usual "invalid subexpression" note, just point
4311 // the caret at its location rather than producing an essentially
4312 // redundant note.
4313 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4314 diag::note_invalid_subexpr_in_const_expr) {
4315 DiagLoc = Notes[0].first;
4316 Notes.clear();
4317 }
4318
4319 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4320 << Arg->getType() << Arg->getSourceRange();
4321 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4322 S.Diag(Notes[I].first, Notes[I].second);
4323
4324 S.Diag(Param->getLocation(), diag::note_template_param_here);
4325 return NPV_Error;
4326 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004327
4328 // C++11 [temp.arg.nontype]p1:
4329 // - an address constant expression of type std::nullptr_t
4330 if (Arg->getType()->isNullPtrType())
4331 return NPV_NullPointer;
4332
4333 // - a constant expression that evaluates to a null pointer value (4.10); or
4334 // - a constant expression that evaluates to a null member pointer value
4335 // (4.11); or
4336 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4337 (EvalResult.Val.isMemberPointer() &&
4338 !EvalResult.Val.getMemberPointerDecl())) {
4339 // If our expression has an appropriate type, we've succeeded.
4340 bool ObjCLifetimeConversion;
4341 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4342 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4343 ObjCLifetimeConversion))
4344 return NPV_NullPointer;
4345
4346 // The types didn't match, but we know we got a null pointer; complain,
4347 // then recover as if the types were correct.
4348 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4349 << Arg->getType() << ParamType << Arg->getSourceRange();
4350 S.Diag(Param->getLocation(), diag::note_template_param_here);
4351 return NPV_NullPointer;
4352 }
4353
4354 // If we don't have a null pointer value, but we do have a NULL pointer
4355 // constant, suggest a cast to the appropriate type.
4356 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4357 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4358 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004359 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4360 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4361 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004362 S.Diag(Param->getLocation(), diag::note_template_param_here);
4363 return NPV_NullPointer;
4364 }
4365
4366 // FIXME: If we ever want to support general, address-constant expressions
4367 // as non-type template arguments, we should return the ExprResult here to
4368 // be interpreted by the caller.
4369 return NPV_NotNullPointer;
4370}
4371
David Majnemer61c39a12013-08-23 05:39:39 +00004372/// \brief Checks whether the given template argument is compatible with its
4373/// template parameter.
4374static bool CheckTemplateArgumentIsCompatibleWithParameter(
4375 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4376 Expr *Arg, QualType ArgType) {
4377 bool ObjCLifetimeConversion;
4378 if (ParamType->isPointerType() &&
4379 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4380 S.IsQualificationConversion(ArgType, ParamType, false,
4381 ObjCLifetimeConversion)) {
4382 // For pointer-to-object types, qualification conversions are
4383 // permitted.
4384 } else {
4385 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4386 if (!ParamRef->getPointeeType()->isFunctionType()) {
4387 // C++ [temp.arg.nontype]p5b3:
4388 // For a non-type template-parameter of type reference to
4389 // object, no conversions apply. The type referred to by the
4390 // reference may be more cv-qualified than the (otherwise
4391 // identical) type of the template- argument. The
4392 // template-parameter is bound directly to the
4393 // template-argument, which shall be an lvalue.
4394
4395 // FIXME: Other qualifiers?
4396 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4397 unsigned ArgQuals = ArgType.getCVRQualifiers();
4398
4399 if ((ParamQuals | ArgQuals) != ParamQuals) {
4400 S.Diag(Arg->getLocStart(),
4401 diag::err_template_arg_ref_bind_ignores_quals)
4402 << ParamType << Arg->getType() << Arg->getSourceRange();
4403 S.Diag(Param->getLocation(), diag::note_template_param_here);
4404 return true;
4405 }
4406 }
4407 }
4408
4409 // At this point, the template argument refers to an object or
4410 // function with external linkage. We now need to check whether the
4411 // argument and parameter types are compatible.
4412 if (!S.Context.hasSameUnqualifiedType(ArgType,
4413 ParamType.getNonReferenceType())) {
4414 // We can't perform this conversion or binding.
4415 if (ParamType->isReferenceType())
4416 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4417 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4418 else
4419 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4420 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4421 S.Diag(Param->getLocation(), diag::note_template_param_here);
4422 return true;
4423 }
4424 }
4425
4426 return false;
4427}
4428
Douglas Gregorccb07762009-02-11 19:52:55 +00004429/// \brief Checks whether the given template argument is the address
4430/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004432CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4433 NonTypeTemplateParmDecl *Param,
4434 QualType ParamType,
4435 Expr *ArgIn,
4436 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004437 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004438 Expr *Arg = ArgIn;
4439 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004440
Douglas Gregorb242683d2010-04-01 18:32:35 +00004441 bool AddressTaken = false;
4442 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004443 if (S.getLangOpts().MicrosoftExt) {
4444 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4445 // dereference and address-of operators.
4446 Arg = Arg->IgnoreParenCasts();
4447
4448 bool ExtWarnMSTemplateArg = false;
4449 UnaryOperatorKind FirstOpKind;
4450 SourceLocation FirstOpLoc;
4451 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4452 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4453 if (UnOpKind == UO_Deref)
4454 ExtWarnMSTemplateArg = true;
4455 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4456 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4457 if (!AddrOpLoc.isValid()) {
4458 FirstOpKind = UnOpKind;
4459 FirstOpLoc = UnOp->getOperatorLoc();
4460 }
4461 } else
4462 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004463 }
David Majnemer61c39a12013-08-23 05:39:39 +00004464 if (FirstOpLoc.isValid()) {
4465 if (ExtWarnMSTemplateArg)
4466 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4467 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004468
David Majnemer61c39a12013-08-23 05:39:39 +00004469 if (FirstOpKind == UO_AddrOf)
4470 AddressTaken = true;
4471 else if (Arg->getType()->isPointerType()) {
4472 // We cannot let pointers get dereferenced here, that is obviously not a
4473 // constant expression.
4474 assert(FirstOpKind == UO_Deref);
4475 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4476 << Arg->getSourceRange();
4477 }
4478 }
4479 } else {
4480 // See through any implicit casts we added to fix the type.
4481 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004482
David Majnemer61c39a12013-08-23 05:39:39 +00004483 // C++ [temp.arg.nontype]p1:
4484 //
4485 // A template-argument for a non-type, non-template
4486 // template-parameter shall be one of: [...]
4487 //
4488 // -- the address of an object or function with external
4489 // linkage, including function templates and function
4490 // template-ids but excluding non-static class members,
4491 // expressed as & id-expression where the & is optional if
4492 // the name refers to a function or array, or if the
4493 // corresponding template-parameter is a reference; or
4494
4495 // In C++98/03 mode, give an extension warning on any extra parentheses.
4496 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4497 bool ExtraParens = false;
4498 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4499 if (!Invalid && !ExtraParens) {
4500 S.Diag(Arg->getLocStart(),
4501 S.getLangOpts().CPlusPlus11
4502 ? diag::warn_cxx98_compat_template_arg_extra_parens
4503 : diag::ext_template_arg_extra_parens)
4504 << Arg->getSourceRange();
4505 ExtraParens = true;
4506 }
4507
4508 Arg = Parens->getSubExpr();
4509 }
4510
4511 while (SubstNonTypeTemplateParmExpr *subst =
4512 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4513 Arg = subst->getReplacement()->IgnoreImpCasts();
4514
4515 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4516 if (UnOp->getOpcode() == UO_AddrOf) {
4517 Arg = UnOp->getSubExpr();
4518 AddressTaken = true;
4519 AddrOpLoc = UnOp->getOperatorLoc();
4520 }
4521 }
4522
4523 while (SubstNonTypeTemplateParmExpr *subst =
4524 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4525 Arg = subst->getReplacement()->IgnoreImpCasts();
4526 }
John McCall7c454bb2011-07-15 05:09:51 +00004527
David Majnemer07910d62014-06-26 07:48:46 +00004528 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4529 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4530
4531 // If our parameter has pointer type, check for a null template value.
4532 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4533 NullPointerValueKind NPV;
4534 // dllimport'd entities aren't constant but are available inside of template
4535 // arguments.
4536 if (Entity && Entity->hasAttr<DLLImportAttr>())
4537 NPV = NPV_NotNullPointer;
4538 else
4539 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4540 switch (NPV) {
4541 case NPV_NullPointer:
4542 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004543 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4544 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004545 return false;
4546
4547 case NPV_Error:
4548 return true;
4549
4550 case NPV_NotNullPointer:
4551 break;
4552 }
4553 }
4554
Chandler Carruth724a8a12010-01-31 10:01:20 +00004555 // Stop checking the precise nature of the argument if it is value dependent,
4556 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004557 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004558 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004559 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004560 }
David Majnemer61c39a12013-08-23 05:39:39 +00004561
4562 if (isa<CXXUuidofExpr>(Arg)) {
4563 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4564 ArgIn, Arg, ArgType))
4565 return true;
4566
4567 Converted = TemplateArgument(ArgIn);
4568 return false;
4569 }
4570
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004571 if (!DRE) {
4572 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4573 << Arg->getSourceRange();
4574 S.Diag(Param->getLocation(), diag::note_template_param_here);
4575 return true;
4576 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004577
Douglas Gregorccb07762009-02-11 19:52:55 +00004578 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004579 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004580 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004581 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004582 S.Diag(Param->getLocation(), diag::note_template_param_here);
4583 return true;
4584 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004585
4586 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004587 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004588 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004589 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004590 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004591 S.Diag(Param->getLocation(), diag::note_template_param_here);
4592 return true;
4593 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004594 }
Mike Stump11289f42009-09-09 15:08:12 +00004595
Richard Smith9380e0e2012-04-04 21:11:30 +00004596 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4597 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004598
Richard Smith9380e0e2012-04-04 21:11:30 +00004599 // A non-type template argument must refer to an object or function.
4600 if (!Func && !Var) {
4601 // We found something, but we don't know specifically what it is.
4602 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4603 << Arg->getSourceRange();
4604 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4605 return true;
4606 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004607
Richard Smith9380e0e2012-04-04 21:11:30 +00004608 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004609 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004610 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004611 diag::warn_cxx98_compat_template_arg_object_internal :
4612 diag::ext_template_arg_object_internal)
4613 << !Func << Entity << Arg->getSourceRange();
4614 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4615 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004616 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004617 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4618 << !Func << Entity << Arg->getSourceRange();
4619 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4620 << !Func;
4621 return true;
4622 }
4623
4624 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004625 // If the template parameter has pointer type, the function decays.
4626 if (ParamType->isPointerType() && !AddressTaken)
4627 ArgType = S.Context.getPointerType(Func->getType());
4628 else if (AddressTaken && ParamType->isReferenceType()) {
4629 // If we originally had an address-of operator, but the
4630 // parameter has reference type, complain and (if things look
4631 // like they will work) drop the address-of operator.
4632 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4633 ParamType.getNonReferenceType())) {
4634 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4635 << ParamType;
4636 S.Diag(Param->getLocation(), diag::note_template_param_here);
4637 return true;
4638 }
4639
4640 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4641 << ParamType
4642 << FixItHint::CreateRemoval(AddrOpLoc);
4643 S.Diag(Param->getLocation(), diag::note_template_param_here);
4644
4645 ArgType = Func->getType();
4646 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004647 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004648 // A value of reference type is not an object.
4649 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004650 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004651 diag::err_template_arg_reference_var)
4652 << Var->getType() << Arg->getSourceRange();
4653 S.Diag(Param->getLocation(), diag::note_template_param_here);
4654 return true;
4655 }
4656
Richard Smith9380e0e2012-04-04 21:11:30 +00004657 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004658 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004659 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4660 << Arg->getSourceRange();
4661 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4662 return true;
4663 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004664
4665 // If the template parameter has pointer type, we must have taken
4666 // the address of this object.
4667 if (ParamType->isReferenceType()) {
4668 if (AddressTaken) {
4669 // If we originally had an address-of operator, but the
4670 // parameter has reference type, complain and (if things look
4671 // like they will work) drop the address-of operator.
4672 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4673 ParamType.getNonReferenceType())) {
4674 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4675 << ParamType;
4676 S.Diag(Param->getLocation(), diag::note_template_param_here);
4677 return true;
4678 }
4679
4680 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4681 << ParamType
4682 << FixItHint::CreateRemoval(AddrOpLoc);
4683 S.Diag(Param->getLocation(), diag::note_template_param_here);
4684
4685 ArgType = Var->getType();
4686 }
4687 } else if (!AddressTaken && ParamType->isPointerType()) {
4688 if (Var->getType()->isArrayType()) {
4689 // Array-to-pointer decay.
4690 ArgType = S.Context.getArrayDecayedType(Var->getType());
4691 } else {
4692 // If the template parameter has pointer type but the address of
4693 // this object was not taken, complain and (possibly) recover by
4694 // taking the address of the entity.
4695 ArgType = S.Context.getPointerType(Var->getType());
4696 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4697 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4698 << ParamType;
4699 S.Diag(Param->getLocation(), diag::note_template_param_here);
4700 return true;
4701 }
4702
4703 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4704 << ParamType
4705 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4706
4707 S.Diag(Param->getLocation(), diag::note_template_param_here);
4708 }
4709 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004710 }
Mike Stump11289f42009-09-09 15:08:12 +00004711
David Majnemer61c39a12013-08-23 05:39:39 +00004712 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4713 Arg, ArgType))
4714 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004715
4716 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004717 Converted =
4718 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004719 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004720 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004721}
4722
4723/// \brief Checks whether the given template argument is a pointer to
4724/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004725static bool CheckTemplateArgumentPointerToMember(Sema &S,
4726 NonTypeTemplateParmDecl *Param,
4727 QualType ParamType,
4728 Expr *&ResultArg,
4729 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004730 bool Invalid = false;
4731
Douglas Gregor20fdef32012-04-10 17:08:25 +00004732 // Check for a null pointer value.
4733 Expr *Arg = ResultArg;
4734 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4735 case NPV_Error:
4736 return true;
4737 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004738 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004739 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4740 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004741 return false;
4742 case NPV_NotNullPointer:
4743 break;
4744 }
4745
4746 bool ObjCLifetimeConversion;
4747 if (S.IsQualificationConversion(Arg->getType(),
4748 ParamType.getNonReferenceType(),
4749 false, ObjCLifetimeConversion)) {
4750 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004751 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004752 ResultArg = Arg;
4753 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4754 ParamType.getNonReferenceType())) {
4755 // We can't perform this conversion.
4756 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4757 << Arg->getType() << ParamType << Arg->getSourceRange();
4758 S.Diag(Param->getLocation(), diag::note_template_param_here);
4759 return true;
4760 }
4761
Douglas Gregorccb07762009-02-11 19:52:55 +00004762 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004763 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004764 Arg = Cast->getSubExpr();
4765
4766 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004767 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004768 // A template-argument for a non-type, non-template
4769 // template-parameter shall be one of: [...]
4770 //
4771 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004772 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004773
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004774 // In C++98/03 mode, give an extension warning on any extra parentheses.
4775 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4776 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004777 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004778 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004779 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004780 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004781 diag::warn_cxx98_compat_template_arg_extra_parens :
4782 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004783 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004784 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004785 }
4786
4787 Arg = Parens->getSubExpr();
4788 }
4789
John McCall7c454bb2011-07-15 05:09:51 +00004790 while (SubstNonTypeTemplateParmExpr *subst =
4791 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4792 Arg = subst->getReplacement()->IgnoreImpCasts();
4793
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004794 // A pointer-to-member constant written &Class::member.
4795 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004796 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004797 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4798 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004799 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004802 // A constant of pointer-to-member type.
4803 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4804 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4805 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004806 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004807 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004808 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004809 } else {
4810 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004811 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004812 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004813 return Invalid;
4814 }
4815 }
4816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Craig Topperc3ec1492014-05-26 06:22:03 +00004818 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Douglas Gregorccb07762009-02-11 19:52:55 +00004821 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004822 return S.Diag(Arg->getLocStart(),
4823 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004824 << Arg->getSourceRange();
4825
David Majnemer3ac84e62013-10-22 21:56:38 +00004826 if (isa<FieldDecl>(DRE->getDecl()) ||
4827 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4828 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004829 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004830 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004831 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4832 "Only non-static member pointers can make it here");
4833
4834 // Okay: this is the address of a non-static member, and therefore
4835 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004836 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004837 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004838 } else {
4839 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004840 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004841 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004842 return Invalid;
4843 }
4844
4845 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004846 S.Diag(Arg->getLocStart(),
4847 diag::err_template_arg_not_pointer_to_member_form)
4848 << Arg->getSourceRange();
4849 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004850 return true;
4851}
4852
Douglas Gregord32e0282009-02-09 23:23:08 +00004853/// \brief Check a template argument against its corresponding
4854/// non-type template parameter.
4855///
Douglas Gregor463421d2009-03-03 04:44:36 +00004856/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004857/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004858/// returns the converted template argument. \p ParamType is the
4859/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004860ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004861 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004862 TemplateArgument &Converted,
4863 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004864 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004865
Douglas Gregor86560402009-02-10 23:36:10 +00004866 // If either the parameter has a dependent type or the argument is
4867 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004868 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004869 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004870 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004871 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004872 }
Douglas Gregor86560402009-02-10 23:36:10 +00004873
Richard Smithd663fdd2014-12-17 20:42:37 +00004874 // We should have already dropped all cv-qualifiers by now.
4875 assert(!ParamType.hasQualifiers() &&
4876 "non-type template parameter type cannot be qualified");
4877
4878 if (CTAK == CTAK_Deduced &&
4879 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4880 // C++ [temp.deduct.type]p17:
4881 // If, in the declaration of a function template with a non-type
4882 // template-parameter, the non-type template-parameter is used
4883 // in an expression in the function parameter-list and, if the
4884 // corresponding template-argument is deduced, the
4885 // template-argument type shall match the type of the
4886 // template-parameter exactly, except that a template-argument
4887 // deduced from an array bound may be of any integral type.
4888 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4889 << Arg->getType().getUnqualifiedType()
4890 << ParamType.getUnqualifiedType();
4891 Diag(Param->getLocation(), diag::note_template_param_here);
4892 return ExprError();
4893 }
4894
Richard Smith410cc892014-11-26 03:26:53 +00004895 if (getLangOpts().CPlusPlus1z) {
4896 // FIXME: We can do some limited checking for a value-dependent but not
4897 // type-dependent argument.
4898 if (Arg->isValueDependent()) {
4899 Converted = TemplateArgument(Arg);
4900 return Arg;
4901 }
4902
4903 // C++1z [temp.arg.nontype]p1:
4904 // A template-argument for a non-type template parameter shall be
4905 // a converted constant expression of the type of the template-parameter.
4906 APValue Value;
4907 ExprResult ArgResult = CheckConvertedConstantExpression(
4908 Arg, ParamType, Value, CCEK_TemplateArg);
4909 if (ArgResult.isInvalid())
4910 return ExprError();
4911
Richard Smithd663fdd2014-12-17 20:42:37 +00004912 QualType CanonParamType = Context.getCanonicalType(ParamType);
4913
Richard Smith410cc892014-11-26 03:26:53 +00004914 // Convert the APValue to a TemplateArgument.
4915 switch (Value.getKind()) {
4916 case APValue::Uninitialized:
4917 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004918 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004919 break;
4920 case APValue::Int:
4921 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004922 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004923 break;
4924 case APValue::MemberPointer: {
4925 assert(ParamType->isMemberPointerType());
4926
4927 // FIXME: We need TemplateArgument representation and mangling for these.
4928 if (!Value.getMemberPointerPath().empty()) {
4929 Diag(Arg->getLocStart(),
4930 diag::err_template_arg_member_ptr_base_derived_not_supported)
4931 << Value.getMemberPointerDecl() << ParamType
4932 << Arg->getSourceRange();
4933 return ExprError();
4934 }
4935
4936 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004937 Converted = VD ? TemplateArgument(VD, CanonParamType)
4938 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004939 break;
4940 }
4941 case APValue::LValue: {
4942 // For a non-type template-parameter of pointer or reference type,
4943 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004944 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4945 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004946 // -- a temporary object
4947 // -- a string literal
4948 // -- the result of a typeid expression, or
4949 // -- a predefind __func__ variable
4950 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4951 if (isa<CXXUuidofExpr>(E)) {
4952 Converted = TemplateArgument(const_cast<Expr*>(E));
4953 break;
4954 }
4955 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4956 << Arg->getSourceRange();
4957 return ExprError();
4958 }
4959 auto *VD = const_cast<ValueDecl *>(
4960 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4961 // -- a subobject
4962 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4963 VD && VD->getType()->isArrayType() &&
4964 Value.getLValuePath()[0].ArrayIndex == 0 &&
4965 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4966 // Per defect report (no number yet):
4967 // ... other than a pointer to the first element of a complete array
4968 // object.
4969 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4970 Value.isLValueOnePastTheEnd()) {
4971 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4972 << Value.getAsString(Context, ParamType);
4973 return ExprError();
4974 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004975 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004976 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004977 assert((!VD || !ParamType->isNullPtrType()) &&
4978 "non-null value of type nullptr_t?");
4979 Converted = VD ? TemplateArgument(VD, CanonParamType)
4980 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004981 break;
4982 }
4983 case APValue::AddrLabelDiff:
4984 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4985 case APValue::Float:
4986 case APValue::ComplexInt:
4987 case APValue::ComplexFloat:
4988 case APValue::Vector:
4989 case APValue::Array:
4990 case APValue::Struct:
4991 case APValue::Union:
4992 llvm_unreachable("invalid kind for template argument");
4993 }
4994
4995 return ArgResult.get();
4996 }
4997
Douglas Gregor86560402009-02-10 23:36:10 +00004998 // C++ [temp.arg.nontype]p5:
4999 // The following conversions are performed on each expression used
5000 // as a non-type template-argument. If a non-type
5001 // template-argument cannot be converted to the type of the
5002 // corresponding template-parameter then the program is
5003 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005004 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005005 // C++11:
5006 // -- for a non-type template-parameter of integral or
5007 // enumeration type, conversions permitted in a converted
5008 // constant expression are applied.
5009 //
5010 // C++98:
5011 // -- for a non-type template-parameter of integral or
5012 // enumeration type, integral promotions (4.5) and integral
5013 // conversions (4.7) are applied.
5014
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005015 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005016 // We can't check arbitrary value-dependent arguments.
5017 // FIXME: If there's no viable conversion to the template parameter type,
5018 // we should be able to diagnose that prior to instantiation.
5019 if (Arg->isValueDependent()) {
5020 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005021 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005022 }
5023
5024 // C++ [temp.arg.nontype]p1:
5025 // A template-argument for a non-type, non-template template-parameter
5026 // shall be one of:
5027 //
5028 // -- for a non-type template-parameter of integral or enumeration
5029 // type, a converted constant expression of the type of the
5030 // template-parameter; or
5031 llvm::APSInt Value;
5032 ExprResult ArgResult =
5033 CheckConvertedConstantExpression(Arg, ParamType, Value,
5034 CCEK_TemplateArg);
5035 if (ArgResult.isInvalid())
5036 return ExprError();
5037
5038 // Widen the argument value to sizeof(parameter type). This is almost
5039 // always a no-op, except when the parameter type is bool. In
5040 // that case, this may extend the argument from 1 bit to 8 bits.
5041 QualType IntegerType = ParamType;
5042 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5043 IntegerType = Enum->getDecl()->getIntegerType();
5044 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5045
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005046 Converted = TemplateArgument(Context, Value,
5047 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005048 return ArgResult;
5049 }
5050
Richard Smith08b12f12011-10-27 22:11:44 +00005051 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5052 if (ArgResult.isInvalid())
5053 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005054 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005055
5056 QualType ArgType = Arg->getType();
5057
Douglas Gregor86560402009-02-10 23:36:10 +00005058 // C++ [temp.arg.nontype]p1:
5059 // A template-argument for a non-type, non-template
5060 // template-parameter shall be one of:
5061 //
5062 // -- an integral constant-expression of integral or enumeration
5063 // type; or
5064 // -- the name of a non-type template-parameter; or
5065 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005066 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005067 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005068 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005069 diag::err_template_arg_not_integral_or_enumeral)
5070 << ArgType << Arg->getSourceRange();
5071 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005072 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005073 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005074 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5075 QualType T;
5076
5077 public:
5078 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005079
5080 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5081 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005082 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5083 }
5084 } Diagnoser(ArgType);
5085
5086 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005087 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005088 if (!Arg)
5089 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005090 }
5091
Richard Smithd663fdd2014-12-17 20:42:37 +00005092 // From here on out, all we care about is the unqualified form
5093 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005094 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005095
5096 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005097 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005098 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005099 } else if (ParamType->isBooleanType()) {
5100 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005101 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005102 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5103 !ParamType->isEnumeralType()) {
5104 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005105 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005106 } else {
5107 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005108 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005109 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005110 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005111 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005112 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005113 }
5114
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005115 // Add the value of this argument to the list of converted
5116 // arguments. We use the bitwidth and signedness of the template
5117 // parameter.
5118 if (Arg->isValueDependent()) {
5119 // The argument is value-dependent. Create a new
5120 // TemplateArgument with the converted expression.
5121 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005122 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005123 }
5124
Douglas Gregor52aba872009-03-14 00:20:21 +00005125 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005126 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005127 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005128
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005129 if (ParamType->isBooleanType()) {
5130 // Value must be zero or one.
5131 Value = Value != 0;
5132 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5133 if (Value.getBitWidth() != AllowedBits)
5134 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005135 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005136 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005137 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005138
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005139 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005140 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005141 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005142 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005143 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005144 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005145
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005146 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005147 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005148 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005149 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005150 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5151 << Arg->getSourceRange();
5152 Diag(Param->getLocation(), diag::note_template_param_here);
5153 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005154
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005155 // Complain if we overflowed the template parameter's type.
5156 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005157 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005158 RequiredBits = OldValue.getActiveBits();
5159 else if (OldValue.isUnsigned())
5160 RequiredBits = OldValue.getActiveBits() + 1;
5161 else
5162 RequiredBits = OldValue.getMinSignedBits();
5163 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005164 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005165 diag::warn_template_arg_too_large)
5166 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5167 << Arg->getSourceRange();
5168 Diag(Param->getLocation(), diag::note_template_param_here);
5169 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005170 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005171
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005172 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005173 ParamType->isEnumeralType()
5174 ? Context.getCanonicalType(ParamType)
5175 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005176 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005177 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005178
Richard Smith08b12f12011-10-27 22:11:44 +00005179 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005180 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5181
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005182 // Handle pointer-to-function, reference-to-function, and
5183 // pointer-to-member-function all in (roughly) the same way.
5184 if (// -- For a non-type template-parameter of type pointer to
5185 // function, only the function-to-pointer conversion (4.3) is
5186 // applied. If the template-argument represents a set of
5187 // overloaded functions (or a pointer to such), the matching
5188 // function is selected from the set (13.4).
5189 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005190 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005191 // -- For a non-type template-parameter of type reference to
5192 // function, no conversions apply. If the template-argument
5193 // represents a set of overloaded functions, the matching
5194 // function is selected from the set (13.4).
5195 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005196 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005197 // -- For a non-type template-parameter of type pointer to
5198 // member function, no conversions apply. If the
5199 // template-argument represents a set of overloaded member
5200 // functions, the matching member function is selected from
5201 // the set (13.4).
5202 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005203 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005204 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005205
Douglas Gregor064fdb22010-04-14 23:11:21 +00005206 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005208 true,
5209 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005210 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005211 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005212
5213 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5214 ArgType = Arg->getType();
5215 } else
John Wiegley01296292011-04-08 18:41:53 +00005216 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005217 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005218
John Wiegley01296292011-04-08 18:41:53 +00005219 if (!ParamType->isMemberPointerType()) {
5220 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5221 ParamType,
5222 Arg, Converted))
5223 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005224 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005225 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005226
Douglas Gregor20fdef32012-04-10 17:08:25 +00005227 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5228 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005229 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005230 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005231 }
5232
Chris Lattner696197c2009-02-20 21:37:53 +00005233 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005234 // -- for a non-type template-parameter of type pointer to
5235 // object, qualification conversions (4.4) and the
5236 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005237 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005238 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005239 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005240
John Wiegley01296292011-04-08 18:41:53 +00005241 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5242 ParamType,
5243 Arg, Converted))
5244 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005245 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005246 }
Mike Stump11289f42009-09-09 15:08:12 +00005247
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005248 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005249 // -- For a non-type template-parameter of type reference to
5250 // object, no conversions apply. The type referred to by the
5251 // reference may be more cv-qualified than the (otherwise
5252 // identical) type of the template-argument. The
5253 // template-parameter is bound directly to the
5254 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005255 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005256 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005257
Douglas Gregor064fdb22010-04-14 23:11:21 +00005258 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005259 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5260 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005261 true,
5262 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005263 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005264 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005265
5266 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5267 ArgType = Arg->getType();
5268 } else
John Wiegley01296292011-04-08 18:41:53 +00005269 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005271
John Wiegley01296292011-04-08 18:41:53 +00005272 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5273 ParamType,
5274 Arg, Converted))
5275 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005276 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005277 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005278
Douglas Gregor20fdef32012-04-10 17:08:25 +00005279 // Deal with parameters of type std::nullptr_t.
5280 if (ParamType->isNullPtrType()) {
5281 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5282 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005283 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005284 }
5285
5286 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5287 case NPV_NotNullPointer:
5288 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5289 << Arg->getType() << ParamType;
5290 Diag(Param->getLocation(), diag::note_template_param_here);
5291 return ExprError();
5292
5293 case NPV_Error:
5294 return ExprError();
5295
5296 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005297 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005298 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5299 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005300 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005301 }
5302 }
5303
Douglas Gregor0e558532009-02-11 16:16:59 +00005304 // -- For a non-type template-parameter of type pointer to data
5305 // member, qualification conversions (4.4) are applied.
5306 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5307
Douglas Gregor20fdef32012-04-10 17:08:25 +00005308 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5309 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005310 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005311 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005312}
5313
5314/// \brief Check a template argument against its corresponding
5315/// template template parameter.
5316///
5317/// This routine implements the semantics of C++ [temp.arg.template].
5318/// It returns true if an error occurred, and false otherwise.
5319bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005320 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005321 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005322 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005323 TemplateDecl *Template = Name.getAsTemplateDecl();
5324 if (!Template) {
5325 // Any dependent template name is fine.
5326 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5327 return false;
5328 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005329
Richard Smith3f1b5d02011-05-05 21:57:07 +00005330 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005331 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005332 // the name of a class template or an alias template, expressed as an
5333 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005334 // primary class templates are considered when matching the
5335 // template template argument with the corresponding parameter;
5336 // partial specializations are not considered even if their
5337 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005338 //
5339 // Note that we also allow template template parameters here, which
5340 // will happen when we are dealing with, e.g., class template
5341 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005342 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005343 !isa<TemplateTemplateParmDecl>(Template) &&
5344 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005345 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005346 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005347 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005348 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005349 << Template;
5350 }
5351
Richard Smith1fde8ec2012-09-07 02:06:42 +00005352 TemplateParameterList *Params = Param->getTemplateParameters();
5353 if (Param->isExpandedParameterPack())
5354 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5355
Douglas Gregor85e0f662009-02-10 00:24:35 +00005356 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005357 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005359 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005360 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005361}
5362
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005363/// \brief Given a non-type template argument that refers to a
5364/// declaration and the type of its corresponding non-type template
5365/// parameter, produce an expression that properly refers to that
5366/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005368Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5369 QualType ParamType,
5370 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005371 // C++ [temp.param]p8:
5372 //
5373 // A non-type template-parameter of type "array of T" or
5374 // "function returning T" is adjusted to be of type "pointer to
5375 // T" or "pointer to function returning T", respectively.
5376 if (ParamType->isArrayType())
5377 ParamType = Context.getArrayDecayedType(ParamType);
5378 else if (ParamType->isFunctionType())
5379 ParamType = Context.getPointerType(ParamType);
5380
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005381 // For a NULL non-type template argument, return nullptr casted to the
5382 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005383 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005384 return ImpCastExprToType(
5385 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5386 ParamType,
5387 ParamType->getAs<MemberPointerType>()
5388 ? CK_NullToMemberPointer
5389 : CK_NullToPointer);
5390 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005391 assert(Arg.getKind() == TemplateArgument::Declaration &&
5392 "Only declaration template arguments permitted here");
5393
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005394 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5395
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005396 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005397 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5398 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005399 // If the value is a class member, we might have a pointer-to-member.
5400 // Determine whether the non-type template template parameter is of
5401 // pointer-to-member type. If so, we need to build an appropriate
5402 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5403 // would refer to the member itself.
5404 if (ParamType->isMemberPointerType()) {
5405 QualType ClassType
5406 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5407 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005408 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005409 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005410 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005411 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005412
5413 // The actual value-ness of this is unimportant, but for
5414 // internal consistency's sake, references to instance methods
5415 // are r-values.
5416 ExprValueKind VK = VK_LValue;
5417 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5418 VK = VK_RValue;
5419
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005420 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005421 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005422 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005423 Loc,
5424 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005425 if (RefExpr.isInvalid())
5426 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
John McCalle3027922010-08-25 11:45:40 +00005428 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005429
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005430 // We might need to perform a trailing qualification conversion, since
5431 // the element type on the parameter could be more qualified than the
5432 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005433 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005434 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005435 ParamType.getUnqualifiedType(), false,
5436 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005437 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005439 assert(!RefExpr.isInvalid() &&
5440 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005441 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005442 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005443 }
5444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005446 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005447
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005448 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005449 // When the non-type template parameter is a pointer, take the
5450 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005451 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005452 if (RefExpr.isInvalid())
5453 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005454
5455 if (T->isFunctionType() || T->isArrayType()) {
5456 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005457 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005458 if (RefExpr.isInvalid())
5459 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005460
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005461 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463
Douglas Gregorb242683d2010-04-01 18:32:35 +00005464 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005465 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005466 }
5467
John McCall7decc9e2010-11-18 06:31:45 +00005468 ExprValueKind VK = VK_RValue;
5469
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005470 // If the non-type template parameter has reference type, qualify the
5471 // resulting declaration reference with the extra qualifiers on the
5472 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005473 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5474 VK = VK_LValue;
5475 T = Context.getQualifiedType(T,
5476 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005477 } else if (isa<FunctionDecl>(VD)) {
5478 // References to functions are always lvalues.
5479 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
John McCall7decc9e2010-11-18 06:31:45 +00005482 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005483}
5484
5485/// \brief Construct a new expression that refers to the given
5486/// integral template argument with the given source-location
5487/// information.
5488///
5489/// This routine takes care of the mapping from an integral template
5490/// argument (which may have any integral type) to the appropriate
5491/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005493Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5494 SourceLocation Loc) {
5495 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005496 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005497 QualType OrigT = Arg.getIntegralType();
5498
5499 // If this is an enum type that we're instantiating, we need to use an integer
5500 // type the same size as the enumerator. We don't want to build an
5501 // IntegerLiteral with enum type. The integer type of an enum type can be of
5502 // any integral type with C++11 enum classes, make sure we create the right
5503 // type of literal for it.
5504 QualType T = OrigT;
5505 if (const EnumType *ET = OrigT->getAs<EnumType>())
5506 T = ET->getDecl()->getIntegerType();
5507
5508 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005509 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005510 // This does not need to handle u8 character literals because those are
5511 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005512 CharacterLiteral::CharacterKind Kind;
5513 if (T->isWideCharType())
5514 Kind = CharacterLiteral::Wide;
5515 else if (T->isChar16Type())
5516 Kind = CharacterLiteral::UTF16;
5517 else if (T->isChar32Type())
5518 Kind = CharacterLiteral::UTF32;
5519 else
5520 Kind = CharacterLiteral::Ascii;
5521
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005522 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5523 Kind, T, Loc);
5524 } else if (T->isBooleanType()) {
5525 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5526 T, Loc);
5527 } else if (T->isNullPtrType()) {
5528 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5529 } else {
5530 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005531 }
5532
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005533 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005534 // FIXME: This is a hack. We need a better way to handle substituted
5535 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005536 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5537 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005538 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005539 Loc, Loc);
5540 }
5541
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005542 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005543}
5544
Douglas Gregor641040a2011-01-12 23:45:44 +00005545/// \brief Match two template parameters within template parameter lists.
5546static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5547 bool Complain,
5548 Sema::TemplateParameterListEqualKind Kind,
5549 SourceLocation TemplateArgLoc) {
5550 // Check the actual kind (type, non-type, template).
5551 if (Old->getKind() != New->getKind()) {
5552 if (Complain) {
5553 unsigned NextDiag = diag::err_template_param_different_kind;
5554 if (TemplateArgLoc.isValid()) {
5555 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5556 NextDiag = diag::note_template_param_different_kind;
5557 }
5558 S.Diag(New->getLocation(), NextDiag)
5559 << (Kind != Sema::TPL_TemplateMatch);
5560 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5561 << (Kind != Sema::TPL_TemplateMatch);
5562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Douglas Gregor641040a2011-01-12 23:45:44 +00005564 return false;
5565 }
5566
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005567 // Check that both are parameter packs are neither are parameter packs.
5568 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005569 // template template parameter, the template template parameter can have
5570 // a parameter pack where the template template argument does not.
5571 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5572 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5573 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005574 if (Complain) {
5575 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5576 if (TemplateArgLoc.isValid()) {
5577 S.Diag(TemplateArgLoc,
5578 diag::err_template_arg_template_params_mismatch);
5579 NextDiag = diag::note_template_parameter_pack_non_pack;
5580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
Douglas Gregor641040a2011-01-12 23:45:44 +00005582 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5583 : isa<NonTypeTemplateParmDecl>(New)? 1
5584 : 2;
5585 S.Diag(New->getLocation(), NextDiag)
5586 << ParamKind << New->isParameterPack();
5587 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5588 << ParamKind << Old->isParameterPack();
5589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005590
Douglas Gregor641040a2011-01-12 23:45:44 +00005591 return false;
5592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005593
Douglas Gregor641040a2011-01-12 23:45:44 +00005594 // For non-type template parameters, check the type of the parameter.
5595 if (NonTypeTemplateParmDecl *OldNTTP
5596 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5597 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598
Douglas Gregor641040a2011-01-12 23:45:44 +00005599 // If we are matching a template template argument to a template
5600 // template parameter and one of the non-type template parameter types
5601 // is dependent, then we must wait until template instantiation time
5602 // to actually compare the arguments.
5603 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5604 (OldNTTP->getType()->isDependentType() ||
5605 NewNTTP->getType()->isDependentType()))
5606 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607
Douglas Gregor641040a2011-01-12 23:45:44 +00005608 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5609 if (Complain) {
5610 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5611 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005613 diag::err_template_arg_template_params_mismatch);
5614 NextDiag = diag::note_template_nontype_parm_different_type;
5615 }
5616 S.Diag(NewNTTP->getLocation(), NextDiag)
5617 << NewNTTP->getType()
5618 << (Kind != Sema::TPL_TemplateMatch);
5619 S.Diag(OldNTTP->getLocation(),
5620 diag::note_template_nontype_parm_prev_declaration)
5621 << OldNTTP->getType();
5622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
Douglas Gregor641040a2011-01-12 23:45:44 +00005624 return false;
5625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Douglas Gregor641040a2011-01-12 23:45:44 +00005627 return true;
5628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
Douglas Gregor641040a2011-01-12 23:45:44 +00005630 // For template template parameters, check the template parameter types.
5631 // The template parameter lists of template template
5632 // parameters must agree.
5633 if (TemplateTemplateParmDecl *OldTTP
5634 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005635 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005636 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5637 OldTTP->getTemplateParameters(),
5638 Complain,
5639 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005641 : Kind),
5642 TemplateArgLoc);
5643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005644
Douglas Gregor641040a2011-01-12 23:45:44 +00005645 return true;
5646}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005647
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005648/// \brief Diagnose a known arity mismatch when comparing template argument
5649/// lists.
5650static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005651void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005652 TemplateParameterList *New,
5653 TemplateParameterList *Old,
5654 Sema::TemplateParameterListEqualKind Kind,
5655 SourceLocation TemplateArgLoc) {
5656 unsigned NextDiag = diag::err_template_param_list_different_arity;
5657 if (TemplateArgLoc.isValid()) {
5658 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5659 NextDiag = diag::note_template_param_list_different_arity;
5660 }
5661 S.Diag(New->getTemplateLoc(), NextDiag)
5662 << (New->size() > Old->size())
5663 << (Kind != Sema::TPL_TemplateMatch)
5664 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5665 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5666 << (Kind != Sema::TPL_TemplateMatch)
5667 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5668}
5669
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005670/// \brief Determine whether the given template parameter lists are
5671/// equivalent.
5672///
Mike Stump11289f42009-09-09 15:08:12 +00005673/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005674/// source code as part of a new template declaration.
5675///
5676/// \param Old The old template parameter list, typically found via
5677/// name lookup of the template declared with this template parameter
5678/// list.
5679///
5680/// \param Complain If true, this routine will produce a diagnostic if
5681/// the template parameter lists are not equivalent.
5682///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005683/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005684///
5685/// \param TemplateArgLoc If this source location is valid, then we
5686/// are actually checking the template parameter list of a template
5687/// argument (New) against the template parameter list of its
5688/// corresponding template template parameter (Old). We produce
5689/// slightly different diagnostics in this scenario.
5690///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005691/// \returns True if the template parameter lists are equal, false
5692/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005693bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005694Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5695 TemplateParameterList *Old,
5696 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005697 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005698 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005699 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5700 if (Complain)
5701 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5702 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005703
5704 return false;
5705 }
5706
Douglas Gregor641040a2011-01-12 23:45:44 +00005707 // C++0x [temp.arg.template]p3:
5708 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005709 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005710 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005711 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005712 // template-parameter-list of P. [...]
5713 TemplateParameterList::iterator NewParm = New->begin();
5714 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005715 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005716 OldParmEnd = Old->end();
5717 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005718 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5719 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005720 if (NewParm == NewParmEnd) {
5721 if (Complain)
5722 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5723 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005725 return false;
5726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005727
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005728 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5729 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730 return false;
5731
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005732 ++NewParm;
5733 continue;
5734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005735
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005736 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005737 // [...] When P's template- parameter-list contains a template parameter
5738 // pack (14.5.3), the template parameter pack will match zero or more
5739 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005740 // template-parameter-list of A with the same type and form as the
5741 // template parameter pack in P (ignoring whether those template
5742 // parameters are template parameter packs).
5743 for (; NewParm != NewParmEnd; ++NewParm) {
5744 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5745 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005747 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005749
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005750 // Make sure we exhausted all of the arguments.
5751 if (NewParm != NewParmEnd) {
5752 if (Complain)
5753 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5754 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005755
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005756 return false;
5757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005758
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005759 return true;
5760}
5761
5762/// \brief Check whether a template can be declared within this scope.
5763///
5764/// If the template declaration is valid in this scope, returns
5765/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005766bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005767Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005768 if (!S)
5769 return false;
5770
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005771 // Find the nearest enclosing declaration scope.
5772 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5773 (S->getFlags() & Scope::TemplateParamScope) != 0)
5774 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005775
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005776 // C++ [temp]p4:
5777 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005778 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005779 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005780 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005781 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005782
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005783 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005784 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005785
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005786 // C++ [temp]p2:
5787 // A template-declaration can appear only as a namespace scope or
5788 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005789 if (Ctx) {
5790 if (Ctx->isFileContext())
5791 return false;
5792 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5793 // C++ [temp.mem]p2:
5794 // A local class shall not have member templates.
5795 if (RD->isLocalClass())
5796 return Diag(TemplateParams->getTemplateLoc(),
5797 diag::err_template_inside_local_class)
5798 << TemplateParams->getSourceRange();
5799 else
5800 return false;
5801 }
5802 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005803
Mike Stump11289f42009-09-09 15:08:12 +00005804 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005805 diag::err_template_outside_namespace_or_class_scope)
5806 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005807}
Douglas Gregor67a65642009-02-17 23:15:12 +00005808
Douglas Gregor54888652009-10-07 00:13:32 +00005809/// \brief Determine what kind of template specialization the given declaration
5810/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005811static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005812 if (!D)
5813 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005814
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005815 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5816 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005817 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5818 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005819 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5820 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821
Douglas Gregor54888652009-10-07 00:13:32 +00005822 return TSK_Undeclared;
5823}
5824
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005825/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005826/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005827///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005828/// This routine determines whether a template specialization can be declared
5829/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005830///
5831/// \param S the semantic analysis object for which this check is being
5832/// performed.
5833///
5834/// \param Specialized the entity being specialized or instantiated, which
5835/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005836/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005837/// member class).
5838///
5839/// \param PrevDecl the previous declaration of this entity, if any.
5840///
5841/// \param Loc the location of the explicit specialization or instantiation of
5842/// this entity.
5843///
5844/// \param IsPartialSpecialization whether this is a partial specialization of
5845/// a class template.
5846///
Douglas Gregor54888652009-10-07 00:13:32 +00005847/// \returns true if there was an error that we cannot recover from, false
5848/// otherwise.
5849static bool CheckTemplateSpecializationScope(Sema &S,
5850 NamedDecl *Specialized,
5851 NamedDecl *PrevDecl,
5852 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005853 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005854 // Keep these "kind" numbers in sync with the %select statements in the
5855 // various diagnostics emitted by this routine.
5856 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005857 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005858 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005859 else if (isa<VarTemplateDecl>(Specialized))
5860 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005861 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005862 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005863 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005864 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005865 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005866 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005867 else if (isa<RecordDecl>(Specialized))
5868 EntityKind = 7;
5869 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5870 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005871 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005872 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005873 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005874 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005875 return true;
5876 }
5877
Douglas Gregorf47b9112009-02-25 22:02:03 +00005878 // C++ [temp.expl.spec]p2:
5879 // An explicit specialization shall be declared in the namespace
5880 // of which the template is a member, or, for member templates, in
5881 // the namespace of which the enclosing class or enclosing class
5882 // template is a member. An explicit specialization of a member
5883 // function, member class or static data member of a class
5884 // template shall be declared in the namespace of which the class
5885 // template is a member. Such a declaration may also be a
5886 // definition. If the declaration is not a definition, the
5887 // specialization may be defined later in the name- space in which
5888 // the explicit specialization was declared, or in a namespace
5889 // that encloses the one in which the explicit specialization was
5890 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005891 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005892 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005893 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005894 return true;
5895 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005896
Douglas Gregor40fb7442009-10-07 17:30:37 +00005897 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005898 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005899 // Do not warn for class scope explicit specialization during
5900 // instantiation, warning was already emitted during pattern
5901 // semantic analysis.
5902 if (!S.ActiveTemplateInstantiations.size())
5903 S.Diag(Loc, diag::ext_function_specialization_in_class)
5904 << Specialized;
5905 } else {
5906 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5907 << Specialized;
5908 return true;
5909 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005911
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005912 if (S.CurContext->isRecord() &&
5913 !S.CurContext->Equals(Specialized->getDeclContext())) {
5914 // Make sure that we're specializing in the right record context.
5915 // Otherwise, things can go horribly wrong.
5916 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5917 << Specialized;
5918 return true;
5919 }
5920
Douglas Gregore4b05162009-10-07 17:21:34 +00005921 // C++ [temp.class.spec]p6:
5922 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005923 // in any namespace scope in which its definition may be defined (14.5.1
5924 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005925 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005926 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005927 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005928
5929 // Make sure that this redeclaration (or definition) occurs in an enclosing
5930 // namespace.
5931 // Note that HandleDeclarator() performs this check for explicit
5932 // specializations of function templates, static data members, and member
5933 // functions, so we skip the check here for those kinds of entities.
5934 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5935 // Should we refactor that check, so that it occurs later?
5936 if (!DC->Encloses(SpecializedContext) &&
5937 !(isa<FunctionTemplateDecl>(Specialized) ||
5938 isa<FunctionDecl>(Specialized) ||
5939 isa<VarTemplateDecl>(Specialized) ||
5940 isa<VarDecl>(Specialized))) {
5941 if (isa<TranslationUnitDecl>(SpecializedContext))
5942 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5943 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005944 else if (isa<NamespaceDecl>(SpecializedContext)) {
5945 int Diag = diag::err_template_spec_redecl_out_of_scope;
5946 if (S.getLangOpts().MicrosoftExt)
5947 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5948 S.Diag(Loc, Diag) << EntityKind << Specialized
5949 << cast<NamedDecl>(SpecializedContext);
5950 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005951 llvm_unreachable("unexpected namespace context for specialization");
5952
5953 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5954 } else if ((!PrevDecl ||
5955 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5956 getTemplateSpecializationKind(PrevDecl) ==
5957 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005958 // C++ [temp.exp.spec]p2:
5959 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005960 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005961 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005962 // An explicit specialization of a member function, member class or
5963 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005964 // namespace of which the class template is a member.
5965 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005966 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005967 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005968 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005969 // C++11 [temp.explicit]p3:
5970 // An explicit instantiation shall appear in an enclosing namespace of its
5971 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005972 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005973 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005974 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005975 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005976 "DC encloses TU but isn't in enclosing namespace set");
5977 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005978 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005979 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5980 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005981 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005982 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005983 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005984 Diag = diag::ext_template_spec_decl_out_of_scope;
5985 else
5986 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5987 S.Diag(Loc, Diag)
5988 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005990
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005991 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005992 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005994
Douglas Gregorf47b9112009-02-25 22:02:03 +00005995 return false;
5996}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005997
Richard Smith6056d5e2014-02-09 00:54:43 +00005998static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5999 if (!E->isInstantiationDependent())
6000 return SourceLocation();
6001 DependencyChecker Checker(Depth);
6002 Checker.TraverseStmt(E);
6003 if (Checker.Match && Checker.MatchLoc.isInvalid())
6004 return E->getSourceRange();
6005 return Checker.MatchLoc;
6006}
6007
6008static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6009 if (!TL.getType()->isDependentType())
6010 return SourceLocation();
6011 DependencyChecker Checker(Depth);
6012 Checker.TraverseTypeLoc(TL);
6013 if (Checker.Match && Checker.MatchLoc.isInvalid())
6014 return TL.getSourceRange();
6015 return Checker.MatchLoc;
6016}
6017
Larisse Voufo39a1e502013-08-06 01:03:05 +00006018/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006019/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006020static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006021 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6022 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006023 for (unsigned I = 0; I != NumArgs; ++I) {
6024 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006025 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006026 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6027 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006028 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006029
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006030 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006032
Eli Friedmanb826a002012-09-26 02:36:12 +00006033 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006034 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006035
6036 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006037
Douglas Gregor98318c22011-01-03 21:37:45 +00006038 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006039 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6040 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006041
6042 // Strip off any implicit casts we added as part of type checking.
6043 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6044 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006045
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006046 // C++ [temp.class.spec]p8:
6047 // A non-type argument is non-specialized if it is the name of a
6048 // non-type parameter. All other non-type arguments are
6049 // specialized.
6050 //
6051 // Below, we check the two conditions that only apply to
6052 // specialized non-type arguments, so skip any non-specialized
6053 // arguments.
6054 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006055 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006056 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006057
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006058 // C++ [temp.class.spec]p9:
6059 // Within the argument list of a class template partial
6060 // specialization, the following restrictions apply:
6061 // -- A partially specialized non-type argument expression
6062 // shall not involve a template parameter of the partial
6063 // specialization except when the argument expression is a
6064 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006065 SourceRange ParamUseRange =
6066 findTemplateParameter(Param->getDepth(), ArgExpr);
6067 if (ParamUseRange.isValid()) {
6068 if (IsDefaultArgument) {
6069 S.Diag(TemplateNameLoc,
6070 diag::err_dependent_non_type_arg_in_partial_spec);
6071 S.Diag(ParamUseRange.getBegin(),
6072 diag::note_dependent_non_type_default_arg_in_partial_spec)
6073 << ParamUseRange;
6074 } else {
6075 S.Diag(ParamUseRange.getBegin(),
6076 diag::err_dependent_non_type_arg_in_partial_spec)
6077 << ParamUseRange;
6078 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006079 return true;
6080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006081
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006082 // -- The type of a template parameter corresponding to a
6083 // specialized non-type argument shall not be dependent on a
6084 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006085 //
6086 // FIXME: We need to delay this check until instantiation in some cases:
6087 //
6088 // template<template<typename> class X> struct A {
6089 // template<typename T, X<T> N> struct B;
6090 // template<typename T> struct B<T, 0>;
6091 // };
6092 // template<typename> using X = int;
6093 // A<X>::B<int, 0> b;
6094 ParamUseRange = findTemplateParameter(
6095 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6096 if (ParamUseRange.isValid()) {
6097 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6098 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6099 << Param->getType() << ParamUseRange;
6100 S.Diag(Param->getLocation(), diag::note_template_param_here)
6101 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006102 return true;
6103 }
6104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006105
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006106 return false;
6107}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006108
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006109/// \brief Check the non-type template arguments of a class template
6110/// partial specialization according to C++ [temp.class.spec]p9.
6111///
Richard Smith6056d5e2014-02-09 00:54:43 +00006112/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006113/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006114/// template.
6115/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006116/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006117/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006118///
Richard Smith6056d5e2014-02-09 00:54:43 +00006119/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006120static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006121 Sema &S, SourceLocation TemplateNameLoc,
6122 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006123 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006124 const TemplateArgument *ArgList = TemplateArgs.data();
6125
6126 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6127 NonTypeTemplateParmDecl *Param
6128 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6129 if (!Param)
6130 continue;
6131
Richard Smith6056d5e2014-02-09 00:54:43 +00006132 if (CheckNonTypeTemplatePartialSpecializationArgs(
6133 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006134 return true;
6135 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006136
6137 return false;
6138}
6139
John McCall48871652010-08-21 09:40:31 +00006140DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006141Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6142 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006143 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006144 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006145 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006146 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006147 MultiTemplateParamsArg
6148 TemplateParameterLists,
6149 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006150 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006151
Richard Smith4b55a9c2014-04-17 03:29:33 +00006152 CXXScopeSpec &SS = TemplateId.SS;
6153
Abramo Bagnara60804e12011-03-18 15:16:37 +00006154 // NOTE: KWLoc is the location of the tag keyword. This will instead
6155 // store the location of the outermost template keyword in the declaration.
6156 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006157 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6158 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6159 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6160 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006161
Douglas Gregor67a65642009-02-17 23:15:12 +00006162 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006163 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006164 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006165 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6166
6167 if (!ClassTemplate) {
6168 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006169 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006170 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6171 return true;
6172 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006173
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006174 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006175 bool isPartialSpecialization = false;
6176
Douglas Gregorf47b9112009-02-25 22:02:03 +00006177 // Check the validity of the template headers that introduce this
6178 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006179 // FIXME: We probably shouldn't complain about these headers for
6180 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006181 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006182 TemplateParameterList *TemplateParams =
6183 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006184 KWLoc, TemplateNameLoc, SS, &TemplateId,
6185 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6186 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006187 if (Invalid)
6188 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006189
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006190 if (TemplateParams && TemplateParams->size() > 0) {
6191 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006192
Douglas Gregorec9518b2010-12-21 08:14:57 +00006193 if (TUK == TUK_Friend) {
6194 Diag(KWLoc, diag::err_partial_specialization_friend)
6195 << SourceRange(LAngleLoc, RAngleLoc);
6196 return true;
6197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006198
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006199 // C++ [temp.class.spec]p10:
6200 // The template parameter list of a specialization shall not
6201 // contain default template argument values.
6202 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6203 Decl *Param = TemplateParams->getParam(I);
6204 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6205 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006206 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006207 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006208 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006209 }
6210 } else if (NonTypeTemplateParmDecl *NTTP
6211 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6212 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006213 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006214 diag::err_default_arg_in_partial_spec)
6215 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006216 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006217 }
6218 } else {
6219 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006220 if (TTP->hasDefaultArgument()) {
6221 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006222 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006223 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006224 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006225 }
6226 }
6227 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006228 } else if (TemplateParams) {
6229 if (TUK == TUK_Friend)
6230 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006231 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006232 SourceRange(TemplateParams->getTemplateLoc(),
6233 TemplateParams->getRAngleLoc()))
6234 << SourceRange(LAngleLoc, RAngleLoc);
6235 else
6236 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006237 } else {
6238 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006239 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006240
Douglas Gregor67a65642009-02-17 23:15:12 +00006241 // Check that the specialization uses the same tag kind as the
6242 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006243 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6244 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006245 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006246 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006247 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006248 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006249 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006250 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006251 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006252 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006253 diag::note_previous_use);
6254 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6255 }
6256
Douglas Gregorc40290e2009-03-09 23:48:35 +00006257 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006258 TemplateArgumentListInfo TemplateArgs =
6259 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006260
Douglas Gregor14406932011-01-03 20:35:03 +00006261 // Check for unexpanded parameter packs in any of the template arguments.
6262 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006263 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006264 UPPC_PartialSpecialization))
6265 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006266
Douglas Gregor67a65642009-02-17 23:15:12 +00006267 // Check that the template argument list is well-formed for this
6268 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006269 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006270 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6271 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006272 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006273
Douglas Gregor2373c592009-05-31 09:31:02 +00006274 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006275 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006276 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006277 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006278 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6279 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006280 return true;
6281
Douglas Gregor678d76c2011-07-01 01:22:09 +00006282 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006283 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006284 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006285 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006286 TemplateArgs.size(),
6287 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006288 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6289 << ClassTemplate->getDeclName();
6290 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006291 }
6292 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006293
Craig Topperc3ec1492014-05-26 06:22:03 +00006294 void *InsertPos = nullptr;
6295 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006296
6297 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006298 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006299 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006300 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006301 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006302
Craig Topperc3ec1492014-05-26 06:22:03 +00006303 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006304
Douglas Gregorf47b9112009-02-25 22:02:03 +00006305 // Check whether we can declare a class template specialization in
6306 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006307 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006308 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6309 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006310 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006311 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006312
Douglas Gregor15301382009-07-30 17:40:51 +00006313 // The canonical type
6314 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006315 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006316 // Build the canonical type that describes the converted template
6317 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006318 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6319 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006320 Converted.data(),
6321 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006322
6323 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006324 ClassTemplate->getInjectedClassNameSpecialization())) {
6325 // C++ [temp.class.spec]p9b3:
6326 //
6327 // -- The argument list of the specialization shall not be identical
6328 // to the implicit argument list of the primary template.
6329 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006330 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006331 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006332 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6333 ClassTemplate->getIdentifier(),
6334 TemplateNameLoc,
6335 Attr,
6336 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006337 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006338 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006339 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006340 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006341 }
Douglas Gregor15301382009-07-30 17:40:51 +00006342
Douglas Gregor2373c592009-05-31 09:31:02 +00006343 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006344 ClassTemplatePartialSpecializationDecl *PrevPartial
6345 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006346 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006347 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006348 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006349 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006350 TemplateParams,
6351 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006352 Converted.data(),
6353 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006354 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006355 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006356 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006357 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006358 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006359 Partial->setTemplateParameterListsInfo(
6360 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006361 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006362
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006363 if (!PrevPartial)
6364 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006365 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006366
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006368 // template specialization, make a note of that.
6369 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6370 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006371
Douglas Gregor91772d12009-06-13 00:26:55 +00006372 // Check that all of the template parameters of the class template
6373 // partial specialization are deducible from the template
6374 // arguments. If not, this class template partial specialization
6375 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006376 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006377 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006378 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006379 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006380
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006381 if (!DeducibleParams.all()) {
6382 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006383 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006384 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006385 << SourceRange(TemplateNameLoc, RAngleLoc);
6386 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6387 if (!DeducibleParams[I]) {
6388 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6389 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006390 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006391 diag::note_partial_spec_unused_parameter)
6392 << Param->getDeclName();
6393 else
Mike Stump11289f42009-09-09 15:08:12 +00006394 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006395 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006396 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006397 }
6398 }
6399 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006400 } else {
6401 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006402 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006403 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006404 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006405 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006406 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006407 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006408 Converted.data(),
6409 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006410 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006411 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006412 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006413 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006414 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006415 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006416
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006417 if (!PrevDecl)
6418 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006419
David Majnemer678f50b2015-11-18 19:49:19 +00006420 if (CurContext->isDependentContext()) {
6421 // -fms-extensions permits specialization of nested classes without
6422 // fully specializing the outer class(es).
6423 assert(getLangOpts().MicrosoftExt &&
6424 "Only possible with -fms-extensions!");
6425 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6426 CanonType = Context.getTemplateSpecializationType(
6427 CanonTemplate, Converted.data(), Converted.size());
6428 } else {
6429 CanonType = Context.getTypeDeclType(Specialization);
6430 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006431 }
6432
Douglas Gregor06db9f52009-10-12 20:18:28 +00006433 // C++ [temp.expl.spec]p6:
6434 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006435 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006436 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006437 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006438 // use occurs; no diagnostic is required.
6439 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006440 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006441 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006442 // Is there any previous explicit specialization declaration?
6443 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6444 Okay = true;
6445 break;
6446 }
6447 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006448
Douglas Gregorc854c662010-02-26 06:03:23 +00006449 if (!Okay) {
6450 SourceRange Range(TemplateNameLoc, RAngleLoc);
6451 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6452 << Context.getTypeDeclType(Specialization) << Range;
6453
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006454 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006455 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006456 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006457 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006458 return true;
6459 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006461
Douglas Gregor2208a292009-09-26 20:57:03 +00006462 // If this is not a friend, note that this is an explicit specialization.
6463 if (TUK != TUK_Friend)
6464 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006465
6466 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006467 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006468 RecordDecl *Def = Specialization->getDefinition();
6469 NamedDecl *Hidden = nullptr;
6470 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6471 SkipBody->ShouldSkip = true;
6472 makeMergedDefinitionVisible(Hidden, KWLoc);
6473 // From here on out, treat this as just a redeclaration.
6474 TUK = TUK_Declaration;
6475 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006476 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006477 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006478 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006479 Diag(Def->getLocation(), diag::note_previous_definition);
6480 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006481 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006482 }
6483 }
6484
John McCall659a3372010-12-18 03:30:47 +00006485 if (Attr)
6486 ProcessDeclAttributeList(S, Specialization, Attr);
6487
Richard Smith034b94a2012-08-17 03:20:55 +00006488 // Add alignment attributes if necessary; these attributes are checked when
6489 // the ASTContext lays out the structure.
6490 if (TUK == TUK_Definition) {
6491 AddAlignmentAttributesForRecord(Specialization);
6492 AddMsStructLayoutForRecord(Specialization);
6493 }
6494
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006495 if (ModulePrivateLoc.isValid())
6496 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6497 << (isPartialSpecialization? 1 : 0)
6498 << FixItHint::CreateRemoval(ModulePrivateLoc);
6499
Douglas Gregord56a91e2009-02-26 22:19:44 +00006500 // Build the fully-sugared type for this class template
6501 // specialization as the user wrote in the specialization
6502 // itself. This means that we'll pretty-print the type retrieved
6503 // from the specialization's declaration the way that the user
6504 // actually wrote the specialization, rather than formatting the
6505 // name based on the "canonical" representation used to store the
6506 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006507 TypeSourceInfo *WrittenTy
6508 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6509 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006510 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006511 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006512 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006513 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006514
Douglas Gregor1e249f82009-02-25 22:18:32 +00006515 // C++ [temp.expl.spec]p9:
6516 // A template explicit specialization is in the scope of the
6517 // namespace in which the template was defined.
6518 //
6519 // We actually implement this paragraph where we set the semantic
6520 // context (in the creation of the ClassTemplateSpecializationDecl),
6521 // but we also maintain the lexical context where the actual
6522 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006523 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006524
Douglas Gregor67a65642009-02-17 23:15:12 +00006525 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006526 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006527 Specialization->startDefinition();
6528
Douglas Gregor2208a292009-09-26 20:57:03 +00006529 if (TUK == TUK_Friend) {
6530 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6531 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006532 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006533 /*FIXME:*/KWLoc);
6534 Friend->setAccess(AS_public);
6535 CurContext->addDecl(Friend);
6536 } else {
6537 // Add the specialization into its lexical context, so that it can
6538 // be seen when iterating through the list of declarations in that
6539 // context. However, specializations are not found by name lookup.
6540 CurContext->addDecl(Specialization);
6541 }
John McCall48871652010-08-21 09:40:31 +00006542 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006543}
Douglas Gregor333489b2009-03-27 23:10:48 +00006544
John McCall48871652010-08-21 09:40:31 +00006545Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006546 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006547 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006548 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006549 ActOnDocumentableDecl(NewDecl);
6550 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006551}
6552
John McCall4f7ced62010-02-11 01:33:53 +00006553/// \brief Strips various properties off an implicit instantiation
6554/// that has just been explicitly specialized.
6555static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006556 D->dropAttr<DLLImportAttr>();
6557 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006558
Nico Webere4974382014-12-19 23:52:45 +00006559 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006560 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006561}
6562
Nico Webera8f80b32012-01-09 19:52:25 +00006563/// \brief Compute the diagnostic location for an explicit instantiation
6564// declaration or definition.
6565static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006566 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006567 // Explicit instantiations following a specialization have no effect and
6568 // hence no PointOfInstantiation. In that case, walk decl backwards
6569 // until a valid name loc is found.
6570 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006571 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6572 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006573 PrevDiagLoc = Prev->getLocation();
6574 }
6575 assert(PrevDiagLoc.isValid() &&
6576 "Explicit instantiation without point of instantiation?");
6577 return PrevDiagLoc;
6578}
6579
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006580/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006581/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006583/// new specialization/instantiation will have any effect.
6584///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006585/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006586/// instantiation.
6587///
6588/// \param NewTSK the kind of the new explicit specialization or instantiation.
6589///
6590/// \param PrevDecl the previous declaration of the entity.
6591///
6592/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6593///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006595/// declaration was instantiated (either implicitly or explicitly).
6596///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006598/// specialization or instantiation has no effect and should be ignored.
6599///
6600/// \returns true if there was an error that should prevent the introduction of
6601/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006602bool
6603Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6604 TemplateSpecializationKind NewTSK,
6605 NamedDecl *PrevDecl,
6606 TemplateSpecializationKind PrevTSK,
6607 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006608 bool &HasNoEffect) {
6609 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006611 switch (NewTSK) {
6612 case TSK_Undeclared:
6613 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006614 assert(
6615 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6616 "previous declaration must be implicit!");
6617 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006619 case TSK_ExplicitSpecialization:
6620 switch (PrevTSK) {
6621 case TSK_Undeclared:
6622 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006623 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006624 // explicitly specialized or has merely been mentioned without any
6625 // instantiation.
6626 return false;
6627
6628 case TSK_ImplicitInstantiation:
6629 if (PrevPointOfInstantiation.isInvalid()) {
6630 // The declaration itself has not actually been instantiated, so it is
6631 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006632 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006633 return false;
6634 }
6635 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006637 case TSK_ExplicitInstantiationDeclaration:
6638 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639 assert((PrevTSK == TSK_ImplicitInstantiation ||
6640 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006641 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006642
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006643 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006644 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006645 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006647 // implicit instantiation to take place, in every translation unit in
6648 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006649 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006650 // Is there any previous explicit specialization declaration?
6651 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6652 return false;
6653 }
6654
Douglas Gregor1d957a32009-10-27 18:42:08 +00006655 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006656 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006657 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006658 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006660 return true;
6661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006662
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006663 case TSK_ExplicitInstantiationDeclaration:
6664 switch (PrevTSK) {
6665 case TSK_ExplicitInstantiationDeclaration:
6666 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006667 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006668 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006670 case TSK_Undeclared:
6671 case TSK_ImplicitInstantiation:
6672 // We're explicitly instantiating something that may have already been
6673 // implicitly instantiated; that's fine.
6674 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006675
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006676 case TSK_ExplicitSpecialization:
6677 // C++0x [temp.explicit]p4:
6678 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006679 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006680 // specialization for that template, the explicit instantiation has no
6681 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006682 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006683 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006684
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006685 case TSK_ExplicitInstantiationDefinition:
6686 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006687 // If an entity is the subject of both an explicit instantiation
6688 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006689 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006691 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006692
6693 // Explicit instantiations following a specialization have no effect and
6694 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6695 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006696 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6697 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006698 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006699 return false;
6700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006702 case TSK_ExplicitInstantiationDefinition:
6703 switch (PrevTSK) {
6704 case TSK_Undeclared:
6705 case TSK_ImplicitInstantiation:
6706 // We're explicitly instantiating something that may have already been
6707 // implicitly instantiated; that's fine.
6708 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006709
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006710 case TSK_ExplicitSpecialization:
6711 // C++ DR 259, C++0x [temp.explicit]p4:
6712 // For a given set of template parameters, if an explicit
6713 // instantiation of a template appears after a declaration of
6714 // an explicit specialization for that template, the explicit
6715 // instantiation has no effect.
6716 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006718 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006719 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006720 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006721 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6722 diag::ext_explicit_instantiation_after_specialization)
6723 << PrevDecl;
6724 Diag(PrevDecl->getLocation(),
6725 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006726 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006727 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006728
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006729 case TSK_ExplicitInstantiationDeclaration:
6730 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006731 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006732
6733 // C++0x [temp.explicit]p4:
6734 // For a given set of template parameters, if an explicit instantiation
6735 // of a template appears after a declaration of an explicit
6736 // specialization for that template, the explicit instantiation has no
6737 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006738 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006739 // Is there any previous explicit specialization declaration?
6740 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6741 HasNoEffect = true;
6742 break;
6743 }
6744 }
6745
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006746 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006748 case TSK_ExplicitInstantiationDefinition:
6749 // C++0x [temp.spec]p5:
6750 // For a given template and a given set of template-arguments,
6751 // - an explicit instantiation definition shall appear at most once
6752 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006753
6754 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6755 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006756 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006757 : diag::err_explicit_instantiation_duplicate)
6758 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006759 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006760 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006761 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006762 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006763 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765
David Blaikie83d382b2011-09-23 05:06:16 +00006766 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006767}
6768
John McCallb9c78482010-04-08 09:05:18 +00006769/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006770/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006771///
James Dennettf14a6e52012-06-15 22:23:43 +00006772/// The only possible way to get a dependent function template specialization
6773/// is with a friend declaration, like so:
6774///
6775/// \code
6776/// template \<class T> void foo(T);
6777/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006778/// friend void foo<>(T);
6779/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006780/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006781///
6782/// There really isn't any useful analysis we can do here, so we
6783/// just store the information.
6784bool
6785Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6786 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6787 LookupResult &Previous) {
6788 // Remove anything from Previous that isn't a function template in
6789 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006790 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006791 LookupResult::Filter F = Previous.makeFilter();
6792 while (F.hasNext()) {
6793 NamedDecl *D = F.next()->getUnderlyingDecl();
6794 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006795 !FDLookupContext->InEnclosingNamespaceSetOf(
6796 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006797 F.erase();
6798 }
6799 F.done();
6800
6801 // Should this be diagnosed here?
6802 if (Previous.empty()) return true;
6803
6804 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6805 ExplicitTemplateArgs);
6806 return false;
6807}
6808
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006809/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006810/// specialization.
6811///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006812/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006813/// explicit function template specialization. On successful completion,
6814/// the function declaration \p FD will become a function template
6815/// specialization.
6816///
6817/// \param FD the function declaration, which will be updated to become a
6818/// function template specialization.
6819///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006820/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6821/// if any. Note that this may be valid info even when 0 arguments are
6822/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6823/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006824///
Francois Pichet3a44e432011-07-08 06:21:47 +00006825/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006826/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006827bool Sema::CheckFunctionTemplateSpecialization(
6828 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6829 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006830 // The set of function template specializations that could match this
6831 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006832 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006833 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6834 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006835
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006836 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6837 ConvertedTemplateArgs;
6838
Sebastian Redl50c68252010-08-31 00:36:30 +00006839 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006840 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6841 I != E; ++I) {
6842 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6843 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006845 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006846 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6847 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006848 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006849
Richard Smith574f4f62013-01-14 05:37:29 +00006850 // When matching a constexpr member function template specialization
6851 // against the primary template, we don't yet know whether the
6852 // specialization has an implicit 'const' (because we don't know whether
6853 // it will be a static member function until we know which template it
6854 // specializes), so adjust it now assuming it specializes this template.
6855 QualType FT = FD->getType();
6856 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006857 CXXMethodDecl *OldMD =
6858 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006859 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006860 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006861 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6862 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006863 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006864 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006865 }
6866 }
6867
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006868 TemplateArgumentListInfo Args;
6869 if (ExplicitTemplateArgs)
6870 Args = *ExplicitTemplateArgs;
6871
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006872 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873 // A trailing template-argument can be left unspecified in the
6874 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006875 // provided it can be deduced from the function argument type.
6876 // Perform template argument deduction to determine whether we may be
6877 // specializing this template.
6878 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006879 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006880 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006881 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6882 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006883 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006884 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006885 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006886 FailedCandidates.addCandidate()
6887 .set(FunTmpl->getTemplatedDecl(),
6888 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006889 (void)TDK;
6890 continue;
6891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006893 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006894 if (ExplicitTemplateArgs)
6895 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006896 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006897 }
6898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006899
Douglas Gregor5de279c2009-09-26 03:41:46 +00006900 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006901 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006902 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006903 FD->getLocation(),
6904 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6905 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006906 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006907 PDiag(diag::note_function_template_spec_matched));
6908
John McCall58cc69d2010-01-27 01:50:18 +00006909 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006910 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006911
6912 // Ignore access information; it doesn't figure into redeclaration checking.
6913 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006914
6915 FunctionTemplateSpecializationInfo *SpecInfo
6916 = Specialization->getTemplateSpecializationInfo();
6917 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006918
6919 // Note: do not overwrite location info if previous template
6920 // specialization kind was explicit.
6921 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006922 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006923 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006924 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6925 // function can differ from the template declaration with respect to
6926 // the constexpr specifier.
6927 Specialization->setConstexpr(FD->isConstexpr());
6928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006929
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006930 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006931 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006932
6933 // If this is a friend declaration, then we're not really declaring
6934 // an explicit specialization.
6935 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
Douglas Gregor54888652009-10-07 00:13:32 +00006937 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006938 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006939 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006940 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006941 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006942 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006943 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006944
6945 // C++ [temp.expl.spec]p6:
6946 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006947 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006948 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006950 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006951 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006952 if (!isFriend &&
6953 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006954 TSK_ExplicitSpecialization,
6955 Specialization,
6956 SpecInfo->getTemplateSpecializationKind(),
6957 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006958 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006959 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006960
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006961 // Mark the prior declaration as an explicit specialization, so that later
6962 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006963 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006964 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006965 MarkUnusedFileScopedDecl(Specialization);
6966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006968 // Turn the given function declaration into a function template
6969 // specialization, with the template arguments from the previous
6970 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006971 // Take copies of (semantic and syntactic) template argument lists.
6972 const TemplateArgumentList* TemplArgs = new (Context)
6973 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006974 FD->setFunctionTemplateSpecialization(
6975 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
6976 SpecInfo->getTemplateSpecializationKind(),
6977 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006978
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006979 // The "previous declaration" for this function template specialization is
6980 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006981 Previous.clear();
6982 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006983 return false;
6984}
6985
Douglas Gregor86d142a2009-10-08 07:24:58 +00006986/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006987/// specialization.
6988///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006990/// explicit member function specialization. On successful completion,
6991/// the function declaration \p FD will become a member function
6992/// specialization.
6993///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006994/// \param Member the member declaration, which will be updated to become a
6995/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006996///
John McCall1f82f242009-11-18 22:49:29 +00006997/// \param Previous the set of declarations, one of which may be specialized
6998/// by this function specialization; the set will be modified to contain the
6999/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007000bool
John McCall1f82f242009-11-18 22:49:29 +00007001Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007002 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007003
Douglas Gregor86d142a2009-10-08 07:24:58 +00007004 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00007005 NamedDecl *Instantiation = nullptr;
7006 NamedDecl *InstantiatedFrom = nullptr;
7007 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007008
John McCall1f82f242009-11-18 22:49:29 +00007009 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007010 // Nowhere to look anyway.
7011 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007012 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7013 I != E; ++I) {
7014 NamedDecl *D = (*I)->getUnderlyingDecl();
7015 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007016 QualType Adjusted = Function->getType();
7017 if (!hasExplicitCallingConv(Adjusted))
7018 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7019 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007020 Instantiation = Method;
7021 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007022 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007023 break;
7024 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007025 }
7026 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007027 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007028 VarDecl *PrevVar;
7029 if (Previous.isSingleResult() &&
7030 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007031 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00007032 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007033 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007034 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007035 }
7036 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007037 CXXRecordDecl *PrevRecord;
7038 if (Previous.isSingleResult() &&
7039 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7040 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007041 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007042 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007043 }
Richard Smith7d137e32012-03-23 03:33:32 +00007044 } else if (isa<EnumDecl>(Member)) {
7045 EnumDecl *PrevEnum;
7046 if (Previous.isSingleResult() &&
7047 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7048 Instantiation = PrevEnum;
7049 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7050 MSInfo = PrevEnum->getMemberSpecializationInfo();
7051 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007054 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007055 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007056 // specializations are always out-of-line, the caller will complain about
7057 // this mismatch later.
7058 return false;
7059 }
John McCalle820e5e2010-04-13 20:37:33 +00007060
7061 // If this is a friend, just bail out here before we start turning
7062 // things into explicit specializations.
7063 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7064 // Preserve instantiation information.
7065 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7066 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7067 cast<CXXMethodDecl>(InstantiatedFrom),
7068 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7069 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7070 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7071 cast<CXXRecordDecl>(InstantiatedFrom),
7072 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7073 }
7074
7075 Previous.clear();
7076 Previous.addDecl(Instantiation);
7077 return false;
7078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007079
Douglas Gregor86d142a2009-10-08 07:24:58 +00007080 // Make sure that this is a specialization of a member.
7081 if (!InstantiatedFrom) {
7082 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7083 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007084 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7085 return true;
7086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087
Douglas Gregor06db9f52009-10-12 20:18:28 +00007088 // C++ [temp.expl.spec]p6:
7089 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007090 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007091 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007092 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007093 // use occurs; no diagnostic is required.
7094 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007095
Abramo Bagnara8075c852010-06-12 07:44:57 +00007096 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007097 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7098 TSK_ExplicitSpecialization,
7099 Instantiation,
7100 MSInfo->getTemplateSpecializationKind(),
7101 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007102 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007103 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007105 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007106 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007107 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007108 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007109 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007110 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007111
Douglas Gregor86d142a2009-10-08 07:24:58 +00007112 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007113 // the original declaration to note that it is an explicit specialization
7114 // (if it was previously an implicit instantiation). This latter step
7115 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007116 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007117 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7118 if (InstantiationFunction->getTemplateSpecializationKind() ==
7119 TSK_ImplicitInstantiation) {
7120 InstantiationFunction->setTemplateSpecializationKind(
7121 TSK_ExplicitSpecialization);
7122 InstantiationFunction->setLocation(Member->getLocation());
7123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007124
Douglas Gregor86d142a2009-10-08 07:24:58 +00007125 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7126 cast<CXXMethodDecl>(InstantiatedFrom),
7127 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007128 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007129 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007130 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7131 if (InstantiationVar->getTemplateSpecializationKind() ==
7132 TSK_ImplicitInstantiation) {
7133 InstantiationVar->setTemplateSpecializationKind(
7134 TSK_ExplicitSpecialization);
7135 InstantiationVar->setLocation(Member->getLocation());
7136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007137
Larisse Voufo39a1e502013-08-06 01:03:05 +00007138 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7139 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007140 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007141 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007142 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7143 if (InstantiationClass->getTemplateSpecializationKind() ==
7144 TSK_ImplicitInstantiation) {
7145 InstantiationClass->setTemplateSpecializationKind(
7146 TSK_ExplicitSpecialization);
7147 InstantiationClass->setLocation(Member->getLocation());
7148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007149
Douglas Gregor86d142a2009-10-08 07:24:58 +00007150 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007151 cast<CXXRecordDecl>(InstantiatedFrom),
7152 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007153 } else {
7154 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7155 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7156 if (InstantiationEnum->getTemplateSpecializationKind() ==
7157 TSK_ImplicitInstantiation) {
7158 InstantiationEnum->setTemplateSpecializationKind(
7159 TSK_ExplicitSpecialization);
7160 InstantiationEnum->setLocation(Member->getLocation());
7161 }
7162
7163 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7164 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007166
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007167 // Save the caller the trouble of having to figure out which declaration
7168 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007169 Previous.clear();
7170 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007171 return false;
7172}
7173
Douglas Gregore47f5a72009-10-14 23:41:34 +00007174/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007175///
7176/// \returns true if a serious error occurs, false otherwise.
7177static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007178 SourceLocation InstLoc,
7179 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007180 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7181 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007182
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007183 if (CurContext->isRecord()) {
7184 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7185 << D;
7186 return true;
7187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007188
Richard Smith050d2612011-10-18 02:28:33 +00007189 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007190 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007191 // template. If the name declared in the explicit instantiation is an
7192 // unqualified name, the explicit instantiation shall appear in the
7193 // namespace where its template is declared or, if that namespace is inline
7194 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007195 //
7196 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007197 if (WasQualifiedName) {
7198 if (CurContext->Encloses(OrigContext))
7199 return false;
7200 } else {
7201 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7202 return false;
7203 }
7204
7205 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7206 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007207 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007208 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007209 diag::err_explicit_instantiation_out_of_scope :
7210 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007211 << D << NS;
7212 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007213 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007214 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007215 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7216 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7217 << D << NS;
7218 } else
7219 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007220 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007221 diag::err_explicit_instantiation_must_be_global :
7222 diag::warn_explicit_instantiation_must_be_global_0x)
7223 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007224 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007225 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007226}
7227
7228/// \brief Determine whether the given scope specifier has a template-id in it.
7229static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7230 if (!SS.isSet())
7231 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007232
Richard Smith050d2612011-10-18 02:28:33 +00007233 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007234 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007235 // or a static data member of a class template specialization, the name of
7236 // the class template specialization in the qualified-id for the member
7237 // name shall be a simple-template-id.
7238 //
7239 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007240 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7241 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007242 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007243 if (isa<TemplateSpecializationType>(T))
7244 return true;
7245
7246 return false;
7247}
7248
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007249// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007250DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007251Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007252 SourceLocation ExternLoc,
7253 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007254 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007255 SourceLocation KWLoc,
7256 const CXXScopeSpec &SS,
7257 TemplateTy TemplateD,
7258 SourceLocation TemplateNameLoc,
7259 SourceLocation LAngleLoc,
7260 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007261 SourceLocation RAngleLoc,
7262 AttributeList *Attr) {
7263 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007264 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007265 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007266 // Check that the specialization uses the same tag kind as the
7267 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007268 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7269 assert(Kind != TTK_Enum &&
7270 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007271
7272 if (isa<TypeAliasTemplateDecl>(TD)) {
7273 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7274 Diag(TD->getTemplatedDecl()->getLocation(),
7275 diag::note_previous_use);
7276 return true;
7277 }
7278
7279 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7280
Douglas Gregord9034f02009-05-14 16:41:31 +00007281 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007282 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007283 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007284 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007285 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007286 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007287 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007288 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007289 diag::note_previous_use);
7290 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7291 }
7292
Douglas Gregore47f5a72009-10-14 23:41:34 +00007293 // C++0x [temp.explicit]p2:
7294 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007295 // definition and an explicit instantiation declaration. An explicit
7296 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007297 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7298 ? TSK_ExplicitInstantiationDefinition
7299 : TSK_ExplicitInstantiationDeclaration;
7300
7301 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7302 // Check for dllexport class template instantiation declarations.
7303 for (AttributeList *A = Attr; A; A = A->getNext()) {
7304 if (A->getKind() == AttributeList::AT_DLLExport) {
7305 Diag(ExternLoc,
7306 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7307 Diag(A->getLoc(), diag::note_attribute);
7308 break;
7309 }
7310 }
7311
7312 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7313 Diag(ExternLoc,
7314 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7315 Diag(A->getLocation(), diag::note_attribute);
7316 }
7317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007318
Douglas Gregora1f49972009-05-13 00:25:59 +00007319 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007320 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007321 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007322
7323 // Check that the template argument list is well-formed for this
7324 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007325 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007326 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7327 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007328 return true;
7329
Douglas Gregora1f49972009-05-13 00:25:59 +00007330 // Find the class template specialization declaration that
7331 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007332 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007333 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007334 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007335
Abramo Bagnara8075c852010-06-12 07:44:57 +00007336 TemplateSpecializationKind PrevDecl_TSK
7337 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7338
Douglas Gregor54888652009-10-07 00:13:32 +00007339 // C++0x [temp.explicit]p2:
7340 // [...] An explicit instantiation shall appear in an enclosing
7341 // namespace of its template. [...]
7342 //
7343 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007344 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7345 SS.isSet()))
7346 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007347
Craig Topperc3ec1492014-05-26 06:22:03 +00007348 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007349
Abramo Bagnara8075c852010-06-12 07:44:57 +00007350 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007351 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007352 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007353 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007354 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007355 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007356 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007357
Abramo Bagnara8075c852010-06-12 07:44:57 +00007358 // Even though HasNoEffect == true means that this explicit instantiation
7359 // has no effect on semantics, we go on to put its syntax in the AST.
7360
7361 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7362 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007363 // Since the only prior class template specialization with these
7364 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007365 // declaration node as our own, updating the source location
7366 // for the template name to reflect our new declaration.
7367 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007368 Specialization = PrevDecl;
7369 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007370 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007371 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007372 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007373
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007374 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007375 // Create a new class template specialization declaration node for
7376 // this explicit specialization.
7377 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007378 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007379 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007380 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007381 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007382 Converted.data(),
7383 Converted.size(),
7384 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007385 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007386
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007387 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007388 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007389 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007390 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007391 }
7392
7393 // Build the fully-sugared type for this explicit instantiation as
7394 // the user wrote in the explicit instantiation itself. This means
7395 // that we'll pretty-print the type retrieved from the
7396 // specialization's declaration the way that the user actually wrote
7397 // the explicit instantiation, rather than formatting the name based
7398 // on the "canonical" representation used to store the template
7399 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007400 TypeSourceInfo *WrittenTy
7401 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7402 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007403 Context.getTypeDeclType(Specialization));
7404 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007405
Abramo Bagnara8075c852010-06-12 07:44:57 +00007406 // Set source locations for keywords.
7407 Specialization->setExternLoc(ExternLoc);
7408 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007409 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007410
Rafael Espindola0b062072012-01-03 06:04:21 +00007411 if (Attr)
7412 ProcessDeclAttributeList(S, Specialization, Attr);
7413
Abramo Bagnara8075c852010-06-12 07:44:57 +00007414 // Add the explicit instantiation into its lexical context. However,
7415 // since explicit instantiations are never found by name lookup, we
7416 // just put it into the declaration context directly.
7417 Specialization->setLexicalDeclContext(CurContext);
7418 CurContext->addDecl(Specialization);
7419
7420 // Syntax is now OK, so return if it has no other effect on semantics.
7421 if (HasNoEffect) {
7422 // Set the template specialization kind.
7423 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007424 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007425 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007426
7427 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007428 // A definition of a class template or class member template
7429 // shall be in scope at the point of the explicit instantiation of
7430 // the class template or class member template.
7431 //
7432 // This check comes when we actually try to perform the
7433 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007434 ClassTemplateSpecializationDecl *Def
7435 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007436 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007437 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007438 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007439 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007440 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007441 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7442 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007443
Douglas Gregor1d957a32009-10-27 18:42:08 +00007444 // Instantiate the members of this class template specialization.
7445 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007446 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007447 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007448 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7449
7450 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7451 // TSK_ExplicitInstantiationDefinition
7452 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007453 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007454 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007455 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007456
Hans Wennborgc0875502015-06-09 00:39:05 +00007457 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7458 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7459 // In the MS ABI, an explicit instantiation definition can add a dll
7460 // attribute to a template with a previous instantiation declaration.
7461 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007462 auto *A = cast<InheritableAttr>(
7463 getDLLAttr(Specialization)->clone(getASTContext()));
7464 A->setInherited(true);
7465 Def->addAttr(A);
7466 checkClassLevelDLLAttribute(Def);
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007467
7468 // Propagate attribute to base class templates.
7469 for (auto &B : Def->bases()) {
7470 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7471 B.getType()->getAsCXXRecordDecl()))
7472 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7473 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007474 }
7475 }
7476
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007477 // Set the template specialization kind. Make sure it is set before
7478 // instantiating the members which will trigger ASTConsumer callbacks.
7479 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007480 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007481 } else {
7482
7483 // Set the template specialization kind.
7484 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007485 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007486
John McCall48871652010-08-21 09:40:31 +00007487 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007488}
7489
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007490// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007491DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007492Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007493 SourceLocation ExternLoc,
7494 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007495 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007496 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007497 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007498 IdentifierInfo *Name,
7499 SourceLocation NameLoc,
7500 AttributeList *Attr) {
7501
Douglas Gregord6ab8742009-05-28 23:31:59 +00007502 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007503 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007504 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007505 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007506 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007507 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007508 SourceLocation(), false, TypeResult(),
7509 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007510 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7511
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007512 if (!TagD)
7513 return true;
7514
John McCall48871652010-08-21 09:40:31 +00007515 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007516 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007517
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007518 if (Tag->isInvalidDecl())
7519 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007520
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007521 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7522 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7523 if (!Pattern) {
7524 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7525 << Context.getTypeDeclType(Record);
7526 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7527 return true;
7528 }
7529
Douglas Gregore47f5a72009-10-14 23:41:34 +00007530 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007531 // If the explicit instantiation is for a class or member class, the
7532 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007533 // simple-template-id.
7534 //
7535 // C++98 has the same restriction, just worded differently.
7536 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007537 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007538 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007539
Douglas Gregore47f5a72009-10-14 23:41:34 +00007540 // C++0x [temp.explicit]p2:
7541 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007542 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007543 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007544 TemplateSpecializationKind TSK
7545 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7546 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007547
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007548 // C++0x [temp.explicit]p2:
7549 // [...] An explicit instantiation shall appear in an enclosing
7550 // namespace of its template. [...]
7551 //
7552 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007553 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007554
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007555 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007557 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007558 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007559 PrevDecl = Record;
7560 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007561 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007562 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007563 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007564 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007565 PrevDecl,
7566 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007567 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007568 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007569 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007570 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007571 return TagD;
7572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007573
Douglas Gregor12e49d32009-10-15 22:53:21 +00007574 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007575 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007576 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007577 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007579 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007580 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007581 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007582 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007583 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7584 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007585 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7586 << Pattern;
7587 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007588 } else {
7589 if (InstantiateClass(NameLoc, Record, Def,
7590 getTemplateInstantiationArgs(Record),
7591 TSK))
7592 return true;
7593
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007594 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007595 if (!RecordDef)
7596 return true;
7597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007598 }
7599
Douglas Gregor1d957a32009-10-27 18:42:08 +00007600 // Instantiate all of the members of the class.
7601 InstantiateClassMembers(NameLoc, RecordDef,
7602 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007603
Douglas Gregor88d292c2010-05-13 16:44:06 +00007604 if (TSK == TSK_ExplicitInstantiationDefinition)
7605 MarkVTableUsed(NameLoc, RecordDef, true);
7606
Mike Stump87c57ac2009-05-16 07:39:55 +00007607 // FIXME: We don't have any representation for explicit instantiations of
7608 // member classes. Such a representation is not needed for compilation, but it
7609 // should be available for clients that want to see all of the declarations in
7610 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007611 return TagD;
7612}
7613
John McCallfaf5fb42010-08-26 23:41:50 +00007614DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7615 SourceLocation ExternLoc,
7616 SourceLocation TemplateLoc,
7617 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007618 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007619 // TODO: check if/when DNInfo should replace Name.
7620 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7621 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007622 if (!Name) {
7623 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007624 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007625 diag::err_explicit_instantiation_requires_name)
7626 << D.getDeclSpec().getSourceRange()
7627 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007628
Douglas Gregor450f00842009-09-25 18:43:00 +00007629 return true;
7630 }
7631
7632 // The scope passed in may not be a decl scope. Zip up the scope tree until
7633 // we find one that is.
7634 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7635 (S->getFlags() & Scope::TemplateParamScope) != 0)
7636 S = S->getParent();
7637
7638 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007639 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7640 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007641 if (R.isNull())
7642 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007643
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007644 // C++ [dcl.stc]p1:
7645 // A storage-class-specifier shall not be specified in [...] an explicit
7646 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007647 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007648 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7649 << Name;
7650 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007651 } else if (D.getDeclSpec().getStorageClassSpec()
7652 != DeclSpec::SCS_unspecified) {
7653 // Complain about then remove the storage class specifier.
7654 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7655 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7656
7657 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007658 }
7659
Douglas Gregor3c74d412009-10-14 20:14:33 +00007660 // C++0x [temp.explicit]p1:
7661 // [...] An explicit instantiation of a function template shall not use the
7662 // inline or constexpr specifiers.
7663 // Presumably, this also applies to member functions of class templates as
7664 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007665 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007666 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007667 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007668 diag::err_explicit_instantiation_inline :
7669 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007670 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007671 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007672 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7673 // not already specified.
7674 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7675 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676
Douglas Gregore47f5a72009-10-14 23:41:34 +00007677 // C++0x [temp.explicit]p2:
7678 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007679 // definition and an explicit instantiation declaration. An explicit
7680 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007681 TemplateSpecializationKind TSK
7682 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7683 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007685 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007686 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007687
7688 if (!R->isFunctionType()) {
7689 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007690 // A [...] static data member of a class template can be explicitly
7691 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007692 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007693 // C++1y [temp.explicit]p1:
7694 // A [...] variable [...] template specialization can be explicitly
7695 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007696 if (Previous.isAmbiguous())
7697 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007698
John McCall67c00872009-12-02 08:25:40 +00007699 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007700 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007701
Larisse Voufo39a1e502013-08-06 01:03:05 +00007702 if (!PrevTemplate) {
7703 if (!Prev || !Prev->isStaticDataMember()) {
7704 // We expect to see a data data member here.
7705 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7706 << Name;
7707 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7708 P != PEnd; ++P)
7709 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7710 return true;
7711 }
7712
7713 if (!Prev->getInstantiatedFromStaticDataMember()) {
7714 // FIXME: Check for explicit specialization?
7715 Diag(D.getIdentifierLoc(),
7716 diag::err_explicit_instantiation_data_member_not_instantiated)
7717 << Prev;
7718 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7719 // FIXME: Can we provide a note showing where this was declared?
7720 return true;
7721 }
7722 } else {
7723 // Explicitly instantiate a variable template.
7724
7725 // C++1y [dcl.spec.auto]p6:
7726 // ... A program that uses auto or decltype(auto) in a context not
7727 // explicitly allowed in this section is ill-formed.
7728 //
7729 // This includes auto-typed variable template instantiations.
7730 if (R->isUndeducedType()) {
7731 Diag(T->getTypeLoc().getLocStart(),
7732 diag::err_auto_not_allowed_var_inst);
7733 return true;
7734 }
7735
Richard Smithef985ac2013-09-18 02:10:12 +00007736 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7737 // C++1y [temp.explicit]p3:
7738 // If the explicit instantiation is for a variable, the unqualified-id
7739 // in the declaration shall be a template-id.
7740 Diag(D.getIdentifierLoc(),
7741 diag::err_explicit_instantiation_without_template_id)
7742 << PrevTemplate;
7743 Diag(PrevTemplate->getLocation(),
7744 diag::note_explicit_instantiation_here);
7745 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007746 }
7747
Richard Smithef985ac2013-09-18 02:10:12 +00007748 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007749 TemplateArgumentListInfo TemplateArgs =
7750 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007751
Larisse Voufo39a1e502013-08-06 01:03:05 +00007752 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7753 D.getIdentifierLoc(), TemplateArgs);
7754 if (Res.isInvalid())
7755 return true;
7756
7757 // Ignore access control bits, we don't need them for redeclaration
7758 // checking.
7759 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007761
Douglas Gregore47f5a72009-10-14 23:41:34 +00007762 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007763 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007764 // or a static data member of a class template specialization, the name of
7765 // the class template specialization in the qualified-id for the member
7766 // name shall be a simple-template-id.
7767 //
7768 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007769 //
Richard Smith5977d872013-09-18 21:55:14 +00007770 // This does not apply to variable template specializations, where the
7771 // template-id is in the unqualified-id instead.
7772 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007773 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007774 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007775 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007776
Douglas Gregore47f5a72009-10-14 23:41:34 +00007777 // Check the scope of this explicit instantiation.
7778 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007780 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007781 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7782 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007783 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007784 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007785 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007786 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007787
Larisse Voufo39a1e502013-08-06 01:03:05 +00007788 if (!HasNoEffect) {
7789 // Instantiate static data member or variable template.
7790
7791 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7792 if (PrevTemplate) {
7793 // Merge attributes.
7794 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7795 ProcessDeclAttributeList(S, Prev, Attr);
7796 }
7797 if (TSK == TSK_ExplicitInstantiationDefinition)
7798 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7799 }
7800
7801 // Check the new variable specialization against the parsed input.
7802 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7803 Diag(T->getTypeLoc().getLocStart(),
7804 diag::err_invalid_var_template_spec_type)
7805 << 0 << PrevTemplate << R << Prev->getType();
7806 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7807 << 2 << PrevTemplate->getDeclName();
7808 return true;
7809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007810
Douglas Gregor450f00842009-09-25 18:43:00 +00007811 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007812 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007814
7815 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007816 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007817 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007818 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007819 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007820 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007821 HasExplicitTemplateArgs = true;
7822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007823
Douglas Gregor450f00842009-09-25 18:43:00 +00007824 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007825 // A [...] function [...] can be explicitly instantiated from its template.
7826 // A member function [...] of a class template can be explicitly
7827 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007828 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007829 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007830 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007831 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7832 P != PEnd; ++P) {
7833 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007834 if (!HasExplicitTemplateArgs) {
7835 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007836 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7837 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007838 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007839
John McCall58cc69d2010-01-27 01:50:18 +00007840 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007841 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7842 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007843 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007844 }
7845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007846
Douglas Gregor450f00842009-09-25 18:43:00 +00007847 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7848 if (!FunTmpl)
7849 continue;
7850
Larisse Voufo98b20f12013-07-19 23:00:19 +00007851 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007852 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007853 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007854 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007855 (HasExplicitTemplateArgs ? &TemplateArgs
7856 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007857 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007858 // Keep track of almost-matches.
7859 FailedCandidates.addCandidate()
7860 .set(FunTmpl->getTemplatedDecl(),
7861 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007862 (void)TDK;
7863 continue;
7864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865
John McCall58cc69d2010-01-27 01:50:18 +00007866 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007868
Douglas Gregor450f00842009-09-25 18:43:00 +00007869 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007870 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007871 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007872 D.getIdentifierLoc(),
7873 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7874 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7875 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007876
John McCall58cc69d2010-01-27 01:50:18 +00007877 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007878 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007879
7880 // Ignore access control bits, we don't need them for redeclaration checking.
7881 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007882
Alexey Bataev73983912014-11-06 10:10:50 +00007883 // C++11 [except.spec]p4
7884 // In an explicit instantiation an exception-specification may be specified,
7885 // but is not required.
7886 // If an exception-specification is specified in an explicit instantiation
7887 // directive, it shall be compatible with the exception-specifications of
7888 // other declarations of that function.
7889 if (auto *FPT = R->getAs<FunctionProtoType>())
7890 if (FPT->hasExceptionSpec()) {
7891 unsigned DiagID =
7892 diag::err_mismatched_exception_spec_explicit_instantiation;
7893 if (getLangOpts().MicrosoftExt)
7894 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7895 bool Result = CheckEquivalentExceptionSpec(
7896 PDiag(DiagID) << Specialization->getType(),
7897 PDiag(diag::note_explicit_instantiation_here),
7898 Specialization->getType()->getAs<FunctionProtoType>(),
7899 Specialization->getLocation(), FPT, D.getLocStart());
7900 // In Microsoft mode, mismatching exception specifications just cause a
7901 // warning.
7902 if (!getLangOpts().MicrosoftExt && Result)
7903 return true;
7904 }
7905
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007906 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007907 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007908 diag::err_explicit_instantiation_member_function_not_instantiated)
7909 << Specialization
7910 << (Specialization->getTemplateSpecializationKind() ==
7911 TSK_ExplicitSpecialization);
7912 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007914 }
7915
Douglas Gregorec9fd132012-01-14 16:38:05 +00007916 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007917 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7918 PrevDecl = Specialization;
7919
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007920 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007921 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007922 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007923 PrevDecl,
7924 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007925 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007926 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007927 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007928
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007929 // FIXME: We may still want to build some representation of this
7930 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007931 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007932 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007933 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007934
7935 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007936 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7937 if (Attr)
7938 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007939
Richard Smitheb36ddf2014-04-24 22:45:46 +00007940 if (Specialization->isDefined()) {
7941 // Let the ASTConsumer know that this function has been explicitly
7942 // instantiated now, and its linkage might have changed.
7943 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7944 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007945 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007946
Douglas Gregore47f5a72009-10-14 23:41:34 +00007947 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007948 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007949 // or a static data member of a class template specialization, the name of
7950 // the class template specialization in the qualified-id for the member
7951 // name shall be a simple-template-id.
7952 //
7953 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007954 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007955 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007956 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007957 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007959 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007960 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007961
Douglas Gregore47f5a72009-10-14 23:41:34 +00007962 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007963 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007964 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007965 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007966 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007967
Douglas Gregor450f00842009-09-25 18:43:00 +00007968 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007969 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007970}
7971
John McCallfaf5fb42010-08-26 23:41:50 +00007972TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007973Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7974 const CXXScopeSpec &SS, IdentifierInfo *Name,
7975 SourceLocation TagLoc, SourceLocation NameLoc) {
7976 // This has to hold, because SS is expected to be defined.
7977 assert(Name && "Expected a name in a dependent tag");
7978
Aaron Ballman4a979672014-01-03 13:56:08 +00007979 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007980 if (!NNS)
7981 return true;
7982
Abramo Bagnara6150c882010-05-11 21:36:43 +00007983 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007984
Douglas Gregorba41d012010-04-24 16:38:41 +00007985 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7986 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007987 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007988 return true;
7989 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007990
Douglas Gregore7c20652011-03-02 00:47:37 +00007991 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007992 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007993 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7994
7995 // Create type-source location information for this type.
7996 TypeLocBuilder TLB;
7997 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007998 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007999 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8000 TL.setNameLoc(NameLoc);
8001 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008002}
8003
John McCallfaf5fb42010-08-26 23:41:50 +00008004TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008005Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8006 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008007 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008008 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008009 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008010
Richard Smith0bf8a4922011-10-18 20:49:44 +00008011 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8012 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008013 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008014 diag::warn_cxx98_compat_typename_outside_of_template :
8015 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016 << FixItHint::CreateRemoval(TypenameLoc);
8017
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008018 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008019 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8020 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008021 if (T.isNull())
8022 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008023
8024 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8025 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008026 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008027 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008028 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008029 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008030 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008031 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008032 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008033 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008034 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008036
John McCallba7bf592010-08-24 05:47:05 +00008037 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008038}
8039
John McCallfaf5fb42010-08-26 23:41:50 +00008040TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008041Sema::ActOnTypenameType(Scope *S,
8042 SourceLocation TypenameLoc,
8043 const CXXScopeSpec &SS,
8044 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008045 TemplateTy TemplateIn,
8046 SourceLocation TemplateNameLoc,
8047 SourceLocation LAngleLoc,
8048 ASTTemplateArgsPtr TemplateArgsIn,
8049 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008050 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8051 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008052 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008053 diag::warn_cxx98_compat_typename_outside_of_template :
8054 diag::ext_typename_outside_of_template)
8055 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008056
8057 // Translate the parser's template argument list in our AST format.
8058 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8059 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8060
8061 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008062 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8063 // Construct a dependent template specialization type.
8064 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008065 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008066 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8067 DTN->getQualifier(),
8068 DTN->getIdentifier(),
8069 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008070
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008071 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008072 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008073 DependentTemplateSpecializationTypeLoc SpecTL
8074 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008075 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8076 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008077 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008078 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008079 SpecTL.setLAngleLoc(LAngleLoc);
8080 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008081 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8082 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008083 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008084 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008085
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008086 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8087 if (T.isNull())
8088 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008089
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008090 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008091 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008092 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008093 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008094 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8095 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008096 SpecTL.setLAngleLoc(LAngleLoc);
8097 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008098 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8099 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8100
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008101 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8102 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008103 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008104 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8105
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008106 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8107 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008108}
8109
Douglas Gregorb09518c2011-02-27 22:46:49 +00008110
Richard Smith6f8d2c62012-05-09 05:17:00 +00008111/// Determine whether this failed name lookup should be treated as being
8112/// disabled by a usage of std::enable_if.
8113static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8114 SourceRange &CondRange) {
8115 // We must be looking for a ::type...
8116 if (!II.isStr("type"))
8117 return false;
8118
8119 // ... within an explicitly-written template specialization...
8120 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8121 return false;
8122 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008123 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8124 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8125 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008126 return false;
8127 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008128 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008129
8130 // ... which names a complete class template declaration...
8131 const TemplateDecl *EnableIfDecl =
8132 EnableIfTST->getTemplateName().getAsTemplateDecl();
8133 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8134 return false;
8135
8136 // ... called "enable_if".
8137 const IdentifierInfo *EnableIfII =
8138 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8139 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8140 return false;
8141
8142 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008143 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008144 return true;
8145}
8146
Douglas Gregor333489b2009-03-27 23:10:48 +00008147/// \brief Build the type that describes a C++ typename specifier,
8148/// e.g., "typename T::type".
8149QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008150Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8151 SourceLocation KeywordLoc,
8152 NestedNameSpecifierLoc QualifierLoc,
8153 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008154 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008155 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008156 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008157
John McCall0b66eb32010-05-01 00:40:08 +00008158 DeclContext *Ctx = computeDeclContext(SS);
8159 if (!Ctx) {
8160 // If the nested-name-specifier is dependent and couldn't be
8161 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008162 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8163 return Context.getDependentNameType(Keyword,
8164 QualifierLoc.getNestedNameSpecifier(),
8165 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008166 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008167
John McCall0b66eb32010-05-01 00:40:08 +00008168 // If the nested-name-specifier refers to the current instantiation,
8169 // the "typename" keyword itself is superfluous. In C++03, the
8170 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8171 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008172 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008173
John McCall0b66eb32010-05-01 00:40:08 +00008174 if (RequireCompleteDeclContext(SS, Ctx))
8175 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008176
8177 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008178 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008179 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008180 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008181 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008182 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008183 case LookupResult::NotFound: {
8184 // If we're looking up 'type' within a template named 'enable_if', produce
8185 // a more specific diagnostic.
8186 SourceRange CondRange;
8187 if (isEnableIf(QualifierLoc, II, CondRange)) {
8188 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8189 << Ctx << CondRange;
8190 return QualType();
8191 }
8192
Douglas Gregore40876a2009-10-13 21:16:44 +00008193 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008194 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008195 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008196
8197 case LookupResult::FoundUnresolvedValue: {
8198 // We found a using declaration that is a value. Most likely, the using
8199 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008200 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008201 IILoc);
8202 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8203 << Name << Ctx << FullRange;
8204 if (UnresolvedUsingValueDecl *Using
8205 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008206 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008207 Diag(Loc, diag::note_using_value_decl_missing_typename)
8208 << FixItHint::CreateInsertion(Loc, "typename ");
8209 }
8210 }
8211 // Fall through to create a dependent typename type, from which we can recover
8212 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008213
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008214 case LookupResult::NotFoundInCurrentInstantiation:
8215 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008216 return Context.getDependentNameType(Keyword,
8217 QualifierLoc.getNestedNameSpecifier(),
8218 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008219
8220 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008221 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008222 // We found a type. Build an ElaboratedType, since the
8223 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008224 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008225 return Context.getElaboratedType(ETK_Typename,
8226 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008227 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008228 }
8229
8230 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008231 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008232 break;
8233
8234 case LookupResult::FoundOverloaded:
8235 DiagID = diag::err_typename_nested_not_type;
8236 Referenced = *Result.begin();
8237 break;
8238
John McCall6538c932009-10-10 05:48:19 +00008239 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008240 return QualType();
8241 }
8242
8243 // If we get here, it's because name lookup did not find a
8244 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008245 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008246 IILoc);
8247 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008248 if (Referenced)
8249 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8250 << Name;
8251 return QualType();
8252}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008253
8254namespace {
8255 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008256 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008257 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008258 SourceLocation Loc;
8259 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008260
Douglas Gregor15acfb92009-08-06 16:20:37 +00008261 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008262 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008263
Mike Stump11289f42009-09-09 15:08:12 +00008264 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008265 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008266 DeclarationName Entity)
8267 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008268 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008269
8270 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008271 /// transformed.
8272 ///
8273 /// For the purposes of type reconstruction, a type has already been
8274 /// transformed if it is NULL or if it is not dependent.
8275 bool AlreadyTransformed(QualType T) {
8276 return T.isNull() || !T->isDependentType();
8277 }
Mike Stump11289f42009-09-09 15:08:12 +00008278
8279 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008280 /// rebuilt.
8281 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008282
Douglas Gregor15acfb92009-08-06 16:20:37 +00008283 /// \brief Returns the name of the entity whose type is being rebuilt.
8284 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008285
Douglas Gregoref6ab412009-10-27 06:26:26 +00008286 /// \brief Sets the "base" location and entity when that
8287 /// information is known based on another transformation.
8288 void setBase(SourceLocation Loc, DeclarationName Entity) {
8289 this->Loc = Loc;
8290 this->Entity = Entity;
8291 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008292
8293 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8294 // Lambdas never need to be transformed.
8295 return E;
8296 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008297 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008298}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008299
Douglas Gregor15acfb92009-08-06 16:20:37 +00008300/// \brief Rebuilds a type within the context of the current instantiation.
8301///
Mike Stump11289f42009-09-09 15:08:12 +00008302/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008303/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008304/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008305/// partial specialization thereof). This routine will rebuild that type now
8306/// that we have entered the declarator's scope, which may produce different
8307/// canonical types, e.g.,
8308///
8309/// \code
8310/// template<typename T>
8311/// struct X {
8312/// typedef T* pointer;
8313/// pointer data();
8314/// };
8315///
8316/// template<typename T>
8317/// typename X<T>::pointer X<T>::data() { ... }
8318/// \endcode
8319///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008320/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008321/// since we do not know that we can look into X<T> when we parsed the type.
8322/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008323/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008324/// as the canonical type of T*, allowing the return types of the out-of-line
8325/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008326TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8327 SourceLocation Loc,
8328 DeclarationName Name) {
8329 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008330 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008331
Douglas Gregor15acfb92009-08-06 16:20:37 +00008332 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8333 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008334}
Douglas Gregorbe999392009-09-15 16:23:51 +00008335
John McCalldadc5752010-08-24 06:29:42 +00008336ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008337 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8338 DeclarationName());
8339 return Rebuilder.TransformExpr(E);
8340}
8341
John McCall99b2fe52010-04-29 23:50:39 +00008342bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008343 if (SS.isInvalid())
8344 return true;
John McCall2408e322010-04-27 00:57:59 +00008345
Douglas Gregor10176412011-02-25 16:07:42 +00008346 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008347 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8348 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008349 NestedNameSpecifierLoc Rebuilt
8350 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8351 if (!Rebuilt)
8352 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008353
Douglas Gregor10176412011-02-25 16:07:42 +00008354 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008355 return false;
John McCall2408e322010-04-27 00:57:59 +00008356}
8357
Douglas Gregor041b0842011-10-14 15:31:12 +00008358/// \brief Rebuild the template parameters now that we know we're in a current
8359/// instantiation.
8360bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8361 TemplateParameterList *Params) {
8362 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8363 Decl *Param = Params->getParam(I);
8364
8365 // There is nothing to rebuild in a type parameter.
8366 if (isa<TemplateTypeParmDecl>(Param))
8367 continue;
8368
8369 // Rebuild the template parameter list of a template template parameter.
8370 if (TemplateTemplateParmDecl *TTP
8371 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8372 if (RebuildTemplateParamsInCurrentInstantiation(
8373 TTP->getTemplateParameters()))
8374 return true;
8375
8376 continue;
8377 }
8378
8379 // Rebuild the type of a non-type template parameter.
8380 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8381 TypeSourceInfo *NewTSI
8382 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8383 NTTP->getLocation(),
8384 NTTP->getDeclName());
8385 if (!NewTSI)
8386 return true;
8387
8388 if (NewTSI != NTTP->getTypeSourceInfo()) {
8389 NTTP->setTypeSourceInfo(NewTSI);
8390 NTTP->setType(NewTSI->getType());
8391 }
8392 }
8393
8394 return false;
8395}
8396
Douglas Gregorbe999392009-09-15 16:23:51 +00008397/// \brief Produces a formatted string that describes the binding of
8398/// template parameters to template arguments.
8399std::string
8400Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8401 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008402 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008403}
8404
8405std::string
8406Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8407 const TemplateArgument *Args,
8408 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008409 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008410 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008411
Douglas Gregore62e6a02009-11-11 19:13:48 +00008412 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008413 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008414
Douglas Gregorbe999392009-09-15 16:23:51 +00008415 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008416 if (I >= NumArgs)
8417 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008418
Douglas Gregorbe999392009-09-15 16:23:51 +00008419 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008420 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008421 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008422 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008423
Douglas Gregorbe999392009-09-15 16:23:51 +00008424 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008425 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008426 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008427 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008429
Douglas Gregor0192c232010-12-20 16:52:59 +00008430 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008431 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008432 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008433
8434 Out << ']';
8435 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008436}
Francois Pichet1c229c02011-04-22 22:18:13 +00008437
Richard Smithe40f2ba2013-08-07 21:41:30 +00008438void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8439 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008440 if (!FD)
8441 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008442
8443 LateParsedTemplate *LPT = new LateParsedTemplate;
8444
8445 // Take tokens to avoid allocations
8446 LPT->Toks.swap(Toks);
8447 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008448 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008449
8450 FD->setLateTemplateParsed(true);
8451}
8452
8453void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8454 if (!FD)
8455 return;
8456 FD->setLateTemplateParsed(false);
8457}
Francois Pichet1c229c02011-04-22 22:18:13 +00008458
8459bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8460 DeclContext *DC = CurContext;
8461
8462 while (DC) {
8463 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8464 const FunctionDecl *FD = RD->isLocalClass();
8465 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8466 } else if (DC->isTranslationUnit() || DC->isNamespace())
8467 return false;
8468
8469 DC = DC->getParent();
8470 }
8471 return false;
8472}