blob: 73b5c44b5998a8dbc7bbe2659ae0ef81d9c08c75 [file] [log] [blame]
Eugene Zelenko1ced5092016-02-12 22:53:10 +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.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007//===----------------------------------------------------------------------===//
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Eugene Zelenko1ced5092016-02-12 22:53:10 +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"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Douglas Gregor5101c242008-12-05 18:15:24 +000036using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000038
John McCall9b72f892010-11-10 02:40:36 +000039// Exported for use by Parser.
40SourceRange
41clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
42 unsigned N) {
43 if (!N) return SourceRange();
44 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45}
46
Douglas Gregorb7bfe792009-09-02 22:59:36 +000047/// \brief Determine whether the declaration found is acceptable as the name
48/// of a template and, if so, return that template declaration. Otherwise,
49/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000050static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000051 NamedDecl *Orig,
52 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000053 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000054
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000055 if (isa<TemplateDecl>(D)) {
56 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000057 return nullptr;
58
John McCalle9cccd82010-06-16 08:42:20 +000059 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000060 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
63 // C++ [temp.local]p1:
64 // Like normal (non-template) classes, class templates have an
65 // injected-class-name (Clause 9). The injected-class-name
66 // can be used with or without a template-argument-list. When
67 // it is used without a template-argument-list, it is
68 // equivalent to the injected-class-name followed by the
69 // template-parameters of the class template enclosed in
70 // <>. When it is used with a template-argument-list, it
71 // refers to the specified class template specialization,
72 // which could be the current specialization or another
73 // specialization.
74 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000075 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (Record->getDescribedClassTemplate())
77 return Record->getDescribedClassTemplate();
78
79 if (ClassTemplateSpecializationDecl *Spec
80 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
81 return Spec->getSpecializedTemplate();
82 }
Mike Stump11289f42009-09-09 15:08:12 +000083
Craig Topperc3ec1492014-05-26 06:22:03 +000084 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000085 }
Mike Stump11289f42009-09-09 15:08:12 +000086
Craig Topperc3ec1492014-05-26 06:22:03 +000087 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000088}
89
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000090void Sema::FilterAcceptableTemplateNames(LookupResult &R,
91 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000092 // The set of class templates we've already seen.
93 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000094 LookupResult::Filter filter = R.makeFilter();
95 while (filter.hasNext()) {
96 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000097 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
98 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +000099 if (!Repl)
100 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000101 else if (Repl != Orig) {
102
103 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000105 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000106 // one base class). If all of the injected-class-names that are found
107 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000108 // is used as a template-name, the reference refers to the class
109 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000110 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000112 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000113 filter.erase();
114 continue;
115 }
John McCallbd8062d2010-08-13 07:02:08 +0000116
117 // FIXME: we promote access to public here as a workaround to
118 // the fact that LookupResult doesn't let us remember that we
119 // found this template through a particular injected class name,
120 // which means we end up doing nasty things to the invariants.
121 // Pretending that access is public is *much* safer.
122 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000123 }
John McCalle66edc12009-11-24 19:00:30 +0000124 }
125 filter.done();
126}
127
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000128bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
129 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000130 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000131 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000132 return true;
133
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000134 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000135}
136
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000138 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000139 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000140 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000141 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000142 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000143 TemplateTy &TemplateResult,
144 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000145 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000146
Douglas Gregor3cf81312009-11-03 23:16:33 +0000147 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000148 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Douglas Gregor3cf81312009-11-03 23:16:33 +0000150 switch (Name.getKind()) {
151 case UnqualifiedId::IK_Identifier:
152 TName = DeclarationName(Name.Identifier);
153 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000154
Douglas Gregor3cf81312009-11-03 23:16:33 +0000155 case UnqualifiedId::IK_OperatorFunctionId:
156 TName = Context.DeclarationNames.getCXXOperatorName(
157 Name.OperatorFunctionId.Operator);
158 break;
159
Alexis Hunted0530f2009-11-28 08:58:14 +0000160 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000161 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
162 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000163
Douglas Gregor3cf81312009-11-03 23:16:33 +0000164 default:
165 return TNK_Non_template;
166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
John McCallba7bf592010-08-24 05:47:05 +0000168 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000169
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000170 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000171 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
172 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000173 if (R.empty()) return TNK_Non_template;
174 if (R.isAmbiguous()) {
175 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000176 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000177
178 // FIXME: we might have ambiguous templates, in which case we
179 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000180 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000181 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000182
John McCalld28ae272009-12-02 08:04:21 +0000183 TemplateName Template;
184 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000185
John McCalld28ae272009-12-02 08:04:21 +0000186 unsigned ResultCount = R.end() - R.begin();
187 if (ResultCount > 1) {
188 // We assume that we'll preserve the qualifier from a function
189 // template name in other ways.
190 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
191 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000192
193 // We'll do this lookup again later.
194 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000195 } else {
John McCalld28ae272009-12-02 08:04:21 +0000196 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
197
198 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000199 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000200 Template = Context.getQualifiedTemplateName(Qualifier,
201 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000202 } else {
203 Template = TemplateName(TD);
204 }
205
John McCalldcc71402010-08-13 02:23:42 +0000206 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000207 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000208
209 // We'll do this lookup again later.
210 R.suppressDiagnostics();
211 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000212 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000213 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
214 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000215 TemplateKind =
216 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000217 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000218 }
Mike Stump11289f42009-09-09 15:08:12 +0000219
John McCalld28ae272009-12-02 08:04:21 +0000220 TemplateResult = TemplateTy::make(Template);
221 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000222}
223
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000225 SourceLocation IILoc,
226 Scope *S,
227 const CXXScopeSpec *SS,
228 TemplateTy &SuggestedTemplate,
229 TemplateNameKind &SuggestedKind) {
230 // We can't recover unless there's a dependent scope specifier preceding the
231 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000232 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000233 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
234 computeDeclContext(*SS))
235 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregor18473f32010-01-12 21:28:44 +0000237 // The code is missing a 'template' keyword prior to the dependent template
238 // name.
239 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
240 Diag(IILoc, diag::err_template_kw_missing)
241 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000242 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000243 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000244 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
245 SuggestedKind = TNK_Dependent_template_name;
246 return true;
247}
248
John McCalle66edc12009-11-24 19:00:30 +0000249void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000250 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000251 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000252 bool EnteringContext,
253 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000254 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000255 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000256 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000257 bool isDependent = false;
258 if (!ObjectType.isNull()) {
259 // This nested-name-specifier occurs in a member access expression, e.g.,
260 // x->B::f, and we are looking into the type of the object.
261 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
262 LookupCtx = computeDeclContext(ObjectType);
263 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000264 assert((isDependent || !ObjectType->isIncompleteType() ||
265 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000266 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000267
268 // Template names cannot appear inside an Objective-C class or object type.
269 if (ObjectType->isObjCObjectOrInterfaceType()) {
270 Found.clear();
271 return;
272 }
John McCalle66edc12009-11-24 19:00:30 +0000273 } else if (SS.isSet()) {
274 // This nested-name-specifier occurs after another nested-name-specifier,
275 // so long into the context associated with the prior nested-name-specifier.
276 LookupCtx = computeDeclContext(SS, EnteringContext);
277 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
John McCalle66edc12009-11-24 19:00:30 +0000279 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000280 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000281 return;
282 }
283
284 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000285 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000286 if (LookupCtx) {
287 // Perform "qualified" name lookup into the declaration context we
288 // computed, which is either the type of the base of a member access
289 // expression or the declaration context associated with a prior
290 // nested-name-specifier.
291 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000292 if (!ObjectType.isNull() && Found.empty()) {
293 // C++ [basic.lookup.classref]p1:
294 // In a class member access expression (5.2.5), if the . or -> token is
295 // immediately followed by an identifier followed by a <, the
296 // identifier must be looked up to determine whether the < is the
297 // beginning of a template argument list (14.2) or a less-than operator.
298 // The identifier is first looked up in the class of the object
299 // expression. If the identifier is not found, it is then looked up in
300 // the context of the entire postfix-expression and shall name a class
301 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000302 if (S) LookupName(Found, S);
303 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000304 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000305 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000306 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000307 // We cannot look into a dependent object type or nested nme
308 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000309 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000310 return;
311 } else {
312 // Perform unqualified name lookup in the current scope.
313 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000314
315 if (!ObjectType.isNull())
316 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000317 }
318
Douglas Gregorc119dd52010-01-12 17:06:20 +0000319 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000320 // If we did not find any names, attempt to correct any typos.
321 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000322 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000323 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000324 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
325 FilterCCC->WantTypeSpecifiers = false;
326 FilterCCC->WantExpressionKeywords = false;
327 FilterCCC->WantRemainingKeywords = false;
328 FilterCCC->WantCXXNamedCasts = true;
329 if (TypoCorrection Corrected = CorrectTypo(
330 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
331 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000332 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000333 if (auto *ND = Corrected.getFoundDecl())
334 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000335 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000336 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000337 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000338 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
339 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000340 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000341 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
342 << Name << LookupCtx << DroppedSpecifier
343 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000344 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000345 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000346 }
John McCalle9cccd82010-06-16 08:42:20 +0000347 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000348 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000349 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000350 }
351 }
352
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000353 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000354 if (Found.empty()) {
355 if (isDependent)
356 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000357 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000358 }
John McCalle66edc12009-11-24 19:00:30 +0000359
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000360 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000361 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000362 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000363 // [...] If the lookup in the class of the object expression finds a
364 // template, the name is also looked up in the context of the entire
365 // postfix-expression and [...]
366 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000367 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000368 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
369 LookupOrdinaryName);
370 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000371 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000372
John McCalle66edc12009-11-24 19:00:30 +0000373 if (FoundOuter.empty()) {
374 // - if the name is not found, the name found in the class of the
375 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000376 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
377 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000378 // - if the name is found in the context of the entire
379 // postfix-expression and does not name a class template, the name
380 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000381 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000382 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000383 // - if the name found is a class template, it must refer to the same
384 // entity as the one found in the class of the object expression,
385 // otherwise the program is ill-formed.
386 if (!Found.isSingleResult() ||
387 Found.getFoundDecl()->getCanonicalDecl()
388 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000390 diag::ext_nested_name_member_ref_lookup_ambiguous)
391 << Found.getLookupName()
392 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000393 Diag(Found.getRepresentativeDecl()->getLocation(),
394 diag::note_ambig_member_ref_object_type)
395 << ObjectType;
396 Diag(FoundOuter.getFoundDecl()->getLocation(),
397 diag::note_ambig_member_ref_scope);
398
399 // Recover by taking the template that we found in the object
400 // expression's type.
401 }
402 }
403 }
404}
405
John McCallcd4b4772009-12-02 03:53:29 +0000406/// ActOnDependentIdExpression - Handle a dependent id-expression that
407/// was just parsed. This is only possible with an explicit scope
408/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000409ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000410Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000411 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000412 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000413 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000414 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000415 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
Reid Kleckner1af391df2016-03-11 18:59:12 +0000417 // C++11 [expr.prim.general]p12:
418 // An id-expression that denotes a non-static data member or non-static
419 // member function of a class can only be used:
420 // (...)
421 // - if that id-expression denotes a non-static data member and it
422 // appears in an unevaluated operand.
423 //
424 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
425 // CXXDependentScopeMemberExpr. The former can instantiate to either
426 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
427 // always a MemberExpr.
428 bool MightBeCxx11UnevalField =
429 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
430
431 if (!MightBeCxx11UnevalField && !isAddressOfOperand &&
432 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000433 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
John McCalle66edc12009-11-24 19:00:30 +0000435 // Since the 'this' expression is synthesized, we don't need to
436 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000437 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000438
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000439 return CXXDependentScopeMemberExpr::Create(
440 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
441 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
442 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000443 }
444
Abramo Bagnara7945c982012-01-27 09:46:47 +0000445 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000446}
447
John McCalldadc5752010-08-24 06:29:42 +0000448ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000449Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000450 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000451 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000452 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000453 return DependentScopeDeclRefExpr::Create(
454 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
455 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000456}
457
Douglas Gregor5101c242008-12-05 18:15:24 +0000458/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
459/// that the template parameter 'PrevDecl' is being shadowed by a new
460/// declaration at location Loc. Returns true to indicate that this is
461/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000462void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000463 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000464
465 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000466 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000467 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000468
469 // C++ [temp.local]p4:
470 // A template-parameter shall not be redeclared within its
471 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000472 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000473 << cast<NamedDecl>(PrevDecl)->getDeclName();
474 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000475}
476
Douglas Gregor463421d2009-03-03 04:44:36 +0000477/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000478/// the parameter D to reference the templated declaration and return a pointer
479/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000480TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
481 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
482 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000483 return Temp;
484 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000485 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000486}
487
Douglas Gregoreb29d182011-01-05 17:40:24 +0000488ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
489 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000491 "Only template template arguments can be pack expansions here");
492 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
493 "Template template argument pack expansion without packs");
494 ParsedTemplateArgument Result(*this);
495 Result.EllipsisLoc = EllipsisLoc;
496 return Result;
497}
498
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000499static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
500 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000502 switch (Arg.getKind()) {
503 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000504 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000505 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000507 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000508 return TemplateArgumentLoc(TemplateArgument(T), DI);
509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000511 case ParsedTemplateArgument::NonType: {
512 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
513 return TemplateArgumentLoc(TemplateArgument(E), E);
514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000516 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000517 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000518 TemplateArgument TArg;
519 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000520 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000521 else
522 TArg = Template;
523 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000524 Arg.getScopeSpec().getWithLocInContext(
525 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000526 Arg.getLocation(),
527 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000528 }
529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000531 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000532}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000534/// \brief Translates template arguments as provided by the parser
535/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000536void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
537 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000538 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000539 TemplateArgs.addArgument(translateTemplateArgument(*this,
540 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000541}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
Richard Smithb80d5402013-06-25 22:21:36 +0000543static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
544 SourceLocation Loc,
545 IdentifierInfo *Name) {
546 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
547 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
548 if (PrevDecl && PrevDecl->isTemplateParameter())
549 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
550}
551
Douglas Gregor5101c242008-12-05 18:15:24 +0000552/// ActOnTypeParameter - Called when a C++ template type parameter
553/// (e.g., "typename T") has been parsed. Typename specifies whether
554/// the keyword "typename" was used to declare the type parameter
555/// (otherwise, "class" was used), and KeyLoc is the location of the
556/// "class" or "typename" keyword. ParamName is the name of the
557/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000558/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000559/// If the type parameter has a default argument, it will be added
560/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000561Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000562 SourceLocation EllipsisLoc,
563 SourceLocation KeyLoc,
564 IdentifierInfo *ParamName,
565 SourceLocation ParamNameLoc,
566 unsigned Depth, unsigned Position,
567 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000568 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000569 assert(S->isTemplateParamScope() &&
570 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000571
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000572 SourceLocation Loc = ParamNameLoc;
573 if (!ParamName)
574 Loc = KeyLoc;
575
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000576 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000578 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000579 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000580 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000581 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000582
583 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000584 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
585
Douglas Gregor5101c242008-12-05 18:15:24 +0000586 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000587 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000588 IdResolver.AddDecl(Param);
589 }
590
Douglas Gregorf5500772011-01-05 15:48:55 +0000591 // C++0x [temp.param]p9:
592 // A default template-argument may be specified for any kind of
593 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000594 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000595 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000596 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000597 }
598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 // Handle the default argument, if provided.
600 if (DefaultArg) {
601 TypeSourceInfo *DefaultTInfo;
602 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603
Douglas Gregordc13ded2010-07-01 00:00:45 +0000604 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000606 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000608 UPPC_DefaultArgument))
609 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregordc13ded2010-07-01 00:00:45 +0000611 // Check the template argument itself.
612 if (CheckTemplateArgument(Param, DefaultTInfo)) {
613 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000614 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Richard Smith1469b912015-06-10 00:29:03 +0000617 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
John McCall48871652010-08-21 09:40:31 +0000620 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000621}
622
Douglas Gregor463421d2009-03-03 04:44:36 +0000623/// \brief Check that the type of a non-type template parameter is
624/// well-formed.
625///
626/// \returns the (possibly-promoted) parameter type if valid;
627/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000628QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000629Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000630 // We don't allow variably-modified types as the type of non-type template
631 // parameters.
632 if (T->isVariablyModifiedType()) {
633 Diag(Loc, diag::err_variably_modified_nontype_template_param)
634 << T;
635 return QualType();
636 }
637
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 // C++ [temp.param]p4:
639 //
640 // A non-type template-parameter shall have one of the following
641 // (optionally cv-qualified) types:
642 //
643 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000644 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000645 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000646 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000647 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000649 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000650 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000651 // -- std::nullptr_t.
652 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000653 // If T is a dependent type, we can't do the check now, so we
654 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000655 T->isDependentType()) {
656 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
657 // are ignored when determining its type.
658 return T.getUnqualifiedType();
659 }
660
Douglas Gregor463421d2009-03-03 04:44:36 +0000661 // C++ [temp.param]p8:
662 //
663 // A non-type template-parameter of type "array of T" or
664 // "function returning T" is adjusted to be of type "pointer to
665 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000666 else if (T->isArrayType() || T->isFunctionType())
667 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668
Douglas Gregor463421d2009-03-03 04:44:36 +0000669 Diag(Loc, diag::err_template_nontype_parm_bad_type)
670 << T;
671
672 return QualType();
673}
674
John McCall48871652010-08-21 09:40:31 +0000675Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
676 unsigned Depth,
677 unsigned Position,
678 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000679 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000680 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
681 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000682
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000683 assert(S->isTemplateParamScope() &&
684 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000685 bool Invalid = false;
686
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000687 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
688 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000689 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000690 Invalid = true;
691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692
Richard Smithb80d5402013-06-25 22:21:36 +0000693 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000694 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000695 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000696 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000697 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000698 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000700 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000701 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000702
Douglas Gregor5101c242008-12-05 18:15:24 +0000703 if (Invalid)
704 Param->setInvalidDecl();
705
Richard Smithb80d5402013-06-25 22:21:36 +0000706 if (ParamName) {
707 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
708 ParamName);
709
Douglas Gregor5101c242008-12-05 18:15:24 +0000710 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000711 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000712 IdResolver.AddDecl(Param);
713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregorf5500772011-01-05 15:48:55 +0000715 // C++0x [temp.param]p9:
716 // A default template-argument may be specified for any kind of
717 // template-parameter that is not a template parameter pack.
718 if (Default && IsParameterPack) {
719 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000720 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000721 }
722
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000724 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000725 // Check for unexpanded parameter packs.
726 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
727 return Param;
728
Douglas Gregordc13ded2010-07-01 00:00:45 +0000729 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000730 ExprResult DefaultRes =
731 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000732 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000733 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000734 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000735 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000736 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737
Richard Smith1469b912015-06-10 00:29:03 +0000738 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
John McCall48871652010-08-21 09:40:31 +0000741 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000742}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000743
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000744/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000745/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000746/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000747Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
748 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000749 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000750 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000751 IdentifierInfo *Name,
752 SourceLocation NameLoc,
753 unsigned Depth,
754 unsigned Position,
755 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000756 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000757 assert(S->isTemplateParamScope() &&
758 "Template template parameter not in template parameter scope!");
759
760 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000761 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000762 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000763 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764 NameLoc.isInvalid()? TmpLoc : NameLoc,
765 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000766 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000767 Param->setAccess(AS_public);
768
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000770 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000771 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000772 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
773
John McCall48871652010-08-21 09:40:31 +0000774 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000775 IdResolver.AddDecl(Param);
776 }
777
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000778 if (Params->size() == 0) {
779 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
780 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
781 Param->setInvalidDecl();
782 }
783
Douglas Gregorf5500772011-01-05 15:48:55 +0000784 // C++0x [temp.param]p9:
785 // A default template-argument may be specified for any kind of
786 // template-parameter that is not a template parameter pack.
787 if (IsParameterPack && !Default.isInvalid()) {
788 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
789 Default = ParsedTemplateArgument();
790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000791
Douglas Gregordc13ded2010-07-01 00:00:45 +0000792 if (!Default.isInvalid()) {
793 // Check only that we have a template template argument. We don't want to
794 // try to check well-formedness now, because our template template parameter
795 // might have dependent types in its template parameters, which we wouldn't
796 // be able to match now.
797 //
798 // If none of the template template parameter's template arguments mention
799 // other template parameters, we could actually perform more checking here.
800 // However, it isn't worth doing.
801 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
802 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000803 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000804 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000805 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000808 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000810 DefaultArg.getArgument().getAsTemplate(),
811 UPPC_DefaultArgument))
812 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813
Richard Smith1469b912015-06-10 00:29:03 +0000814 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
John McCall48871652010-08-21 09:40:31 +0000817 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000818}
819
Hubert Tongf608c052016-04-29 18:05:37 +0000820/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
821/// constrained by RequiresClause, that contains the template parameters in
822/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000823TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000824Sema::ActOnTemplateParameterList(unsigned Depth,
825 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000826 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000827 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000828 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000829 SourceLocation RAngleLoc,
830 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000831 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000832 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000833
Hubert Tongf608c052016-04-29 18:05:37 +0000834 // FIXME: store RequiresClause
David Majnemer902f8c62015-12-27 07:16:27 +0000835 return TemplateParameterList::Create(
836 Context, TemplateLoc, LAngleLoc,
837 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
838 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000839}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000840
John McCall3e11ebe2010-03-15 10:12:16 +0000841static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
842 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000843 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000844}
845
John McCallfaf5fb42010-08-26 23:41:50 +0000846DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000847Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000848 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849 IdentifierInfo *Name, SourceLocation NameLoc,
850 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000851 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000852 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000853 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000854 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000855 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000856 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000857 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000858 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000859 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000860 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000861
862 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000863 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000864 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865
Abramo Bagnara6150c882010-05-11 21:36:43 +0000866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
867 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000868
869 // There is no such thing as an unnamed class template.
870 if (!Name) {
871 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000872 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000873 }
874
Richard Smith6483d222012-04-21 01:27:54 +0000875 // Find any previous declaration with this name. For a friend with no
876 // scope explicitly specified, we only look for tag declarations (per
877 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000878 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000879 LookupResult Previous(*this, Name, NameLoc,
880 (SS.isEmpty() && TUK == TUK_Friend)
881 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000882 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000883 if (SS.isNotEmpty() && !SS.isInvalid()) {
884 SemanticContext = computeDeclContext(SS, true);
885 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000886 // FIXME: Horrible, horrible hack! We can't currently represent this
887 // in the AST, and historically we have just ignored such friend
888 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000889 Diag(NameLoc, TUK == TUK_Friend
890 ? diag::warn_template_qualified_friend_ignored
891 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000892 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000893 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895
John McCall0b66eb32010-05-01 00:40:08 +0000896 if (RequireCompleteDeclContext(SS, SemanticContext))
897 return true;
898
Douglas Gregor041b0842011-10-14 15:31:12 +0000899 // If we're adding a template to a dependent context, we may need to
900 // rebuilding some of the types used within the template parameter list,
901 // now that we know what the current instantiation is.
902 if (SemanticContext->isDependentContext()) {
903 ContextRAII SavedContext(*this, SemanticContext);
904 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
905 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000906 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
907 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000908
John McCall27b18f82009-11-17 02:14:36 +0000909 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000910 } else {
911 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000912
913 // C++14 [class.mem]p14:
914 // If T is the name of a class, then each of the following shall have a
915 // name different from T:
916 // -- every member template of class T
917 if (TUK != TUK_Friend &&
918 DiagnoseClassNameShadow(SemanticContext,
919 DeclarationNameInfo(Name, NameLoc)))
920 return true;
921
John McCall27b18f82009-11-17 02:14:36 +0000922 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000923 }
Mike Stump11289f42009-09-09 15:08:12 +0000924
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000925 if (Previous.isAmbiguous())
926 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927
Craig Topperc3ec1492014-05-26 06:22:03 +0000928 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000929 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000930 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000931
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932 // If there is a previous declaration with the same name, check
933 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000934 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000935 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000936
937 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000939 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000941 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
942 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000943 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000944 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
945 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
946 PrevClassTemplate
947 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
948 ->getSpecializedTemplate();
949 }
950 }
951
John McCalld43784f2009-12-18 11:25:59 +0000952 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000953 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 // [...] When looking for a prior declaration of a class or a function
955 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000956 // function is neither a qualified name nor a template-id, scopes outside
957 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000958 if (!SS.isSet()) {
959 DeclContext *OutermostContext = CurContext;
960 while (!OutermostContext->isFileContext())
961 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000962
Richard Smith61e582f2012-04-20 07:12:26 +0000963 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000964 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
965 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
966 SemanticContext = PrevDecl->getDeclContext();
967 } else {
968 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000970 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000971 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000972 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000973
974 // Check that the chosen semantic context doesn't already contain a
975 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000976 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000977 DeclContext *LookupContext = SemanticContext;
978 while (LookupContext->isTransparentContext())
979 LookupContext = LookupContext->getLookupParent();
980 LookupQualifiedName(Previous, LookupContext);
981
982 if (Previous.isAmbiguous())
983 return true;
984
985 if (Previous.begin() != Previous.end())
986 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000987 }
John McCall90d3bb92009-12-17 23:21:11 +0000988 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000989 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000990 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
991 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000992 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993
Richard Smithfc805ca2015-07-06 04:43:58 +0000994 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
995 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
996 if (SS.isEmpty() &&
997 !(PrevClassTemplate &&
998 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
999 SemanticContext->getRedeclContext()))) {
1000 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1001 Diag(Shadow->getTargetDecl()->getLocation(),
1002 diag::note_using_decl_target);
1003 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1004 // Recover by ignoring the old declaration.
1005 PrevDecl = PrevClassTemplate = nullptr;
1006 }
1007 }
1008
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001009 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001010 // Ensure that the template parameter lists are compatible. Skip this check
1011 // for a friend in a dependent context: the template parameter list itself
1012 // could be dependent.
1013 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1014 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001015 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001016 /*Complain=*/true,
1017 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001018 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001019
1020 // C++ [temp.class]p4:
1021 // In a redeclaration, partial specialization, explicit
1022 // specialization or explicit instantiation of a class template,
1023 // the class-key shall agree in kind with the original class
1024 // template declaration (7.1.5.3).
1025 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001026 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001027 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001028 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001029 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001030 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001031 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001032 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001033 }
1034
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001035 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001036 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001037 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001038 // If we have a prior definition that is not visible, treat this as
1039 // simply making that previous definition visible.
1040 NamedDecl *Hidden = nullptr;
1041 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001042 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001043 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1044 assert(Tmpl && "original definition of a class template is not a "
1045 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001046 makeMergedDefinitionVisible(Hidden, KWLoc);
1047 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001048 return Def;
1049 }
1050
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001051 Diag(NameLoc, diag::err_redefinition) << Name;
1052 Diag(Def->getLocation(), diag::note_previous_definition);
1053 // FIXME: Would it make sense to try to "forget" the previous
1054 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001055 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001056 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001057 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001058 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1059 // Maybe we will complain about the shadowed template parameter.
1060 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1061 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001062 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001063 } else if (PrevDecl) {
1064 // C++ [temp]p5:
1065 // A class template shall not have the same name as any other
1066 // template, class, function, object, enumeration, enumerator,
1067 // namespace, or type in the same scope (3.3), except as specified
1068 // in (14.5.4).
1069 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1070 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001071 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001072 }
1073
Douglas Gregordba32632009-02-10 19:49:53 +00001074 // Check the template parameter list of this declaration, possibly
1075 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001076 // template declaration. Skip this check for a friend in a dependent
1077 // context, because the template parameter list might be dependent.
1078 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001079 CheckTemplateParameterList(
1080 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001081 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1082 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001083 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1084 SemanticContext->isDependentContext())
1085 ? TPC_ClassTemplateMember
1086 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1087 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001088 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001089
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001090 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001092 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001093 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1094 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001095 : diag::err_member_decl_does_not_match)
1096 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001097 Invalid = true;
1098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 }
1100
Mike Stump11289f42009-09-09 15:08:12 +00001101 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001102 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001103 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001104 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001105 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001106 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001107 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001108 NewClass->setTemplateParameterListsInfo(
1109 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1110 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001111
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001112 // Add alignment attributes if necessary; these attributes are checked when
1113 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001114 if (TUK == TUK_Definition) {
1115 AddAlignmentAttributesForRecord(NewClass);
1116 AddMsStructLayoutForRecord(NewClass);
1117 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001118
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001119 ClassTemplateDecl *NewTemplate
1120 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1121 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001122 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001123 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001124
Douglas Gregor21823bf2011-12-20 18:11:52 +00001125 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001126 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001127
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001128 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001129 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001130 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001131 assert(T->isDependentType() && "Class template type is not dependent?");
1132 (void)T;
1133
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001135 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001137 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1138 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Anders Carlsson137108d2009-03-26 01:24:28 +00001140 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001141 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001142 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001144 // Set the lexical context of these templates
1145 NewClass->setLexicalDeclContext(CurContext);
1146 NewTemplate->setLexicalDeclContext(CurContext);
1147
John McCall9bb74a52009-07-31 02:45:11 +00001148 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001149 NewClass->startDefinition();
1150
1151 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001152 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001153
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001154 if (PrevClassTemplate)
1155 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1156
Rafael Espindola385c0422012-07-13 18:04:45 +00001157 AddPushedVisibilityAttribute(NewClass);
1158
Richard Smith234ff472014-08-23 00:49:01 +00001159 if (TUK != TUK_Friend) {
1160 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1161 Scope *Outer = S;
1162 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1163 Outer = Outer->getParent();
1164 PushOnScopeChains(NewTemplate, Outer);
1165 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001166 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001167 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001168 NewClass->setAccess(PrevClassTemplate->getAccess());
1169 }
John McCall27b5c252009-09-14 21:59:20 +00001170
Richard Smith64017682013-07-17 23:53:16 +00001171 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172
John McCall27b5c252009-09-14 21:59:20 +00001173 // Friend templates are visible in fairly strange ways.
1174 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001175 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001176 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001177 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1178 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001182 FriendDecl *Friend = FriendDecl::Create(
1183 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001184 Friend->setAccess(AS_public);
1185 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001186 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001187
Douglas Gregordba32632009-02-10 19:49:53 +00001188 if (Invalid) {
1189 NewTemplate->setInvalidDecl();
1190 NewClass->setInvalidDecl();
1191 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001192
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001193 ActOnDocumentableDecl(NewTemplate);
1194
John McCall48871652010-08-21 09:40:31 +00001195 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001196}
1197
Douglas Gregored5731f2009-11-25 17:50:39 +00001198/// \brief Diagnose the presence of a default template argument on a
1199/// template parameter, which is ill-formed in certain contexts.
1200///
1201/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001203 Sema::TemplateParamListContext TPC,
1204 SourceLocation ParamLoc,
1205 SourceRange DefArgRange) {
1206 switch (TPC) {
1207 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001208 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001209 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001210 return false;
1211
1212 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001213 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001215 // A default template-argument shall not be specified in a
1216 // function template declaration or a function template
1217 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001218 // If a friend function template declaration specifies a default
1219 // template-argument, that declaration shall be a definition and shall be
1220 // the only declaration of the function template in the translation unit.
1221 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001222 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001223 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1224 : diag::ext_template_parameter_default_in_function_template)
1225 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001226 return false;
1227
1228 case Sema::TPC_ClassTemplateMember:
1229 // C++0x [temp.param]p9:
1230 // A default template-argument shall not be specified in the
1231 // template-parameter-lists of the definition of a member of a
1232 // class template that appears outside of the member's class.
1233 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1234 << DefArgRange;
1235 return true;
1236
David Majnemerba8f17a2013-06-25 22:08:55 +00001237 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001238 case Sema::TPC_FriendFunctionTemplate:
1239 // C++ [temp.param]p9:
1240 // A default template-argument shall not be specified in a
1241 // friend template declaration.
1242 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1243 << DefArgRange;
1244 return true;
1245
1246 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1247 // for friend function templates if there is only a single
1248 // declaration (and it is a definition). Strange!
1249 }
1250
David Blaikie8a40f702012-01-17 06:56:22 +00001251 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001252}
1253
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001254/// \brief Check for unexpanded parameter packs within the template parameters
1255/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001256static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1257 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001258 // A template template parameter which is a parameter pack is also a pack
1259 // expansion.
1260 if (TTP->isParameterPack())
1261 return false;
1262
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001263 TemplateParameterList *Params = TTP->getTemplateParameters();
1264 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1265 NamedDecl *P = Params->getParam(I);
1266 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001267 if (!NTTP->isParameterPack() &&
1268 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001269 NTTP->getTypeSourceInfo(),
1270 Sema::UPPC_NonTypeTemplateParameterType))
1271 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001273 continue;
1274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275
1276 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001277 = dyn_cast<TemplateTemplateParmDecl>(P))
1278 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1279 return true;
1280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001282 return false;
1283}
1284
Douglas Gregordba32632009-02-10 19:49:53 +00001285/// \brief Checks the validity of a template parameter list, possibly
1286/// considering the template parameter list from a previous
1287/// declaration.
1288///
1289/// If an "old" template parameter list is provided, it must be
1290/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1291/// template parameter list.
1292///
1293/// \param NewParams Template parameter list for a new template
1294/// declaration. This template parameter list will be updated with any
1295/// default arguments that are carried through from the previous
1296/// template parameter list.
1297///
1298/// \param OldParams If provided, template parameter list from a
1299/// previous declaration of the same template. Default template
1300/// arguments will be merged from the old template parameter list to
1301/// the new template parameter list.
1302///
Douglas Gregored5731f2009-11-25 17:50:39 +00001303/// \param TPC Describes the context in which we are checking the given
1304/// template parameter list.
1305///
Douglas Gregordba32632009-02-10 19:49:53 +00001306/// \returns true if an error occurred, false otherwise.
1307bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001308 TemplateParameterList *OldParams,
1309 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001310 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Douglas Gregordba32632009-02-10 19:49:53 +00001312 // C++ [temp.param]p10:
1313 // The set of default template-arguments available for use with a
1314 // template declaration or definition is obtained by merging the
1315 // default arguments from the definition (if in scope) and all
1316 // declarations in scope in the same way default function
1317 // arguments are (8.3.6).
1318 bool SawDefaultArgument = false;
1319 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001320
Mike Stumpc89c8e32009-02-11 23:03:27 +00001321 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001322 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001323 if (OldParams)
1324 OldParam = OldParams->begin();
1325
Douglas Gregor0693def2011-01-27 01:40:17 +00001326 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001327 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1328 NewParamEnd = NewParams->end();
1329 NewParam != NewParamEnd; ++NewParam) {
1330 // Variables used to diagnose redundant default arguments
1331 bool RedundantDefaultArg = false;
1332 SourceLocation OldDefaultLoc;
1333 SourceLocation NewDefaultLoc;
1334
David Blaikie651c73c2011-10-19 05:19:50 +00001335 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001336 bool MissingDefaultArg = false;
1337
David Blaikie651c73c2011-10-19 05:19:50 +00001338 // Variable used to diagnose non-final parameter packs
1339 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001340
Douglas Gregordba32632009-02-10 19:49:53 +00001341 if (TemplateTypeParmDecl *NewTypeParm
1342 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001343 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344 if (NewTypeParm->hasDefaultArgument() &&
1345 DiagnoseDefaultTemplateArgument(*this, TPC,
1346 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001347 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001348 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001349 NewTypeParm->removeDefaultArgument();
1350
1351 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001352 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001353 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001354 if (NewTypeParm->isParameterPack()) {
1355 assert(!NewTypeParm->hasDefaultArgument() &&
1356 "Parameter packs can't have a default argument!");
1357 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001358 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001359 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001360 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1361 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1362 SawDefaultArgument = true;
1363 RedundantDefaultArg = true;
1364 PreviousDefaultArgLoc = NewDefaultLoc;
1365 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1366 // Merge the default argument from the old declaration to the
1367 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001368 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001369 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1370 } else if (NewTypeParm->hasDefaultArgument()) {
1371 SawDefaultArgument = true;
1372 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1373 } else if (SawDefaultArgument)
1374 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001375 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001376 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001377 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001378 if (!NewNonTypeParm->isParameterPack() &&
1379 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001381 UPPC_NonTypeTemplateParameterType)) {
1382 Invalid = true;
1383 continue;
1384 }
1385
Douglas Gregored5731f2009-11-25 17:50:39 +00001386 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 if (NewNonTypeParm->hasDefaultArgument() &&
1388 DiagnoseDefaultTemplateArgument(*this, TPC,
1389 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001390 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001391 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001392 }
1393
Mike Stump12b8ce12009-08-04 21:02:39 +00001394 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001395 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001396 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001397 if (NewNonTypeParm->isParameterPack()) {
1398 assert(!NewNonTypeParm->hasDefaultArgument() &&
1399 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001400 if (!NewNonTypeParm->isPackExpansion())
1401 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001402 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001403 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001404 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1405 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1406 SawDefaultArgument = true;
1407 RedundantDefaultArg = true;
1408 PreviousDefaultArgLoc = NewDefaultLoc;
1409 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1410 // Merge the default argument from the old declaration to the
1411 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001412 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001413 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1414 } else if (NewNonTypeParm->hasDefaultArgument()) {
1415 SawDefaultArgument = true;
1416 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1417 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001418 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001419 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001420 TemplateTemplateParmDecl *NewTemplateParm
1421 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001423 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001424 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001425 Invalid = true;
1426 continue;
1427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428
David Blaikie651c73c2011-10-19 05:19:50 +00001429 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430 if (NewTemplateParm->hasDefaultArgument() &&
1431 DiagnoseDefaultTemplateArgument(*this, TPC,
1432 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001433 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001434 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001435
1436 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001437 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001438 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001439 if (NewTemplateParm->isParameterPack()) {
1440 assert(!NewTemplateParm->hasDefaultArgument() &&
1441 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001442 if (!NewTemplateParm->isPackExpansion())
1443 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001444 } else if (OldTemplateParm &&
1445 hasVisibleDefaultArgument(OldTemplateParm) &&
1446 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001447 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1448 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001449 SawDefaultArgument = true;
1450 RedundantDefaultArg = true;
1451 PreviousDefaultArgLoc = NewDefaultLoc;
1452 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1453 // Merge the default argument from the old declaration to the
1454 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001455 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001456 PreviousDefaultArgLoc
1457 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001458 } else if (NewTemplateParm->hasDefaultArgument()) {
1459 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001460 PreviousDefaultArgLoc
1461 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001462 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001463 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001464 }
1465
Richard Smith1fde8ec2012-09-07 02:06:42 +00001466 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001467 // If a template parameter of a primary class template or alias template
1468 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001469 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001470 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1471 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001472 Diag((*NewParam)->getLocation(),
1473 diag::err_template_param_pack_must_be_last_template_parameter);
1474 Invalid = true;
1475 }
1476
Douglas Gregordba32632009-02-10 19:49:53 +00001477 if (RedundantDefaultArg) {
1478 // C++ [temp.param]p12:
1479 // A template-parameter shall not be given default arguments
1480 // by two different declarations in the same scope.
1481 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1482 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1483 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001484 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001485 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001486 // If a template-parameter of a class template has a default
1487 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001488 // have a default template-argument supplied or be a template parameter
1489 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001490 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001491 diag::err_template_param_default_arg_missing);
1492 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1493 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001494 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001495 }
1496
1497 // If we have an old template parameter list that we're merging
1498 // in, move on to the next parameter.
1499 if (OldParams)
1500 ++OldParam;
1501 }
1502
Douglas Gregor0693def2011-01-27 01:40:17 +00001503 // We were missing some default arguments at the end of the list, so remove
1504 // all of the default arguments.
1505 if (RemoveDefaultArguments) {
1506 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1507 NewParamEnd = NewParams->end();
1508 NewParam != NewParamEnd; ++NewParam) {
1509 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1510 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001512 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1513 NTTP->removeDefaultArgument();
1514 else
1515 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1516 }
1517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518
Douglas Gregordba32632009-02-10 19:49:53 +00001519 return Invalid;
1520}
Douglas Gregord32e0282009-02-09 23:23:08 +00001521
John McCalla020a012010-10-20 05:44:58 +00001522namespace {
1523
1524/// A class which looks for a use of a certain level of template
1525/// parameter.
1526struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1527 typedef RecursiveASTVisitor<DependencyChecker> super;
1528
1529 unsigned Depth;
1530 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001531 SourceLocation MatchLoc;
1532
1533 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001534
1535 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1536 NamedDecl *ND = Params->getParam(0);
1537 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1538 Depth = PD->getDepth();
1539 } else if (NonTypeTemplateParmDecl *PD =
1540 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1541 Depth = PD->getDepth();
1542 } else {
1543 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1544 }
1545 }
1546
Richard Smith6056d5e2014-02-09 00:54:43 +00001547 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001548 if (ParmDepth >= Depth) {
1549 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001550 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001551 return true;
1552 }
1553 return false;
1554 }
1555
Richard Smith6056d5e2014-02-09 00:54:43 +00001556 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1557 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1558 }
1559
John McCalla020a012010-10-20 05:44:58 +00001560 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1561 return !Matches(T->getDepth());
1562 }
1563
1564 bool TraverseTemplateName(TemplateName N) {
1565 if (TemplateTemplateParmDecl *PD =
1566 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001567 if (Matches(PD->getDepth()))
1568 return false;
John McCalla020a012010-10-20 05:44:58 +00001569 return super::TraverseTemplateName(N);
1570 }
1571
1572 bool VisitDeclRefExpr(DeclRefExpr *E) {
1573 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001574 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1575 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001576 return false;
John McCalla020a012010-10-20 05:44:58 +00001577 return super::VisitDeclRefExpr(E);
1578 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001579
1580 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1581 return TraverseType(T->getReplacementType());
1582 }
1583
1584 bool
1585 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1586 return TraverseTemplateArgument(T->getArgumentPack());
1587 }
1588
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001589 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1590 return TraverseType(T->getInjectedSpecializationType());
1591 }
John McCalla020a012010-10-20 05:44:58 +00001592};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001593} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001594
Douglas Gregor972fe532011-05-10 18:27:06 +00001595/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001596/// list.
1597static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001598DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001599 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001600 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001601 return Checker.Match;
1602}
1603
Douglas Gregor972fe532011-05-10 18:27:06 +00001604// Find the source range corresponding to the named type in the given
1605// nested-name-specifier, if any.
1606static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1607 QualType T,
1608 const CXXScopeSpec &SS) {
1609 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1610 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1611 if (const Type *CurType = NNS->getAsType()) {
1612 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1613 return NNSLoc.getTypeLoc().getSourceRange();
1614 } else
1615 break;
1616
1617 NNSLoc = NNSLoc.getPrefix();
1618 }
1619
1620 return SourceRange();
1621}
1622
Mike Stump11289f42009-09-09 15:08:12 +00001623/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001624/// specifier, returning the template parameter list that applies to the
1625/// name.
1626///
1627/// \param DeclStartLoc the start of the declaration that has a scope
1628/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001629///
Douglas Gregor972fe532011-05-10 18:27:06 +00001630/// \param DeclLoc The location of the declaration itself.
1631///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001632/// \param SS the scope specifier that will be matched to the given template
1633/// parameter lists. This scope specifier precedes a qualified name that is
1634/// being declared.
1635///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001636/// \param TemplateId The template-id following the scope specifier, if there
1637/// is one. Used to check for a missing 'template<>'.
1638///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001639/// \param ParamLists the template parameter lists, from the outermost to the
1640/// innermost template parameter lists.
1641///
John McCalle820e5e2010-04-13 20:37:33 +00001642/// \param IsFriend Whether to apply the slightly different rules for
1643/// matching template parameters to scope specifiers in friend
1644/// declarations.
1645///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001646/// \param IsExplicitSpecialization will be set true if the entity being
1647/// declared is an explicit specialization, false otherwise.
1648///
Mike Stump11289f42009-09-09 15:08:12 +00001649/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001650/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001651/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001652/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001653/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001654/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001655TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1656 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001657 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001658 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1659 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001660 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001661 Invalid = false;
1662
1663 // The sequence of nested types to which we will match up the template
1664 // parameter lists. We first build this list by starting with the type named
1665 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001666 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001667 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001668 if (SS.getScopeRep()) {
1669 if (CXXRecordDecl *Record
1670 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1671 T = Context.getTypeDeclType(Record);
1672 else
1673 T = QualType(SS.getScopeRep()->getAsType(), 0);
1674 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001675
1676 // If we found an explicit specialization that prevents us from needing
1677 // 'template<>' headers, this will be set to the location of that
1678 // explicit specialization.
1679 SourceLocation ExplicitSpecLoc;
1680
1681 while (!T.isNull()) {
1682 NestedTypes.push_back(T);
1683
1684 // Retrieve the parent of a record type.
1685 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1686 // If this type is an explicit specialization, we're done.
1687 if (ClassTemplateSpecializationDecl *Spec
1688 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1689 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1690 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1691 ExplicitSpecLoc = Spec->getLocation();
1692 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001693 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001694 } else if (Record->getTemplateSpecializationKind()
1695 == TSK_ExplicitSpecialization) {
1696 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001697 break;
1698 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001699
1700 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1701 T = Context.getTypeDeclType(Parent);
1702 else
1703 T = QualType();
1704 continue;
1705 }
1706
1707 if (const TemplateSpecializationType *TST
1708 = T->getAs<TemplateSpecializationType>()) {
1709 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1710 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1711 T = Context.getTypeDeclType(Parent);
1712 else
1713 T = QualType();
1714 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001715 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001716 }
1717
1718 // Look one step prior in a dependent template specialization type.
1719 if (const DependentTemplateSpecializationType *DependentTST
1720 = T->getAs<DependentTemplateSpecializationType>()) {
1721 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1722 T = QualType(NNS->getAsType(), 0);
1723 else
1724 T = QualType();
1725 continue;
1726 }
1727
1728 // Look one step prior in a dependent name type.
1729 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1730 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1731 T = QualType(NNS->getAsType(), 0);
1732 else
1733 T = QualType();
1734 continue;
1735 }
1736
1737 // Retrieve the parent of an enumeration type.
1738 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1739 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1740 // check here.
1741 EnumDecl *Enum = EnumT->getDecl();
1742
1743 // Get to the parent type.
1744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1745 T = Context.getTypeDeclType(Parent);
1746 else
1747 T = QualType();
1748 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
Douglas Gregor972fe532011-05-10 18:27:06 +00001751 T = QualType();
1752 }
1753 // Reverse the nested types list, since we want to traverse from the outermost
1754 // to the innermost while checking template-parameter-lists.
1755 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001756
Douglas Gregor972fe532011-05-10 18:27:06 +00001757 // C++0x [temp.expl.spec]p17:
1758 // A member or a member template may be nested within many
1759 // enclosing class templates. In an explicit specialization for
1760 // such a member, the member declaration shall be preceded by a
1761 // template<> for each enclosing class template that is
1762 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001763 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001764
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001765 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001766 if (SawNonEmptyTemplateParameterList) {
1767 Diag(DeclLoc, diag::err_specialize_member_of_template)
1768 << !Recovery << Range;
1769 Invalid = true;
1770 IsExplicitSpecialization = false;
1771 return true;
1772 }
1773
1774 return false;
1775 };
1776
1777 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1778 // Check that we can have an explicit specialization here.
1779 if (CheckExplicitSpecialization(Range, true))
1780 return true;
1781
1782 // We don't have a template header, but we should.
1783 SourceLocation ExpectedTemplateLoc;
1784 if (!ParamLists.empty())
1785 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1786 else
1787 ExpectedTemplateLoc = DeclStartLoc;
1788
1789 Diag(DeclLoc, diag::err_template_spec_needs_header)
1790 << Range
1791 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1792 return false;
1793 };
1794
Douglas Gregor972fe532011-05-10 18:27:06 +00001795 unsigned ParamIdx = 0;
1796 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1797 ++TypeIdx) {
1798 T = NestedTypes[TypeIdx];
1799
1800 // Whether we expect a 'template<>' header.
1801 bool NeedEmptyTemplateHeader = false;
1802
1803 // Whether we expect a template header with parameters.
1804 bool NeedNonemptyTemplateHeader = false;
1805
1806 // For a dependent type, the set of template parameters that we
1807 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001808 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001809
Douglas Gregor373af9b2011-05-11 23:26:17 +00001810 // C++0x [temp.expl.spec]p15:
1811 // A member or a member template may be nested within many enclosing
1812 // class templates. In an explicit specialization for such a member, the
1813 // member declaration shall be preceded by a template<> for each
1814 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001815 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1816 if (ClassTemplatePartialSpecializationDecl *Partial
1817 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1818 ExpectedTemplateParams = Partial->getTemplateParameters();
1819 NeedNonemptyTemplateHeader = true;
1820 } else if (Record->isDependentType()) {
1821 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001822 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001823 ->getTemplateParameters();
1824 NeedNonemptyTemplateHeader = true;
1825 }
1826 } else if (ClassTemplateSpecializationDecl *Spec
1827 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1828 // C++0x [temp.expl.spec]p4:
1829 // Members of an explicitly specialized class template are defined
1830 // in the same manner as members of normal classes, and not using
1831 // the template<> syntax.
1832 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1833 NeedEmptyTemplateHeader = true;
1834 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001835 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001836 } else if (Record->getTemplateSpecializationKind()) {
1837 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001838 != TSK_ExplicitSpecialization &&
1839 TypeIdx == NumTypes - 1)
1840 IsExplicitSpecialization = true;
1841
1842 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001843 }
1844 } else if (const TemplateSpecializationType *TST
1845 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001846 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001847 ExpectedTemplateParams = Template->getTemplateParameters();
1848 NeedNonemptyTemplateHeader = true;
1849 }
1850 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1851 // FIXME: We actually could/should check the template arguments here
1852 // against the corresponding template parameter list.
1853 NeedNonemptyTemplateHeader = false;
1854 }
1855
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001856 // C++ [temp.expl.spec]p16:
1857 // In an explicit specialization declaration for a member of a class
1858 // template or a member template that ap- pears in namespace scope, the
1859 // member template and some of its enclosing class templates may remain
1860 // unspecialized, except that the declaration shall not explicitly
1861 // specialize a class member template if its en- closing class templates
1862 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001863 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001864 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001865 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1866 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001867 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001868 } else
1869 SawNonEmptyTemplateParameterList = true;
1870 }
1871
Douglas Gregor972fe532011-05-10 18:27:06 +00001872 if (NeedEmptyTemplateHeader) {
1873 // If we're on the last of the types, and we need a 'template<>' header
1874 // here, then it's an explicit specialization.
1875 if (TypeIdx == NumTypes - 1)
1876 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001877
1878 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001879 if (ParamLists[ParamIdx]->size() > 0) {
1880 // The header has template parameters when it shouldn't. Complain.
1881 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1882 diag::err_template_param_list_matches_nontemplate)
1883 << T
1884 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1885 ParamLists[ParamIdx]->getRAngleLoc())
1886 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1887 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001888 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001889 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001890
Douglas Gregor972fe532011-05-10 18:27:06 +00001891 // Consume this template header.
1892 ++ParamIdx;
1893 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001894 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001895
1896 if (!IsFriend)
1897 if (DiagnoseMissingExplicitSpecialization(
1898 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001899 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001900
Douglas Gregor972fe532011-05-10 18:27:06 +00001901 continue;
1902 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001903
Douglas Gregor972fe532011-05-10 18:27:06 +00001904 if (NeedNonemptyTemplateHeader) {
1905 // In friend declarations we can have template-ids which don't
1906 // depend on the corresponding template parameter lists. But
1907 // assume that empty parameter lists are supposed to match this
1908 // template-id.
1909 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001910 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001911 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001912 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001913 else
1914 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001915 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001916
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001917 if (ParamIdx < ParamLists.size()) {
1918 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001919 if (ExpectedTemplateParams &&
1920 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1921 ExpectedTemplateParams,
1922 true, TPL_TemplateMatch))
1923 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001924
Douglas Gregor972fe532011-05-10 18:27:06 +00001925 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001926 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001927 TPC_ClassTemplateMember))
1928 Invalid = true;
1929
1930 ++ParamIdx;
1931 continue;
1932 }
1933
1934 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1935 << T
1936 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1937 Invalid = true;
1938 continue;
1939 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001940 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001941
Douglas Gregord8d297c2009-07-21 23:53:31 +00001942 // If there were at least as many template-ids as there were template
1943 // parameter lists, then there are no template parameter lists remaining for
1944 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001945 if (ParamIdx >= ParamLists.size()) {
1946 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001947 // We don't have a template header for the declaration itself, but we
1948 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001949 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001950 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1951 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001952
1953 // Fabricate an empty template parameter list for the invented header.
1954 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00001955 SourceLocation(), None,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001956 SourceLocation());
1957 }
1958
Craig Topperc3ec1492014-05-26 06:22:03 +00001959 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Douglas Gregord8d297c2009-07-21 23:53:31 +00001962 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001963 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001964 bool HasAnyExplicitSpecHeader = false;
1965 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001966 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001967 if (ParamLists[I]->size() == 0)
1968 HasAnyExplicitSpecHeader = true;
1969 else
1970 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001971 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001972
Douglas Gregor972fe532011-05-10 18:27:06 +00001973 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001974 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1975 : diag::err_template_spec_extra_headers)
1976 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1977 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001978
1979 // If there was a specialization somewhere, such that 'template<>' is
1980 // not required, and there were any 'template<>' headers, note where the
1981 // specialization occurred.
1982 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1983 Diag(ExplicitSpecLoc,
1984 diag::note_explicit_template_spec_does_not_need_header)
1985 << NestedTypes.back();
1986
1987 // We have a template parameter list with no corresponding scope, which
1988 // means that the resulting template declaration can't be instantiated
1989 // properly (we'll end up with dependent nodes when we shouldn't).
1990 if (!AllExplicitSpecHeaders)
1991 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001992 }
Mike Stump11289f42009-09-09 15:08:12 +00001993
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001994 // C++ [temp.expl.spec]p16:
1995 // In an explicit specialization declaration for a member of a class
1996 // template or a member template that ap- pears in namespace scope, the
1997 // member template and some of its enclosing class templates may remain
1998 // unspecialized, except that the declaration shall not explicitly
1999 // specialize a class member template if its en- closing class templates
2000 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002001 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002002 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2003 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002004 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002005
Douglas Gregord8d297c2009-07-21 23:53:31 +00002006 // Return the last template parameter list, which corresponds to the
2007 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002008 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002009}
2010
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002011void Sema::NoteAllFoundTemplates(TemplateName Name) {
2012 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2013 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002014 << (isa<FunctionTemplateDecl>(Template)
2015 ? 0
2016 : isa<ClassTemplateDecl>(Template)
2017 ? 1
2018 : isa<VarTemplateDecl>(Template)
2019 ? 2
2020 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2021 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002022 return;
2023 }
2024
2025 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2026 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2027 IEnd = OST->end();
2028 I != IEnd; ++I)
2029 Diag((*I)->getLocation(), diag::note_template_declared_here)
2030 << 0 << (*I)->getDeclName();
2031
2032 return;
2033 }
2034}
2035
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002036static QualType
2037checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2038 const SmallVectorImpl<TemplateArgument> &Converted,
2039 SourceLocation TemplateLoc,
2040 TemplateArgumentListInfo &TemplateArgs) {
2041 ASTContext &Context = SemaRef.getASTContext();
2042 switch (BTD->getBuiltinTemplateKind()) {
2043 case BTK__make_integer_seq:
2044 // Specializations of __make_integer_seq<S, T, N> are treated like
2045 // S<T, 0, ..., N-1>.
2046
2047 // C++14 [inteseq.intseq]p1:
2048 // T shall be an integer type.
2049 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2050 SemaRef.Diag(TemplateArgs[1].getLocation(),
2051 diag::err_integer_sequence_integral_element_type);
2052 return QualType();
2053 }
2054
2055 // C++14 [inteseq.make]p1:
2056 // If N is negative the program is ill-formed.
2057 TemplateArgument NumArgsArg = Converted[2];
2058 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2059 if (NumArgs < 0) {
2060 SemaRef.Diag(TemplateArgs[2].getLocation(),
2061 diag::err_integer_sequence_negative_length);
2062 return QualType();
2063 }
2064
2065 QualType ArgTy = NumArgsArg.getIntegralType();
2066 TemplateArgumentListInfo SyntheticTemplateArgs;
2067 // The type argument gets reused as the first template argument in the
2068 // synthetic template argument list.
2069 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2070 // Expand N into 0 ... N-1.
2071 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2072 I < NumArgs; ++I) {
2073 TemplateArgument TA(Context, I, ArgTy);
2074 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2075 TA, TemplateArgs[2].getLocation())
2076 .getAs<Expr>();
2077 SyntheticTemplateArgs.addArgument(
2078 TemplateArgumentLoc(TemplateArgument(E), E));
2079 }
2080 // The first template argument will be reused as the template decl that
2081 // our synthetic template arguments will be applied to.
2082 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2083 TemplateLoc, SyntheticTemplateArgs);
2084 }
2085 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2086}
2087
Douglas Gregordc572a32009-03-30 22:58:21 +00002088QualType Sema::CheckTemplateIdType(TemplateName Name,
2089 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002090 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002091 DependentTemplateName *DTN
2092 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002093 if (DTN && DTN->isIdentifier())
2094 // When building a template-id where the template-name is dependent,
2095 // assume the template is a type template. Either our assumption is
2096 // correct, or the code is ill-formed and will be diagnosed when the
2097 // dependent name is substituted.
2098 return Context.getDependentTemplateSpecializationType(ETK_None,
2099 DTN->getQualifier(),
2100 DTN->getIdentifier(),
2101 TemplateArgs);
2102
Douglas Gregordc572a32009-03-30 22:58:21 +00002103 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002104 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2105 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002106 // We might have a substituted template template parameter pack. If so,
2107 // build a template specialization type for it.
2108 if (Name.getAsSubstTemplateTemplateParmPack())
2109 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002110
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002111 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2112 << Name;
2113 NoteAllFoundTemplates(Name);
2114 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002115 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002116
Douglas Gregorc40290e2009-03-09 23:48:35 +00002117 // Check that the template argument list is well-formed for this
2118 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002119 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002120 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002121 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002122 return QualType();
2123
Douglas Gregorc40290e2009-03-09 23:48:35 +00002124 QualType CanonType;
2125
Douglas Gregor678d76c2011-07-01 01:22:09 +00002126 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002127 if (TypeAliasTemplateDecl *AliasTemplate =
2128 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002129 // Find the canonical type for this type alias template specialization.
2130 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2131 if (Pattern->isInvalidDecl())
2132 return QualType();
2133
2134 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2135 Converted.data(), Converted.size());
2136
2137 // Only substitute for the innermost template argument list.
2138 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002139 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002140 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2141 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002142 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002143
Richard Smith802c4b72012-08-23 06:16:52 +00002144 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002145 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002146 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002147 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002148
Richard Smith3f1b5d02011-05-05 21:57:07 +00002149 CanonType = SubstType(Pattern->getUnderlyingType(),
2150 TemplateArgLists, AliasTemplate->getLocation(),
2151 AliasTemplate->getDeclName());
2152 if (CanonType.isNull())
2153 return QualType();
2154 } else if (Name.isDependent() ||
2155 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002156 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002157 // This class template specialization is a dependent
2158 // type. Therefore, its canonical type is another class template
2159 // specialization type that contains all of the converted
2160 // arguments in canonical form. This ensures that, e.g., A<T> and
2161 // A<T, T> have identical types when A is declared as:
2162 //
2163 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002164 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002165 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002166 Converted.data(),
2167 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002168
Douglas Gregora8e02e72009-07-28 23:00:59 +00002169 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002170 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002171 // In the future, we need to teach getTemplateSpecializationType to only
2172 // build the canonical type and return that to us.
2173 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002174
2175 // This might work out to be a current instantiation, in which
2176 // case the canonical type needs to be the InjectedClassNameType.
2177 //
2178 // TODO: in theory this could be a simple hashtable lookup; most
2179 // changes to CurContext don't change the set of current
2180 // instantiations.
2181 if (isa<ClassTemplateDecl>(Template)) {
2182 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2183 // If we get out to a namespace, we're done.
2184 if (Ctx->isFileContext()) break;
2185
2186 // If this isn't a record, keep looking.
2187 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2188 if (!Record) continue;
2189
2190 // Look for one of the two cases with InjectedClassNameTypes
2191 // and check whether it's the same template.
2192 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2193 !Record->getDescribedClassTemplate())
2194 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002195
John McCall2408e322010-04-27 00:57:59 +00002196 // Fetch the injected class name type and check whether its
2197 // injected type is equal to the type we just built.
2198 QualType ICNT = Context.getTypeDeclType(Record);
2199 QualType Injected = cast<InjectedClassNameType>(ICNT)
2200 ->getInjectedSpecializationType();
2201
2202 if (CanonType != Injected->getCanonicalTypeInternal())
2203 continue;
2204
2205 // If so, the canonical type of this TST is the injected
2206 // class name type of the record we just found.
2207 assert(ICNT.isCanonical());
2208 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002209 break;
2210 }
2211 }
Mike Stump11289f42009-09-09 15:08:12 +00002212 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002213 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002214 // Find the class template specialization declaration that
2215 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002216 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002217 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002218 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002219 if (!Decl) {
2220 // This is the first time we have referenced this class template
2221 // specialization. Create the canonical declaration and add it to
2222 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002223 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002224 ClassTemplate->getTemplatedDecl()->getTagKind(),
2225 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002226 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002227 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002228 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002229 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002230 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002231 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002232 if (ClassTemplate->isOutOfLine())
2233 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002234 }
2235
Chandler Carruth2acfb222013-09-27 22:14:40 +00002236 // Diagnose uses of this specialization.
2237 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2238
Douglas Gregorc40290e2009-03-09 23:48:35 +00002239 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002240 assert(isa<RecordType>(CanonType) &&
2241 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002242 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2243 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2244 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002245 }
Mike Stump11289f42009-09-09 15:08:12 +00002246
Douglas Gregorc40290e2009-03-09 23:48:35 +00002247 // Build the fully-sugared type for this class template
2248 // specialization, which refers back to the class template
2249 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002250 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002251}
2252
John McCallfaf5fb42010-08-26 23:41:50 +00002253TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002254Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002255 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002256 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002257 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002258 SourceLocation RAngleLoc,
2259 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002260 if (SS.isInvalid())
2261 return true;
2262
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002263 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002264
Douglas Gregorc40290e2009-03-09 23:48:35 +00002265 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002266 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002267 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002268
Douglas Gregor5a064722011-02-28 17:23:35 +00002269 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002270 QualType T
2271 = Context.getDependentTemplateSpecializationType(ETK_None,
2272 DTN->getQualifier(),
2273 DTN->getIdentifier(),
2274 TemplateArgs);
2275 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002276 TypeLocBuilder TLB;
2277 DependentTemplateSpecializationTypeLoc SpecTL
2278 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002279 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2280 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002281 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002282 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002283 SpecTL.setLAngleLoc(LAngleLoc);
2284 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002285 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2286 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2287 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2288 }
2289
John McCall6b51f282009-11-23 01:53:49 +00002290 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002291
2292 if (Result.isNull())
2293 return true;
2294
Douglas Gregore7c20652011-03-02 00:47:37 +00002295 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002296 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002297 TemplateSpecializationTypeLoc SpecTL
2298 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002299 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002300 SpecTL.setTemplateNameLoc(TemplateLoc);
2301 SpecTL.setLAngleLoc(LAngleLoc);
2302 SpecTL.setRAngleLoc(RAngleLoc);
2303 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2304 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002305
Abramo Bagnara4244b432012-01-27 08:46:19 +00002306 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2307 // constructor or destructor name (in such a case, the scope specifier
2308 // will be attached to the enclosing Decl or Expr node).
2309 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002310 // Create an elaborated-type-specifier containing the nested-name-specifier.
2311 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2312 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002313 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002314 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2315 }
2316
2317 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002318}
John McCall06f6fe8d2009-09-04 01:14:41 +00002319
Douglas Gregore7c20652011-03-02 00:47:37 +00002320TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002321 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002322 SourceLocation TagLoc,
2323 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002324 SourceLocation TemplateKWLoc,
2325 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002326 SourceLocation TemplateLoc,
2327 SourceLocation LAngleLoc,
2328 ASTTemplateArgsPtr TemplateArgsIn,
2329 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002330 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002331
2332 // Translate the parser's template argument list in our AST format.
2333 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2334 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2335
2336 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002337 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002338 ElaboratedTypeKeyword Keyword
2339 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002340
Douglas Gregore7c20652011-03-02 00:47:37 +00002341 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2342 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2343 DTN->getQualifier(),
2344 DTN->getIdentifier(),
2345 TemplateArgs);
2346
2347 // Build type-source information.
2348 TypeLocBuilder TLB;
2349 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002350 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2351 SpecTL.setElaboratedKeywordLoc(TagLoc);
2352 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002353 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002354 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002355 SpecTL.setLAngleLoc(LAngleLoc);
2356 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002357 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2358 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2359 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2360 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002361
2362 if (TypeAliasTemplateDecl *TAT =
2363 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2364 // C++0x [dcl.type.elab]p2:
2365 // If the identifier resolves to a typedef-name or the simple-template-id
2366 // resolves to an alias template specialization, the
2367 // elaborated-type-specifier is ill-formed.
2368 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2369 Diag(TAT->getLocation(), diag::note_declared_at);
2370 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002371
2372 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2373 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002374 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002375
2376 // Check the tag kind
2377 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002378 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002379
John McCalld8fe9af2009-09-08 17:47:29 +00002380 IdentifierInfo *Id = D->getIdentifier();
2381 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002382
Richard Trieucaa33d32011-06-10 03:11:26 +00002383 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002384 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002385 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002386 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002387 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002388 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002389 }
2390 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002391
Douglas Gregore7c20652011-03-02 00:47:37 +00002392 // Provide source-location information for the template specialization.
2393 TypeLocBuilder TLB;
2394 TemplateSpecializationTypeLoc SpecTL
2395 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002396 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002397 SpecTL.setTemplateNameLoc(TemplateLoc);
2398 SpecTL.setLAngleLoc(LAngleLoc);
2399 SpecTL.setRAngleLoc(RAngleLoc);
2400 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2401 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002402
Douglas Gregore7c20652011-03-02 00:47:37 +00002403 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002404 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002405 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2406 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002407 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002408 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2409 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002410}
2411
Larisse Voufo39a1e502013-08-06 01:03:05 +00002412static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002413 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2414 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002415
2416static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2417 NamedDecl *PrevDecl,
2418 SourceLocation Loc,
2419 bool IsPartialSpecialization);
2420
2421static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002422
Richard Smith300e0c32013-09-24 04:49:23 +00002423static bool isTemplateArgumentTemplateParameter(
2424 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2425 switch (Arg.getKind()) {
2426 case TemplateArgument::Null:
2427 case TemplateArgument::NullPtr:
2428 case TemplateArgument::Integral:
2429 case TemplateArgument::Declaration:
2430 case TemplateArgument::Pack:
2431 case TemplateArgument::TemplateExpansion:
2432 return false;
2433
2434 case TemplateArgument::Type: {
2435 QualType Type = Arg.getAsType();
2436 const TemplateTypeParmType *TPT =
2437 Arg.getAsType()->getAs<TemplateTypeParmType>();
2438 return TPT && !Type.hasQualifiers() &&
2439 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2440 }
2441
2442 case TemplateArgument::Expression: {
2443 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2444 if (!DRE || !DRE->getDecl())
2445 return false;
2446 const NonTypeTemplateParmDecl *NTTP =
2447 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2448 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2449 }
2450
2451 case TemplateArgument::Template:
2452 const TemplateTemplateParmDecl *TTP =
2453 dyn_cast_or_null<TemplateTemplateParmDecl>(
2454 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2455 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2456 }
2457 llvm_unreachable("unexpected kind of template argument");
2458}
2459
2460static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2461 ArrayRef<TemplateArgument> Args) {
2462 if (Params->size() != Args.size())
2463 return false;
2464
2465 unsigned Depth = Params->getDepth();
2466
2467 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2468 TemplateArgument Arg = Args[I];
2469
2470 // If the parameter is a pack expansion, the argument must be a pack
2471 // whose only element is a pack expansion.
2472 if (Params->getParam(I)->isParameterPack()) {
2473 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2474 !Arg.pack_begin()->isPackExpansion())
2475 return false;
2476 Arg = Arg.pack_begin()->getPackExpansionPattern();
2477 }
2478
2479 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2480 return false;
2481 }
2482
2483 return true;
2484}
2485
Richard Smith4b55a9c2014-04-17 03:29:33 +00002486/// Convert the parser's template argument list representation into our form.
2487static TemplateArgumentListInfo
2488makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2489 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2490 TemplateId.RAngleLoc);
2491 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2492 TemplateId.NumArgs);
2493 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2494 return TemplateArgs;
2495}
2496
Larisse Voufo39a1e502013-08-06 01:03:05 +00002497DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002498 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002499 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002500 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002501 // D must be variable template id.
2502 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2503 "Variable template specialization is declared with a template it.");
2504
2505 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002506 TemplateArgumentListInfo TemplateArgs =
2507 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002508 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2509 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2510 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002511
Richard Smithbeef3452014-01-16 23:39:20 +00002512 TemplateName Name = TemplateId->Template.get();
2513
2514 // The template-id must name a variable template.
2515 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002516 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2517 if (!VarTemplate) {
2518 NamedDecl *FnTemplate;
2519 if (auto *OTS = Name.getAsOverloadedTemplate())
2520 FnTemplate = *OTS->begin();
2521 else
2522 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2523 if (FnTemplate)
2524 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2525 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002526 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2527 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002528 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002529
2530 // Check for unexpanded parameter packs in any of the template arguments.
2531 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2532 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2533 UPPC_PartialSpecialization))
2534 return true;
2535
2536 // Check that the template argument list is well-formed for this
2537 // template.
2538 SmallVector<TemplateArgument, 4> Converted;
2539 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2540 false, Converted))
2541 return true;
2542
Larisse Voufo39a1e502013-08-06 01:03:05 +00002543 // Find the variable template (partial) specialization declaration that
2544 // corresponds to these arguments.
2545 if (IsPartialSpecialization) {
2546 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002547 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2548 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002549 return true;
2550
2551 bool InstantiationDependent;
2552 if (!Name.isDependent() &&
2553 !TemplateSpecializationType::anyDependentTemplateArguments(
2554 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2555 InstantiationDependent)) {
2556 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2557 << VarTemplate->getDeclName();
2558 IsPartialSpecialization = false;
2559 }
Richard Smith300e0c32013-09-24 04:49:23 +00002560
2561 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2562 Converted)) {
2563 // C++ [temp.class.spec]p9b3:
2564 //
2565 // -- The argument list of the specialization shall not be identical
2566 // to the implicit argument list of the primary template.
2567 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2568 << /*variable template*/ 1
2569 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2570 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2571 // FIXME: Recover from this by treating the declaration as a redeclaration
2572 // of the primary template.
2573 return true;
2574 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002575 }
2576
Craig Topperc3ec1492014-05-26 06:22:03 +00002577 void *InsertPos = nullptr;
2578 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002579
2580 if (IsPartialSpecialization)
2581 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002582 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002583 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002584 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002585
Craig Topperc3ec1492014-05-26 06:22:03 +00002586 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002587
2588 // Check whether we can declare a variable template specialization in
2589 // the current scope.
2590 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2591 TemplateNameLoc,
2592 IsPartialSpecialization))
2593 return true;
2594
2595 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2596 // Since the only prior variable template specialization with these
2597 // arguments was referenced but not declared, reuse that
2598 // declaration node as our own, updating its source location and
2599 // the list of outer template parameters to reflect our new declaration.
2600 Specialization = PrevDecl;
2601 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002602 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002603 } else if (IsPartialSpecialization) {
2604 // Create a new class template partial specialization declaration node.
2605 VarTemplatePartialSpecializationDecl *PrevPartial =
2606 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002607 VarTemplatePartialSpecializationDecl *Partial =
2608 VarTemplatePartialSpecializationDecl::Create(
2609 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2610 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002611 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002612
2613 if (!PrevPartial)
2614 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2615 Specialization = Partial;
2616
2617 // If we are providing an explicit specialization of a member variable
2618 // template specialization, make a note of that.
2619 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002620 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002621
2622 // Check that all of the template parameters of the variable template
2623 // partial specialization are deducible from the template
2624 // arguments. If not, this variable template partial specialization
2625 // will never be used.
2626 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2627 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2628 TemplateParams->getDepth(), DeducibleParams);
2629
2630 if (!DeducibleParams.all()) {
2631 unsigned NumNonDeducible =
2632 DeducibleParams.size() - DeducibleParams.count();
2633 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002634 << /*variable template*/ 1 << (NumNonDeducible > 1)
2635 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002636 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2637 if (!DeducibleParams[I]) {
2638 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2639 if (Param->getDeclName())
2640 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2641 << Param->getDeclName();
2642 else
2643 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002644 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002645 }
2646 }
2647 }
2648 } else {
2649 // Create a new class template specialization declaration node for
2650 // this explicit specialization or friend declaration.
2651 Specialization = VarTemplateSpecializationDecl::Create(
2652 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2653 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2654 Specialization->setTemplateArgsInfo(TemplateArgs);
2655
2656 if (!PrevDecl)
2657 VarTemplate->AddSpecialization(Specialization, InsertPos);
2658 }
2659
2660 // C++ [temp.expl.spec]p6:
2661 // If a template, a member template or the member of a class template is
2662 // explicitly specialized then that specialization shall be declared
2663 // before the first use of that specialization that would cause an implicit
2664 // instantiation to take place, in every translation unit in which such a
2665 // use occurs; no diagnostic is required.
2666 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2667 bool Okay = false;
2668 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2669 // Is there any previous explicit specialization declaration?
2670 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2671 Okay = true;
2672 break;
2673 }
2674 }
2675
2676 if (!Okay) {
2677 SourceRange Range(TemplateNameLoc, RAngleLoc);
2678 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2679 << Name << Range;
2680
2681 Diag(PrevDecl->getPointOfInstantiation(),
2682 diag::note_instantiation_required_here)
2683 << (PrevDecl->getTemplateSpecializationKind() !=
2684 TSK_ImplicitInstantiation);
2685 return true;
2686 }
2687 }
2688
2689 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2690 Specialization->setLexicalDeclContext(CurContext);
2691
2692 // Add the specialization into its lexical context, so that it can
2693 // be seen when iterating through the list of declarations in that
2694 // context. However, specializations are not found by name lookup.
2695 CurContext->addDecl(Specialization);
2696
2697 // Note that this is an explicit specialization.
2698 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2699
2700 if (PrevDecl) {
2701 // Check that this isn't a redefinition of this specialization,
2702 // merging with previous declarations.
2703 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2704 ForRedeclaration);
2705 PrevSpec.addDecl(PrevDecl);
2706 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002707 } else if (Specialization->isStaticDataMember() &&
2708 Specialization->isOutOfLine()) {
2709 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002710 }
2711
2712 // Link instantiations of static data members back to the template from
2713 // which they were instantiated.
2714 if (Specialization->isStaticDataMember())
2715 Specialization->setInstantiationOfStaticDataMember(
2716 VarTemplate->getTemplatedDecl(),
2717 Specialization->getSpecializationKind());
2718
2719 return Specialization;
2720}
2721
2722namespace {
2723/// \brief A partial specialization whose template arguments have matched
2724/// a given template-id.
2725struct PartialSpecMatchResult {
2726 VarTemplatePartialSpecializationDecl *Partial;
2727 TemplateArgumentList *Args;
2728};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002729} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002730
2731DeclResult
2732Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2733 SourceLocation TemplateNameLoc,
2734 const TemplateArgumentListInfo &TemplateArgs) {
2735 assert(Template && "A variable template id without template?");
2736
2737 // Check that the template argument list is well-formed for this template.
2738 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002739 if (CheckTemplateArgumentList(
2740 Template, TemplateNameLoc,
2741 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002742 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002743 return true;
2744
2745 // Find the variable template specialization declaration that
2746 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002747 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002748 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002749 Converted, InsertPos)) {
2750 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002751 // If we already have a variable template specialization, return it.
2752 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002753 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002754
2755 // This is the first time we have referenced this variable template
2756 // specialization. Create the canonical declaration and add it to
2757 // the set of specializations, based on the closest partial specialization
2758 // that it represents. That is,
2759 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2760 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2761 Converted.data(), Converted.size());
2762 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2763 bool AmbiguousPartialSpec = false;
2764 typedef PartialSpecMatchResult MatchResult;
2765 SmallVector<MatchResult, 4> Matched;
2766 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002767 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2768 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002769
2770 // 1. Attempt to find the closest partial specialization that this
2771 // specializes, if any.
2772 // If any of the template arguments is dependent, then this is probably
2773 // a placeholder for an incomplete declarative context; which must be
2774 // complete by instantiation time. Thus, do not search through the partial
2775 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002776 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2777 // Perhaps better after unification of DeduceTemplateArguments() and
2778 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002779 bool InstantiationDependent = false;
2780 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2781 TemplateArgs, InstantiationDependent)) {
2782
2783 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2784 Template->getPartialSpecializations(PartialSpecs);
2785
2786 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2787 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2788 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2789
2790 if (TemplateDeductionResult Result =
2791 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2792 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002793 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002794 FailedCandidates.addCandidate().set(
2795 DeclAccessPair::make(Template, AS_public), Partial,
2796 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002797 (void)Result;
2798 } else {
2799 Matched.push_back(PartialSpecMatchResult());
2800 Matched.back().Partial = Partial;
2801 Matched.back().Args = Info.take();
2802 }
2803 }
2804
Larisse Voufo39a1e502013-08-06 01:03:05 +00002805 if (Matched.size() >= 1) {
2806 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2807 if (Matched.size() == 1) {
2808 // -- If exactly one matching specialization is found, the
2809 // instantiation is generated from that specialization.
2810 // We don't need to do anything for this.
2811 } else {
2812 // -- If more than one matching specialization is found, the
2813 // partial order rules (14.5.4.2) are used to determine
2814 // whether one of the specializations is more specialized
2815 // than the others. If none of the specializations is more
2816 // specialized than all of the other matching
2817 // specializations, then the use of the variable template is
2818 // ambiguous and the program is ill-formed.
2819 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2820 PEnd = Matched.end();
2821 P != PEnd; ++P) {
2822 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2823 PointOfInstantiation) ==
2824 P->Partial)
2825 Best = P;
2826 }
2827
2828 // Determine if the best partial specialization is more specialized than
2829 // the others.
2830 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2831 PEnd = Matched.end();
2832 P != PEnd; ++P) {
2833 if (P != Best && getMoreSpecializedPartialSpecialization(
2834 P->Partial, Best->Partial,
2835 PointOfInstantiation) != Best->Partial) {
2836 AmbiguousPartialSpec = true;
2837 break;
2838 }
2839 }
2840 }
2841
2842 // Instantiate using the best variable template partial specialization.
2843 InstantiationPattern = Best->Partial;
2844 InstantiationArgs = Best->Args;
2845 } else {
2846 // -- If no match is found, the instantiation is generated
2847 // from the primary template.
2848 // InstantiationPattern = Template->getTemplatedDecl();
2849 }
2850 }
2851
Larisse Voufo39a1e502013-08-06 01:03:05 +00002852 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00002853 // Note that we do not instantiate a definition until we see an odr-use
2854 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002855 // FIXME: LateAttrs et al.?
2856 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2857 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2858 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2859 if (!Decl)
2860 return true;
2861
2862 if (AmbiguousPartialSpec) {
2863 // Partial ordering did not produce a clear winner. Complain.
2864 Decl->setInvalidDecl();
2865 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2866 << Decl;
2867
2868 // Print the matching partial specializations.
2869 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2870 PEnd = Matched.end();
2871 P != PEnd; ++P)
2872 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2873 << getTemplateArgumentBindingsText(
2874 P->Partial->getTemplateParameters(), *P->Args);
2875 return true;
2876 }
2877
2878 if (VarTemplatePartialSpecializationDecl *D =
2879 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2880 Decl->setInstantiationOf(D, InstantiationArgs);
2881
Richard Smith6739a102016-05-05 00:56:12 +00002882 checkSpecializationVisibility(TemplateNameLoc, Decl);
2883
Larisse Voufo39a1e502013-08-06 01:03:05 +00002884 assert(Decl && "No variable template specialization?");
2885 return Decl;
2886}
2887
2888ExprResult
2889Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2890 const DeclarationNameInfo &NameInfo,
2891 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2892 const TemplateArgumentListInfo *TemplateArgs) {
2893
2894 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2895 *TemplateArgs);
2896 if (Decl.isInvalid())
2897 return ExprError();
2898
2899 VarDecl *Var = cast<VarDecl>(Decl.get());
2900 if (!Var->getTemplateSpecializationKind())
2901 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2902 NameInfo.getLoc());
2903
2904 // Build an ordinary singleton decl ref.
2905 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002906 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002907}
2908
John McCalldadc5752010-08-24 06:29:42 +00002909ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002910 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002911 LookupResult &R,
2912 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002913 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002914 // FIXME: Can we do any checking at this point? I guess we could check the
2915 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002916 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002917 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002918 // foo<int> could identify a single function unambiguously
2919 // This approach does NOT work, since f<int>(1);
2920 // gets resolved prior to resorting to overload resolution
2921 // i.e., template<class T> void f(double);
2922 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002923
2924 // These should be filtered out by our callers.
2925 assert(!R.empty() && "empty lookup results when building templateid");
2926 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2927
Larisse Voufo39a1e502013-08-06 01:03:05 +00002928 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002929 bool InstantiationDependent;
2930 if (R.getAsSingle<VarTemplateDecl>() &&
2931 !TemplateSpecializationType::anyDependentTemplateArguments(
2932 *TemplateArgs, InstantiationDependent)) {
2933 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2934 R.getAsSingle<VarTemplateDecl>(),
2935 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002936 }
2937
John McCall58cc69d2010-01-27 01:50:18 +00002938 // We don't want lookup warnings at this point.
2939 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940
John McCalle66edc12009-11-24 19:00:30 +00002941 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002942 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002943 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002944 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002945 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002946 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002947 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002948
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002949 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002950}
2951
John McCalle66edc12009-11-24 19:00:30 +00002952// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002953ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002954Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002955 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002956 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002957 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002958
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002959 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002960 DeclContext *DC;
2961 if (!(DC = computeDeclContext(SS, false)) ||
2962 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002963 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002964 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002965
Douglas Gregor786123d2010-05-21 23:18:07 +00002966 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002967 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002968 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002969 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002970
John McCalle66edc12009-11-24 19:00:30 +00002971 if (R.isAmbiguous())
2972 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002973
John McCalle66edc12009-11-24 19:00:30 +00002974 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002975 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2976 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002977 return ExprError();
2978 }
2979
2980 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002981 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002982 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002983 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002984 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2985 return ExprError();
2986 }
2987
Abramo Bagnara7945c982012-01-27 09:46:47 +00002988 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002989}
2990
Douglas Gregorb67535d2009-03-31 00:43:58 +00002991/// \brief Form a dependent template name.
2992///
2993/// This action forms a dependent template name given the template
2994/// name and its (presumably dependent) scope specifier. For
2995/// example, given "MetaFun::template apply", the scope specifier \p
2996/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2997/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002999 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003000 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003001 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003002 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003003 bool EnteringContext,
3004 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003005 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3006 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003007 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003008 diag::warn_cxx98_compat_template_outside_of_template :
3009 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003010 << FixItHint::CreateRemoval(TemplateKWLoc);
3011
Craig Topperc3ec1492014-05-26 06:22:03 +00003012 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003013 if (SS.isSet())
3014 LookupCtx = computeDeclContext(SS, EnteringContext);
3015 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003016 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003017 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003018 // C++0x [temp.names]p5:
3019 // If a name prefixed by the keyword template is not the name of
3020 // a template, the program is ill-formed. [Note: the keyword
3021 // template may not be applied to non-template members of class
3022 // templates. -end note ] [ Note: as is the case with the
3023 // typename prefix, the template prefix is allowed in cases
3024 // where it is not strictly necessary; i.e., when the
3025 // nested-name-specifier or the expression on the left of the ->
3026 // or . is not dependent on a template-parameter, or the use
3027 // does not appear in the scope of a template. -end note]
3028 //
3029 // Note: C++03 was more strict here, because it banned the use of
3030 // the "template" keyword prior to a template-name that was not a
3031 // dependent name. C++ DR468 relaxed this requirement (the
3032 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003033 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003034 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003035 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003036 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003037 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003038 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3039 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003040 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3041 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003042 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003043 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003044 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003045 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003046 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003047 << Name.getSourceRange()
3048 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003049 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003050 } else {
3051 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003052 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003053 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003054 }
3055
Aaron Ballman4a979672014-01-03 13:56:08 +00003056 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057
Douglas Gregor3cf81312009-11-03 23:16:33 +00003058 switch (Name.getKind()) {
3059 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003061 Name.Identifier));
3062 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003063
Douglas Gregor71395fa2009-11-04 00:56:37 +00003064 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003065 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003066 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003067 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003068
3069 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003070 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003071
Douglas Gregor3cf81312009-11-03 23:16:33 +00003072 default:
3073 break;
3074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003075
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003076 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003077 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003078 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003079 << Name.getSourceRange()
3080 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003081 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003082}
3083
Mike Stump11289f42009-09-09 15:08:12 +00003084bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003085 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003086 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003087 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003088 QualType ArgType;
3089 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003090
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003091 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003092 switch(Arg.getKind()) {
3093 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003094 // C++ [temp.arg.type]p1:
3095 // A template-argument for a template-parameter which is a
3096 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003097 ArgType = Arg.getAsType();
3098 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003099 break;
3100 case TemplateArgument::Template: {
3101 // We have a template type parameter but the template argument
3102 // is a template without any arguments.
3103 SourceRange SR = AL.getSourceRange();
3104 TemplateName Name = Arg.getAsTemplate();
3105 Diag(SR.getBegin(), diag::err_template_missing_args)
3106 << Name << SR;
3107 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3108 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003109
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003110 return true;
3111 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003112 case TemplateArgument::Expression: {
3113 // We have a template type parameter but the template argument is an
3114 // expression; see if maybe it is missing the "typename" keyword.
3115 CXXScopeSpec SS;
3116 DeclarationNameInfo NameInfo;
3117
3118 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3119 SS.Adopt(ArgExpr->getQualifierLoc());
3120 NameInfo = ArgExpr->getNameInfo();
3121 } else if (DependentScopeDeclRefExpr *ArgExpr =
3122 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3123 SS.Adopt(ArgExpr->getQualifierLoc());
3124 NameInfo = ArgExpr->getNameInfo();
3125 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3126 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003127 if (ArgExpr->isImplicitAccess()) {
3128 SS.Adopt(ArgExpr->getQualifierLoc());
3129 NameInfo = ArgExpr->getMemberNameInfo();
3130 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003131 }
3132
Reid Kleckner377c1592014-06-10 23:29:48 +00003133 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003134 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3135 LookupParsedName(Result, CurScope, &SS);
3136
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003137 if (Result.getAsSingle<TypeDecl>() ||
3138 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003139 LookupResult::NotFoundInCurrentInstantiation) {
3140 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003141 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003142 Diag(Loc, getLangOpts().MSVCCompat
3143 ? diag::ext_ms_template_type_arg_missing_typename
3144 : diag::err_template_arg_must_be_type_suggest)
3145 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003146 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003147
3148 // Recover by synthesizing a type using the location information that we
3149 // already have.
3150 ArgType =
3151 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3152 TypeLocBuilder TLB;
3153 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3154 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3155 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3156 TL.setNameLoc(NameInfo.getLoc());
3157 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3158
3159 // Overwrite our input TemplateArgumentLoc so that we can recover
3160 // properly.
3161 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3162 TemplateArgumentLocInfo(TSI));
3163
3164 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003165 }
3166 }
3167 // fallthrough
3168 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003169 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003170 // We have a template type parameter but the template argument
3171 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003172 SourceRange SR = AL.getSourceRange();
3173 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003174 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003175
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003176 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003177 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003178 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003179
Reid Kleckner377c1592014-06-10 23:29:48 +00003180 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003181 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003182
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003183 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003184 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003185
3186 // Objective-C ARC:
3187 // If an explicitly-specified template argument type is a lifetime type
3188 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003189 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003190 ArgType->isObjCLifetimeType() &&
3191 !ArgType.getObjCLifetime()) {
3192 Qualifiers Qs;
3193 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3194 ArgType = Context.getQualifiedType(ArgType, Qs);
3195 }
3196
3197 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003198 return false;
3199}
3200
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003201/// \brief Substitute template arguments into the default template argument for
3202/// the given template type parameter.
3203///
3204/// \param SemaRef the semantic analysis object for which we are performing
3205/// the substitution.
3206///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003208/// for.
3209///
3210/// \param TemplateLoc the location of the template name that started the
3211/// template-id we are checking.
3212///
3213/// \param RAngleLoc the location of the right angle bracket ('>') that
3214/// terminates the template-id.
3215///
3216/// \param Param the template template parameter whose default we are
3217/// substituting into.
3218///
3219/// \param Converted the list of template arguments provided for template
3220/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003221/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003222static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003223SubstDefaultTemplateArgument(Sema &SemaRef,
3224 TemplateDecl *Template,
3225 SourceLocation TemplateLoc,
3226 SourceLocation RAngleLoc,
3227 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003228 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003229 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003230
3231 // If the argument type is dependent, instantiate it now based
3232 // on the previously-computed template arguments.
3233 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003234 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003235 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003236 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003237 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003238 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239
David Majnemer89189202013-08-28 23:48:32 +00003240 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3241 Converted.data(), Converted.size());
3242
3243 // Only substitute for the innermost template argument list.
3244 MultiLevelTemplateArgumentList TemplateArgLists;
3245 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3246 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3247 TemplateArgLists.addOuterTemplateArguments(None);
3248
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003249 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003250 ArgType =
3251 SemaRef.SubstType(ArgType, TemplateArgLists,
3252 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003253 }
3254
3255 return ArgType;
3256}
3257
3258/// \brief Substitute template arguments into the default template argument for
3259/// the given non-type template parameter.
3260///
3261/// \param SemaRef the semantic analysis object for which we are performing
3262/// the substitution.
3263///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003265/// for.
3266///
3267/// \param TemplateLoc the location of the template name that started the
3268/// template-id we are checking.
3269///
3270/// \param RAngleLoc the location of the right angle bracket ('>') that
3271/// terminates the template-id.
3272///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003273/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003274/// substituting into.
3275///
3276/// \param Converted the list of template arguments provided for template
3277/// parameters that precede \p Param in the template parameter list.
3278///
3279/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003280static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003281SubstDefaultTemplateArgument(Sema &SemaRef,
3282 TemplateDecl *Template,
3283 SourceLocation TemplateLoc,
3284 SourceLocation RAngleLoc,
3285 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003287 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003288 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003289 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003290 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003291 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003292
David Majnemer89189202013-08-28 23:48:32 +00003293 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3294 Converted.data(), Converted.size());
3295
3296 // Only substitute for the innermost template argument list.
3297 MultiLevelTemplateArgumentList TemplateArgLists;
3298 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3299 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3300 TemplateArgLists.addOuterTemplateArguments(None);
3301
Faisal Vali48401eb2015-11-19 19:20:17 +00003302 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3303 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003304 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003305}
3306
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003307/// \brief Substitute template arguments into the default template argument for
3308/// the given template template parameter.
3309///
3310/// \param SemaRef the semantic analysis object for which we are performing
3311/// the substitution.
3312///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003314/// for.
3315///
3316/// \param TemplateLoc the location of the template name that started the
3317/// template-id we are checking.
3318///
3319/// \param RAngleLoc the location of the right angle bracket ('>') that
3320/// terminates the template-id.
3321///
3322/// \param Param the template template parameter whose default we are
3323/// substituting into.
3324///
3325/// \param Converted the list of template arguments provided for template
3326/// parameters that precede \p Param in the template parameter list.
3327///
Douglas Gregordf846d12011-03-02 18:46:51 +00003328/// \param QualifierLoc Will be set to the nested-name-specifier (with
3329/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003330///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003331/// \returns the substituted template argument, or NULL if an error occurred.
3332static TemplateName
3333SubstDefaultTemplateArgument(Sema &SemaRef,
3334 TemplateDecl *Template,
3335 SourceLocation TemplateLoc,
3336 SourceLocation RAngleLoc,
3337 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003338 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003339 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003340 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003341 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003342 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003343 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344
David Majnemer89189202013-08-28 23:48:32 +00003345 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3346 Converted.data(), Converted.size());
3347
3348 // Only substitute for the innermost template argument list.
3349 MultiLevelTemplateArgumentList TemplateArgLists;
3350 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3351 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3352 TemplateArgLists.addOuterTemplateArguments(None);
3353
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003354 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003355 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003356 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003357 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003358 QualifierLoc =
3359 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003360 if (!QualifierLoc)
3361 return TemplateName();
3362 }
David Majnemer89189202013-08-28 23:48:32 +00003363
3364 return SemaRef.SubstTemplateName(
3365 QualifierLoc,
3366 Param->getDefaultArgument().getArgument().getAsTemplate(),
3367 Param->getDefaultArgument().getTemplateNameLoc(),
3368 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003369}
3370
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003371/// \brief If the given template parameter has a default template
3372/// argument, substitute into that default template argument and
3373/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003375Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3376 SourceLocation TemplateLoc,
3377 SourceLocation RAngleLoc,
3378 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003379 SmallVectorImpl<TemplateArgument>
3380 &Converted,
3381 bool &HasDefaultArg) {
3382 HasDefaultArg = false;
3383
3384 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003385 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003386 return TemplateArgumentLoc();
3387
Richard Smithc87b9382013-07-04 01:01:24 +00003388 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003389 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003390 TemplateLoc,
3391 RAngleLoc,
3392 TypeParm,
3393 Converted);
3394 if (DI)
3395 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3396
3397 return TemplateArgumentLoc();
3398 }
3399
3400 if (NonTypeTemplateParmDecl *NonTypeParm
3401 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003402 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003403 return TemplateArgumentLoc();
3404
Richard Smithc87b9382013-07-04 01:01:24 +00003405 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003406 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003407 TemplateLoc,
3408 RAngleLoc,
3409 NonTypeParm,
3410 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003411 if (Arg.isInvalid())
3412 return TemplateArgumentLoc();
3413
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003414 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003415 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3416 }
3417
3418 TemplateTemplateParmDecl *TempTempParm
3419 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003420 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003421 return TemplateArgumentLoc();
3422
Richard Smithc87b9382013-07-04 01:01:24 +00003423 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003424 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003425 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003427 RAngleLoc,
3428 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003429 Converted,
3430 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003431 if (TName.isNull())
3432 return TemplateArgumentLoc();
3433
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003435 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003436 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3437}
3438
Douglas Gregorda0fb532009-11-11 19:31:23 +00003439/// \brief Check that the given template argument corresponds to the given
3440/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003441///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003443/// checked.
3444///
Richard Trieu15b66532015-01-24 02:48:32 +00003445/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003446///
3447/// \param Template The template in which the template argument resides.
3448///
3449/// \param TemplateLoc The location of the template name for the template
3450/// whose argument list we're matching.
3451///
3452/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3453/// the template argument list.
3454///
3455/// \param ArgumentPackIndex The index into the argument pack where this
3456/// argument will be placed. Only valid if the parameter is a parameter pack.
3457///
3458/// \param Converted The checked, converted argument will be added to the
3459/// end of this small vector.
3460///
3461/// \param CTAK Describes how we arrived at this particular template argument:
3462/// explicitly written, deduced, etc.
3463///
3464/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003465bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003466 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003467 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003468 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003469 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003470 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003471 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003472 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003473 // Check template type parameters.
3474 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003475 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003476
Douglas Gregoreebed722009-11-11 19:41:09 +00003477 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003479 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003480 // with the template arguments we've seen thus far. But if the
3481 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003482 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003483 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3484 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485
Peter Collingbourne01687632010-12-10 17:08:53 +00003486 if (NTTPType->isDependentType() &&
3487 !isa<TemplateTemplateParmDecl>(Template) &&
3488 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003489 // Do substitution on the type of the non-type template parameter.
3490 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003491 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003492 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003493 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003494 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495
3496 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003497 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003498 NTTPType = SubstType(NTTPType,
3499 MultiLevelTemplateArgumentList(TemplateArgs),
3500 NTTP->getLocation(),
3501 NTTP->getDeclName());
3502 // If that worked, check the non-type template parameter type
3503 // for validity.
3504 if (!NTTPType.isNull())
3505 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3506 NTTP->getLocation());
3507 if (NTTPType.isNull())
3508 return true;
3509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510
Douglas Gregorda0fb532009-11-11 19:31:23 +00003511 switch (Arg.getArgument().getKind()) {
3512 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003513 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
Douglas Gregorda0fb532009-11-11 19:31:23 +00003515 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003516 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003517 ExprResult Res =
3518 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3519 Result, CTAK);
3520 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003521 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522
Richard Trieu15b66532015-01-24 02:48:32 +00003523 // If the resulting expression is new, then use it in place of the
3524 // old expression in the template argument.
3525 if (Res.get() != Arg.getArgument().getAsExpr()) {
3526 TemplateArgument TA(Res.get());
3527 Arg = TemplateArgumentLoc(TA, Res.get());
3528 }
3529
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003530 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003531 break;
3532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003533
Douglas Gregorda0fb532009-11-11 19:31:23 +00003534 case TemplateArgument::Declaration:
3535 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003536 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003537 // We've already checked this template argument, so just copy
3538 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003539 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003540 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
Douglas Gregorda0fb532009-11-11 19:31:23 +00003542 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003543 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003544 // We were given a template template argument. It may not be ill-formed;
3545 // see below.
3546 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003547 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3548 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003549 // We have a template argument such as \c T::template X, which we
3550 // parsed as a template template argument. However, since we now
3551 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003552 // template name into an expression.
3553
3554 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3555 Arg.getTemplateNameLoc());
3556
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003557 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003558 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003559 // FIXME: the template-template arg was a DependentTemplateName,
3560 // so it was provided with a template keyword. However, its source
3561 // location is not stored in the template argument structure.
3562 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003563 ExprResult E = DependentScopeDeclRefExpr::Create(
3564 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3565 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003567 // If we parsed the template argument as a pack expansion, create a
3568 // pack expansion expression.
3569 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003570 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003571 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003572 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574
Douglas Gregorda0fb532009-11-11 19:31:23 +00003575 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003576 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003577 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003578 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003580 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003581 break;
3582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregorda0fb532009-11-11 19:31:23 +00003584 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003585 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003586 // therefore cannot be a non-type template argument.
3587 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3588 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589
Douglas Gregorda0fb532009-11-11 19:31:23 +00003590 Diag(Param->getLocation(), diag::note_template_param_here);
3591 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Douglas Gregorda0fb532009-11-11 19:31:23 +00003593 case TemplateArgument::Type: {
3594 // We have a non-type template parameter but the template
3595 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregorda0fb532009-11-11 19:31:23 +00003597 // C++ [temp.arg]p2:
3598 // In a template-argument, an ambiguity between a type-id and
3599 // an expression is resolved to a type-id, regardless of the
3600 // form of the corresponding template-parameter.
3601 //
3602 // We warn specifically about this case, since it can be rather
3603 // confusing for users.
3604 QualType T = Arg.getArgument().getAsType();
3605 SourceRange SR = Arg.getSourceRange();
3606 if (T->isFunctionType())
3607 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3608 else
3609 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3610 Diag(Param->getLocation(), diag::note_template_param_here);
3611 return true;
3612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Douglas Gregorda0fb532009-11-11 19:31:23 +00003614 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003615 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617
Douglas Gregorda0fb532009-11-11 19:31:23 +00003618 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619 }
3620
3621
Douglas Gregorda0fb532009-11-11 19:31:23 +00003622 // Check template template parameters.
3623 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624
Douglas Gregorda0fb532009-11-11 19:31:23 +00003625 // Substitute into the template parameter list of the template
3626 // template parameter, since previously-supplied template arguments
3627 // may appear within the template template parameter.
3628 {
3629 // Set up a template instantiation context.
3630 LocalInstantiationScope Scope(*this);
3631 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003632 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003633 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003634 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003635 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636
3637 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003638 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003639 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003641 MultiLevelTemplateArgumentList(TemplateArgs)));
3642 if (!TempParm)
3643 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregorda0fb532009-11-11 19:31:23 +00003646 switch (Arg.getArgument().getKind()) {
3647 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003648 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649
Douglas Gregorda0fb532009-11-11 19:31:23 +00003650 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003651 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003652 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003653 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003655 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657
Douglas Gregorda0fb532009-11-11 19:31:23 +00003658 case TemplateArgument::Expression:
3659 case TemplateArgument::Type:
3660 // We have a template template parameter but the template
3661 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003662 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003663 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003664 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665
Douglas Gregorda0fb532009-11-11 19:31:23 +00003666 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003667 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003668 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003669 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003670 case TemplateArgument::NullPtr:
3671 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672
Douglas Gregorda0fb532009-11-11 19:31:23 +00003673 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003674 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Douglas Gregorda0fb532009-11-11 19:31:23 +00003677 return false;
3678}
3679
Douglas Gregor8e072612012-02-03 07:34:46 +00003680/// \brief Diagnose an arity mismatch in the
3681static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3682 SourceLocation TemplateLoc,
3683 TemplateArgumentListInfo &TemplateArgs) {
3684 TemplateParameterList *Params = Template->getTemplateParameters();
3685 unsigned NumParams = Params->size();
3686 unsigned NumArgs = TemplateArgs.size();
3687
3688 SourceRange Range;
3689 if (NumArgs > NumParams)
3690 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3691 TemplateArgs.getRAngleLoc());
3692 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3693 << (NumArgs > NumParams)
3694 << (isa<ClassTemplateDecl>(Template)? 0 :
3695 isa<FunctionTemplateDecl>(Template)? 1 :
3696 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3697 << Template << Range;
3698 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3699 << Params->getSourceRange();
3700 return true;
3701}
3702
Richard Smith1fde8ec2012-09-07 02:06:42 +00003703/// \brief Check whether the template parameter is a pack expansion, and if so,
3704/// determine the number of parameters produced by that expansion. For instance:
3705///
3706/// \code
3707/// template<typename ...Ts> struct A {
3708/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3709/// };
3710/// \endcode
3711///
3712/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3713/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003714static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003715 if (NonTypeTemplateParmDecl *NTTP
3716 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3717 if (NTTP->isExpandedParameterPack())
3718 return NTTP->getNumExpansionTypes();
3719 }
3720
3721 if (TemplateTemplateParmDecl *TTP
3722 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3723 if (TTP->isExpandedParameterPack())
3724 return TTP->getNumExpansionTemplateParameters();
3725 }
3726
David Blaikie7a30dc52013-02-21 01:47:18 +00003727 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003728}
3729
Richard Smith35c1df52015-06-17 20:16:32 +00003730/// Diagnose a missing template argument.
3731template<typename TemplateParmDecl>
3732static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3733 TemplateDecl *TD,
3734 const TemplateParmDecl *D,
3735 TemplateArgumentListInfo &Args) {
3736 // Dig out the most recent declaration of the template parameter; there may be
3737 // declarations of the template that are more recent than TD.
3738 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3739 ->getTemplateParameters()
3740 ->getParam(D->getIndex()));
3741
3742 // If there's a default argument that's not visible, diagnose that we're
3743 // missing a module import.
3744 llvm::SmallVector<Module*, 8> Modules;
3745 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3746 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3747 D->getDefaultArgumentLoc(), Modules,
3748 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003749 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003750 return true;
3751 }
3752
3753 // FIXME: If there's a more recent default argument that *is* visible,
3754 // diagnose that it was declared too late.
3755
3756 return diagnoseArityMismatch(S, TD, Loc, Args);
3757}
3758
Douglas Gregord32e0282009-02-09 23:23:08 +00003759/// \brief Check that the given template argument list is well-formed
3760/// for specializing the given template.
3761bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3762 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003763 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003764 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003765 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003766 // Make a copy of the template arguments for processing. Only make the
3767 // changes at the end when successful in matching the arguments to the
3768 // template.
3769 TemplateArgumentListInfo NewArgs = TemplateArgs;
3770
Douglas Gregord32e0282009-02-09 23:23:08 +00003771 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003772
Richard Trieu15b66532015-01-24 02:48:32 +00003773 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003774
Mike Stump11289f42009-09-09 15:08:12 +00003775 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003776 // [...] The type and form of each template-argument specified in
3777 // a template-id shall match the type and form specified for the
3778 // corresponding parameter declared by the template in its
3779 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003780 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003781 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003782 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003783 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003784 for (TemplateParameterList::iterator Param = Params->begin(),
3785 ParamEnd = Params->end();
3786 Param != ParamEnd; /* increment in loop */) {
3787 // If we have an expanded parameter pack, make sure we don't have too
3788 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003789 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003790 if (*Expansions == ArgumentPack.size()) {
3791 // We're done with this parameter pack. Pack up its arguments and add
3792 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003793 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003794 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003795 ArgumentPack.clear();
3796
Richard Smith1fde8ec2012-09-07 02:06:42 +00003797 // This argument is assigned to the next parameter.
3798 ++Param;
3799 continue;
3800 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3801 // Not enough arguments for this parameter pack.
3802 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3803 << false
3804 << (isa<ClassTemplateDecl>(Template)? 0 :
3805 isa<FunctionTemplateDecl>(Template)? 1 :
3806 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3807 << Template;
3808 Diag(Template->getLocation(), diag::note_template_decl_here)
3809 << Params->getSourceRange();
3810 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003811 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813
Richard Smith1fde8ec2012-09-07 02:06:42 +00003814 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003815 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003816 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003818 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003819 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Richard Smith96d71c32014-11-12 23:38:38 +00003821 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003822 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003823 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3824 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003825 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003826 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003827 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003828 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003829 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003830 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003831 Diag((*Param)->getLocation(), diag::note_template_param_here);
3832 return true;
3833 }
3834
Richard Smith1fde8ec2012-09-07 02:06:42 +00003835 // We're now done with this argument.
3836 ++ArgIdx;
3837
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003838 if ((*Param)->isTemplateParameterPack()) {
3839 // The template parameter was a template parameter pack, so take the
3840 // deduced argument and place it on the argument pack. Note that we
3841 // stay on the same template parameter so that we can deduce more
3842 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003843 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003844 } else {
3845 // Move to the next template parameter.
3846 ++Param;
3847 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003848
Richard Smith96d71c32014-11-12 23:38:38 +00003849 // If we just saw a pack expansion into a non-pack, then directly convert
3850 // the remaining arguments, because we don't know what parameters they'll
3851 // match up with.
3852 if (PackExpansionIntoNonPack) {
3853 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003854 // If we were part way through filling in an expanded parameter pack,
3855 // fall back to just producing individual arguments.
3856 Converted.insert(Converted.end(),
3857 ArgumentPack.begin(), ArgumentPack.end());
3858 ArgumentPack.clear();
3859 }
3860
3861 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003862 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003863 ++ArgIdx;
3864 }
3865
Richard Smith1fde8ec2012-09-07 02:06:42 +00003866 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003867 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003868
Douglas Gregor84d49a22009-11-11 21:54:23 +00003869 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
Douglas Gregor2f157c92011-06-03 02:59:40 +00003872 // If we're checking a partial template argument list, we're done.
3873 if (PartialTemplateArgs) {
3874 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003875 Converted.push_back(
3876 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3877
Richard Smith1fde8ec2012-09-07 02:06:42 +00003878 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003879 }
3880
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003882 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003883 if ((*Param)->isTemplateParameterPack()) {
3884 assert(!getExpandedPackSize(*Param) &&
3885 "Should have dealt with this already");
3886
3887 // A non-expanded parameter pack before the end of the parameter list
3888 // only occurs for an ill-formed template parameter list, unless we've
3889 // got a partial argument list for a function template, so just bail out.
3890 if (Param + 1 != ParamEnd)
3891 return true;
3892
Benjamin Kramercce63472015-08-05 09:40:22 +00003893 Converted.push_back(
3894 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003895 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003896
3897 ++Param;
3898 continue;
3899 }
3900
Douglas Gregor8e072612012-02-03 07:34:46 +00003901 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003902 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003903
Douglas Gregor84d49a22009-11-11 21:54:23 +00003904 // Retrieve the default template argument from the template
3905 // parameter. For each kind of template parameter, we substitute the
3906 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003908 // the default argument.
3909 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003910 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003911 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3912 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003913
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003914 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003915 Template,
3916 TemplateLoc,
3917 RAngleLoc,
3918 TTP,
3919 Converted);
3920 if (!ArgType)
3921 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922
Douglas Gregor84d49a22009-11-11 21:54:23 +00003923 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3924 ArgType);
3925 } else if (NonTypeTemplateParmDecl *NTTP
3926 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003927 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003928 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3929 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003930
John McCalldadc5752010-08-24 06:29:42 +00003931 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932 TemplateLoc,
3933 RAngleLoc,
3934 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003935 Converted);
3936 if (E.isInvalid())
3937 return true;
3938
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003939 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003940 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3941 } else {
3942 TemplateTemplateParmDecl *TempParm
3943 = cast<TemplateTemplateParmDecl>(*Param);
3944
Richard Smith95d83952015-06-10 20:36:34 +00003945 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003946 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3947 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003948
Douglas Gregordf846d12011-03-02 18:46:51 +00003949 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003950 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951 TemplateLoc,
3952 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003953 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003954 Converted,
3955 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003956 if (Name.isNull())
3957 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958
Douglas Gregor9d802122011-03-02 17:09:35 +00003959 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3960 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003962
Douglas Gregor84d49a22009-11-11 21:54:23 +00003963 // Introduce an instantiation record that describes where we are using
3964 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003965 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3966 SourceRange(TemplateLoc, RAngleLoc));
3967 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003968 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969
Douglas Gregor84d49a22009-11-11 21:54:23 +00003970 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003971 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003972 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003973 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003974
Richard Trieu15b66532015-01-24 02:48:32 +00003975 // Core issue 150 (assumed resolution): if this is a template template
3976 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003977 // template definition.
3978 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003979 NewArgs.addArgument(Arg);
3980
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003981 // Move to the next template parameter and argument.
3982 ++Param;
3983 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
Richard Smith07f79912014-06-06 16:00:50 +00003986 // If we're performing a partial argument substitution, allow any trailing
3987 // pack expansions; they might be empty. This can happen even if
3988 // PartialTemplateArgs is false (the list of arguments is complete but
3989 // still dependent).
3990 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3991 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003992 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3993 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003994 }
3995
Douglas Gregor8e072612012-02-03 07:34:46 +00003996 // If we have any leftover arguments, then there were too many arguments.
3997 // Complain and fail.
3998 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003999 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4000
4001 // No problems found with the new argument list, propagate changes back
4002 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004003 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004
Richard Smith1fde8ec2012-09-07 02:06:42 +00004005 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004006}
4007
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004008namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004009 class UnnamedLocalNoLinkageFinder
4010 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004011 {
4012 Sema &S;
4013 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004015 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004017 public:
4018 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4019
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020 bool Visit(QualType T) {
4021 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004024#define TYPE(Class, Parent) \
4025 bool Visit##Class##Type(const Class##Type *);
4026#define ABSTRACT_TYPE(Class, Parent) \
4027 bool Visit##Class##Type(const Class##Type *) { return false; }
4028#define NON_CANONICAL_TYPE(Class, Parent) \
4029 bool Visit##Class##Type(const Class##Type *) { return false; }
4030#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004032 bool VisitTagDecl(const TagDecl *Tag);
4033 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4034 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004035} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004036
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004038 return false;
4039}
4040
4041bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4042 return Visit(T->getElementType());
4043}
4044
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004046 return Visit(T->getPointeeType());
4047}
4048
4049bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004051 return Visit(T->getPointeeType());
4052}
4053
4054bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004056 return Visit(T->getPointeeType());
4057}
4058
4059bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004061 return Visit(T->getPointeeType());
4062}
4063
4064bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004066 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4067}
4068
4069bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004070 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004071 return Visit(T->getElementType());
4072}
4073
4074bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004076 return Visit(T->getElementType());
4077}
4078
4079bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004081 return Visit(T->getElementType());
4082}
4083
4084bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004086 return Visit(T->getElementType());
4087}
4088
4089bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004091 return Visit(T->getElementType());
4092}
4093
4094bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4095 return Visit(T->getElementType());
4096}
4097
4098bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4099 return Visit(T->getElementType());
4100}
4101
4102bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4103 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004104 for (const auto &A : T->param_types()) {
4105 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004106 return true;
4107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Alp Toker314cc812014-01-25 16:55:45 +00004109 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004110}
4111
4112bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4113 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004114 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004115}
4116
4117bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4118 const UnresolvedUsingType*) {
4119 return false;
4120}
4121
4122bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4123 return false;
4124}
4125
4126bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4127 return Visit(T->getUnderlyingType());
4128}
4129
4130bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4131 return false;
4132}
4133
Alexis Hunte852b102011-05-24 22:41:36 +00004134bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4135 const UnaryTransformType*) {
4136 return false;
4137}
4138
Richard Smith30482bc2011-02-20 03:19:35 +00004139bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4140 return Visit(T->getDeducedType());
4141}
4142
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004143bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4144 return VisitTagDecl(T->getDecl());
4145}
4146
4147bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4148 return VisitTagDecl(T->getDecl());
4149}
4150
4151bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4152 const TemplateTypeParmType*) {
4153 return false;
4154}
4155
Douglas Gregorada4b792011-01-14 02:55:32 +00004156bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4157 const SubstTemplateTypeParmPackType *) {
4158 return false;
4159}
4160
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004161bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4162 const TemplateSpecializationType*) {
4163 return false;
4164}
4165
4166bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4167 const InjectedClassNameType* T) {
4168 return VisitTagDecl(T->getDecl());
4169}
4170
4171bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4172 const DependentNameType* T) {
4173 return VisitNestedNameSpecifier(T->getQualifier());
4174}
4175
4176bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4177 const DependentTemplateSpecializationType* T) {
4178 return VisitNestedNameSpecifier(T->getQualifier());
4179}
4180
Douglas Gregord2fa7662010-12-20 02:24:11 +00004181bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4182 const PackExpansionType* T) {
4183 return Visit(T->getPattern());
4184}
4185
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004186bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4187 return false;
4188}
4189
4190bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4191 const ObjCInterfaceType *) {
4192 return false;
4193}
4194
4195bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4196 const ObjCObjectPointerType *) {
4197 return false;
4198}
4199
Eli Friedman0dfb8892011-10-06 23:00:33 +00004200bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4201 return Visit(T->getValueType());
4202}
4203
Xiuli Pan9c14e282016-01-09 12:53:17 +00004204bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4205 return false;
4206}
4207
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004208bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4209 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004210 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004211 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004212 diag::warn_cxx98_compat_template_arg_local_type :
4213 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004214 << S.Context.getTypeDeclType(Tag) << SR;
4215 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004216 }
4217
John McCall5ea95772013-03-09 00:54:27 +00004218 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004219 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004220 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004221 diag::warn_cxx98_compat_template_arg_unnamed_type :
4222 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004223 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4224 return true;
4225 }
4226
4227 return false;
4228}
4229
4230bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4231 NestedNameSpecifier *NNS) {
4232 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4233 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004235 switch (NNS->getKind()) {
4236 case NestedNameSpecifier::Identifier:
4237 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004238 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004239 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004240 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004241 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004243 case NestedNameSpecifier::TypeSpec:
4244 case NestedNameSpecifier::TypeSpecWithTemplate:
4245 return Visit(QualType(NNS->getAsType(), 0));
4246 }
David Blaikie8a40f702012-01-17 06:56:22 +00004247 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004248}
4249
Douglas Gregord32e0282009-02-09 23:23:08 +00004250/// \brief Check a template argument against its corresponding
4251/// template type parameter.
4252///
4253/// This routine implements the semantics of C++ [temp.arg.type]. It
4254/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004255bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004256 TypeSourceInfo *ArgInfo) {
4257 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004258 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004259 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004260
4261 if (Arg->isVariablyModifiedType()) {
4262 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004263 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004264 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004265 }
4266
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004267 // C++03 [temp.arg.type]p2:
4268 // A local type, a type with no linkage, an unnamed type or a type
4269 // compounded from any of these types shall not be used as a
4270 // template-argument for a template type-parameter.
4271 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004272 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004273 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004274 bool NeedsCheck;
4275 if (LangOpts.CPlusPlus11)
4276 NeedsCheck =
4277 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4278 SR.getBegin()) ||
4279 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4280 SR.getBegin());
4281 else
4282 NeedsCheck = Arg->hasUnnamedOrLocalType();
4283
4284 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004285 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4286 (void)Finder.Visit(Context.getCanonicalType(Arg));
4287 }
4288
Douglas Gregord32e0282009-02-09 23:23:08 +00004289 return false;
4290}
4291
Douglas Gregor20fdef32012-04-10 17:08:25 +00004292enum NullPointerValueKind {
4293 NPV_NotNullPointer,
4294 NPV_NullPointer,
4295 NPV_Error
4296};
4297
4298/// \brief Determine whether the given template argument is a null pointer
4299/// value of the appropriate type.
4300static NullPointerValueKind
4301isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4302 QualType ParamType, Expr *Arg) {
4303 if (Arg->isValueDependent() || Arg->isTypeDependent())
4304 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004305
Richard Smithdb0ac552015-12-18 22:40:25 +00004306 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004307 llvm_unreachable(
4308 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004309
David Majnemer5c734ad2014-08-14 00:49:23 +00004310 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004311 return NPV_NotNullPointer;
4312
4313 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004314 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4315 if (ArgRV.isInvalid())
4316 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004317 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004318
Douglas Gregor20fdef32012-04-10 17:08:25 +00004319 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004320 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004321 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004322 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004323 EvalResult.HasSideEffects) {
4324 SourceLocation DiagLoc = Arg->getExprLoc();
4325
4326 // If our only note is the usual "invalid subexpression" note, just point
4327 // the caret at its location rather than producing an essentially
4328 // redundant note.
4329 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4330 diag::note_invalid_subexpr_in_const_expr) {
4331 DiagLoc = Notes[0].first;
4332 Notes.clear();
4333 }
4334
4335 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4336 << Arg->getType() << Arg->getSourceRange();
4337 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4338 S.Diag(Notes[I].first, Notes[I].second);
4339
4340 S.Diag(Param->getLocation(), diag::note_template_param_here);
4341 return NPV_Error;
4342 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004343
4344 // C++11 [temp.arg.nontype]p1:
4345 // - an address constant expression of type std::nullptr_t
4346 if (Arg->getType()->isNullPtrType())
4347 return NPV_NullPointer;
4348
4349 // - a constant expression that evaluates to a null pointer value (4.10); or
4350 // - a constant expression that evaluates to a null member pointer value
4351 // (4.11); or
4352 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4353 (EvalResult.Val.isMemberPointer() &&
4354 !EvalResult.Val.getMemberPointerDecl())) {
4355 // If our expression has an appropriate type, we've succeeded.
4356 bool ObjCLifetimeConversion;
4357 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4358 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4359 ObjCLifetimeConversion))
4360 return NPV_NullPointer;
4361
4362 // The types didn't match, but we know we got a null pointer; complain,
4363 // then recover as if the types were correct.
4364 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4365 << Arg->getType() << ParamType << Arg->getSourceRange();
4366 S.Diag(Param->getLocation(), diag::note_template_param_here);
4367 return NPV_NullPointer;
4368 }
4369
4370 // If we don't have a null pointer value, but we do have a NULL pointer
4371 // constant, suggest a cast to the appropriate type.
4372 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4373 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4374 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004375 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4376 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4377 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004378 S.Diag(Param->getLocation(), diag::note_template_param_here);
4379 return NPV_NullPointer;
4380 }
4381
4382 // FIXME: If we ever want to support general, address-constant expressions
4383 // as non-type template arguments, we should return the ExprResult here to
4384 // be interpreted by the caller.
4385 return NPV_NotNullPointer;
4386}
4387
David Majnemer61c39a12013-08-23 05:39:39 +00004388/// \brief Checks whether the given template argument is compatible with its
4389/// template parameter.
4390static bool CheckTemplateArgumentIsCompatibleWithParameter(
4391 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4392 Expr *Arg, QualType ArgType) {
4393 bool ObjCLifetimeConversion;
4394 if (ParamType->isPointerType() &&
4395 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4396 S.IsQualificationConversion(ArgType, ParamType, false,
4397 ObjCLifetimeConversion)) {
4398 // For pointer-to-object types, qualification conversions are
4399 // permitted.
4400 } else {
4401 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4402 if (!ParamRef->getPointeeType()->isFunctionType()) {
4403 // C++ [temp.arg.nontype]p5b3:
4404 // For a non-type template-parameter of type reference to
4405 // object, no conversions apply. The type referred to by the
4406 // reference may be more cv-qualified than the (otherwise
4407 // identical) type of the template- argument. The
4408 // template-parameter is bound directly to the
4409 // template-argument, which shall be an lvalue.
4410
4411 // FIXME: Other qualifiers?
4412 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4413 unsigned ArgQuals = ArgType.getCVRQualifiers();
4414
4415 if ((ParamQuals | ArgQuals) != ParamQuals) {
4416 S.Diag(Arg->getLocStart(),
4417 diag::err_template_arg_ref_bind_ignores_quals)
4418 << ParamType << Arg->getType() << Arg->getSourceRange();
4419 S.Diag(Param->getLocation(), diag::note_template_param_here);
4420 return true;
4421 }
4422 }
4423 }
4424
4425 // At this point, the template argument refers to an object or
4426 // function with external linkage. We now need to check whether the
4427 // argument and parameter types are compatible.
4428 if (!S.Context.hasSameUnqualifiedType(ArgType,
4429 ParamType.getNonReferenceType())) {
4430 // We can't perform this conversion or binding.
4431 if (ParamType->isReferenceType())
4432 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4433 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4434 else
4435 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4436 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4437 S.Diag(Param->getLocation(), diag::note_template_param_here);
4438 return true;
4439 }
4440 }
4441
4442 return false;
4443}
4444
Douglas Gregorccb07762009-02-11 19:52:55 +00004445/// \brief Checks whether the given template argument is the address
4446/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004448CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4449 NonTypeTemplateParmDecl *Param,
4450 QualType ParamType,
4451 Expr *ArgIn,
4452 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004453 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004454 Expr *Arg = ArgIn;
4455 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004456
Douglas Gregorb242683d2010-04-01 18:32:35 +00004457 bool AddressTaken = false;
4458 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004459 if (S.getLangOpts().MicrosoftExt) {
4460 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4461 // dereference and address-of operators.
4462 Arg = Arg->IgnoreParenCasts();
4463
4464 bool ExtWarnMSTemplateArg = false;
4465 UnaryOperatorKind FirstOpKind;
4466 SourceLocation FirstOpLoc;
4467 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4468 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4469 if (UnOpKind == UO_Deref)
4470 ExtWarnMSTemplateArg = true;
4471 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4472 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4473 if (!AddrOpLoc.isValid()) {
4474 FirstOpKind = UnOpKind;
4475 FirstOpLoc = UnOp->getOperatorLoc();
4476 }
4477 } else
4478 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004479 }
David Majnemer61c39a12013-08-23 05:39:39 +00004480 if (FirstOpLoc.isValid()) {
4481 if (ExtWarnMSTemplateArg)
4482 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4483 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004484
David Majnemer61c39a12013-08-23 05:39:39 +00004485 if (FirstOpKind == UO_AddrOf)
4486 AddressTaken = true;
4487 else if (Arg->getType()->isPointerType()) {
4488 // We cannot let pointers get dereferenced here, that is obviously not a
4489 // constant expression.
4490 assert(FirstOpKind == UO_Deref);
4491 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4492 << Arg->getSourceRange();
4493 }
4494 }
4495 } else {
4496 // See through any implicit casts we added to fix the type.
4497 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004498
David Majnemer61c39a12013-08-23 05:39:39 +00004499 // C++ [temp.arg.nontype]p1:
4500 //
4501 // A template-argument for a non-type, non-template
4502 // template-parameter shall be one of: [...]
4503 //
4504 // -- the address of an object or function with external
4505 // linkage, including function templates and function
4506 // template-ids but excluding non-static class members,
4507 // expressed as & id-expression where the & is optional if
4508 // the name refers to a function or array, or if the
4509 // corresponding template-parameter is a reference; or
4510
4511 // In C++98/03 mode, give an extension warning on any extra parentheses.
4512 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4513 bool ExtraParens = false;
4514 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4515 if (!Invalid && !ExtraParens) {
4516 S.Diag(Arg->getLocStart(),
4517 S.getLangOpts().CPlusPlus11
4518 ? diag::warn_cxx98_compat_template_arg_extra_parens
4519 : diag::ext_template_arg_extra_parens)
4520 << Arg->getSourceRange();
4521 ExtraParens = true;
4522 }
4523
4524 Arg = Parens->getSubExpr();
4525 }
4526
4527 while (SubstNonTypeTemplateParmExpr *subst =
4528 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4529 Arg = subst->getReplacement()->IgnoreImpCasts();
4530
4531 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4532 if (UnOp->getOpcode() == UO_AddrOf) {
4533 Arg = UnOp->getSubExpr();
4534 AddressTaken = true;
4535 AddrOpLoc = UnOp->getOperatorLoc();
4536 }
4537 }
4538
4539 while (SubstNonTypeTemplateParmExpr *subst =
4540 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4541 Arg = subst->getReplacement()->IgnoreImpCasts();
4542 }
John McCall7c454bb2011-07-15 05:09:51 +00004543
David Majnemer07910d62014-06-26 07:48:46 +00004544 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4545 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4546
4547 // If our parameter has pointer type, check for a null template value.
4548 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4549 NullPointerValueKind NPV;
4550 // dllimport'd entities aren't constant but are available inside of template
4551 // arguments.
4552 if (Entity && Entity->hasAttr<DLLImportAttr>())
4553 NPV = NPV_NotNullPointer;
4554 else
4555 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4556 switch (NPV) {
4557 case NPV_NullPointer:
4558 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004559 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4560 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004561 return false;
4562
4563 case NPV_Error:
4564 return true;
4565
4566 case NPV_NotNullPointer:
4567 break;
4568 }
4569 }
4570
Chandler Carruth724a8a12010-01-31 10:01:20 +00004571 // Stop checking the precise nature of the argument if it is value dependent,
4572 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004573 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004574 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004575 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004576 }
David Majnemer61c39a12013-08-23 05:39:39 +00004577
4578 if (isa<CXXUuidofExpr>(Arg)) {
4579 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4580 ArgIn, Arg, ArgType))
4581 return true;
4582
4583 Converted = TemplateArgument(ArgIn);
4584 return false;
4585 }
4586
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004587 if (!DRE) {
4588 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4589 << Arg->getSourceRange();
4590 S.Diag(Param->getLocation(), diag::note_template_param_here);
4591 return true;
4592 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004593
Douglas Gregorccb07762009-02-11 19:52:55 +00004594 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004595 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004596 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004597 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004598 S.Diag(Param->getLocation(), diag::note_template_param_here);
4599 return true;
4600 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004601
4602 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004604 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004605 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004606 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004607 S.Diag(Param->getLocation(), diag::note_template_param_here);
4608 return true;
4609 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004610 }
Mike Stump11289f42009-09-09 15:08:12 +00004611
Richard Smith9380e0e2012-04-04 21:11:30 +00004612 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4613 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004614
Richard Smith9380e0e2012-04-04 21:11:30 +00004615 // A non-type template argument must refer to an object or function.
4616 if (!Func && !Var) {
4617 // We found something, but we don't know specifically what it is.
4618 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4619 << Arg->getSourceRange();
4620 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4621 return true;
4622 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004623
Richard Smith9380e0e2012-04-04 21:11:30 +00004624 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004625 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004626 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004627 diag::warn_cxx98_compat_template_arg_object_internal :
4628 diag::ext_template_arg_object_internal)
4629 << !Func << Entity << Arg->getSourceRange();
4630 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4631 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004632 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004633 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4634 << !Func << Entity << Arg->getSourceRange();
4635 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4636 << !Func;
4637 return true;
4638 }
4639
4640 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004641 // If the template parameter has pointer type, the function decays.
4642 if (ParamType->isPointerType() && !AddressTaken)
4643 ArgType = S.Context.getPointerType(Func->getType());
4644 else if (AddressTaken && ParamType->isReferenceType()) {
4645 // If we originally had an address-of operator, but the
4646 // parameter has reference type, complain and (if things look
4647 // like they will work) drop the address-of operator.
4648 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4649 ParamType.getNonReferenceType())) {
4650 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4651 << ParamType;
4652 S.Diag(Param->getLocation(), diag::note_template_param_here);
4653 return true;
4654 }
4655
4656 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4657 << ParamType
4658 << FixItHint::CreateRemoval(AddrOpLoc);
4659 S.Diag(Param->getLocation(), diag::note_template_param_here);
4660
4661 ArgType = Func->getType();
4662 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004663 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004664 // A value of reference type is not an object.
4665 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004666 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004667 diag::err_template_arg_reference_var)
4668 << Var->getType() << Arg->getSourceRange();
4669 S.Diag(Param->getLocation(), diag::note_template_param_here);
4670 return true;
4671 }
4672
Richard Smith9380e0e2012-04-04 21:11:30 +00004673 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004674 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004675 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4676 << Arg->getSourceRange();
4677 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4678 return true;
4679 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004680
4681 // If the template parameter has pointer type, we must have taken
4682 // the address of this object.
4683 if (ParamType->isReferenceType()) {
4684 if (AddressTaken) {
4685 // If we originally had an address-of operator, but the
4686 // parameter has reference type, complain and (if things look
4687 // like they will work) drop the address-of operator.
4688 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4689 ParamType.getNonReferenceType())) {
4690 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4691 << ParamType;
4692 S.Diag(Param->getLocation(), diag::note_template_param_here);
4693 return true;
4694 }
4695
4696 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4697 << ParamType
4698 << FixItHint::CreateRemoval(AddrOpLoc);
4699 S.Diag(Param->getLocation(), diag::note_template_param_here);
4700
4701 ArgType = Var->getType();
4702 }
4703 } else if (!AddressTaken && ParamType->isPointerType()) {
4704 if (Var->getType()->isArrayType()) {
4705 // Array-to-pointer decay.
4706 ArgType = S.Context.getArrayDecayedType(Var->getType());
4707 } else {
4708 // If the template parameter has pointer type but the address of
4709 // this object was not taken, complain and (possibly) recover by
4710 // taking the address of the entity.
4711 ArgType = S.Context.getPointerType(Var->getType());
4712 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4713 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4714 << ParamType;
4715 S.Diag(Param->getLocation(), diag::note_template_param_here);
4716 return true;
4717 }
4718
4719 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4720 << ParamType
4721 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4722
4723 S.Diag(Param->getLocation(), diag::note_template_param_here);
4724 }
4725 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004726 }
Mike Stump11289f42009-09-09 15:08:12 +00004727
David Majnemer61c39a12013-08-23 05:39:39 +00004728 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4729 Arg, ArgType))
4730 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004731
4732 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004733 Converted =
4734 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004735 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004736 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004737}
4738
4739/// \brief Checks whether the given template argument is a pointer to
4740/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004741static bool CheckTemplateArgumentPointerToMember(Sema &S,
4742 NonTypeTemplateParmDecl *Param,
4743 QualType ParamType,
4744 Expr *&ResultArg,
4745 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004746 bool Invalid = false;
4747
Douglas Gregor20fdef32012-04-10 17:08:25 +00004748 // Check for a null pointer value.
4749 Expr *Arg = ResultArg;
4750 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4751 case NPV_Error:
4752 return true;
4753 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004754 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004755 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4756 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004757 return false;
4758 case NPV_NotNullPointer:
4759 break;
4760 }
4761
4762 bool ObjCLifetimeConversion;
4763 if (S.IsQualificationConversion(Arg->getType(),
4764 ParamType.getNonReferenceType(),
4765 false, ObjCLifetimeConversion)) {
4766 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004767 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004768 ResultArg = Arg;
4769 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4770 ParamType.getNonReferenceType())) {
4771 // We can't perform this conversion.
4772 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4773 << Arg->getType() << ParamType << Arg->getSourceRange();
4774 S.Diag(Param->getLocation(), diag::note_template_param_here);
4775 return true;
4776 }
4777
Douglas Gregorccb07762009-02-11 19:52:55 +00004778 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004779 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004780 Arg = Cast->getSubExpr();
4781
4782 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004783 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004784 // A template-argument for a non-type, non-template
4785 // template-parameter shall be one of: [...]
4786 //
4787 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004788 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004789
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004790 // In C++98/03 mode, give an extension warning on any extra parentheses.
4791 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4792 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004793 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004794 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004795 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004796 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004797 diag::warn_cxx98_compat_template_arg_extra_parens :
4798 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004799 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004800 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004801 }
4802
4803 Arg = Parens->getSubExpr();
4804 }
4805
John McCall7c454bb2011-07-15 05:09:51 +00004806 while (SubstNonTypeTemplateParmExpr *subst =
4807 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4808 Arg = subst->getReplacement()->IgnoreImpCasts();
4809
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004810 // A pointer-to-member constant written &Class::member.
4811 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004812 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004813 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4814 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004815 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004818 // A constant of pointer-to-member type.
4819 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4820 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4821 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004822 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004823 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004824 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004825 } else {
4826 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004827 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004828 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004829 return Invalid;
4830 }
4831 }
4832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
Craig Topperc3ec1492014-05-26 06:22:03 +00004834 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836
Douglas Gregorccb07762009-02-11 19:52:55 +00004837 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004838 return S.Diag(Arg->getLocStart(),
4839 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004840 << Arg->getSourceRange();
4841
David Majnemer3ac84e62013-10-22 21:56:38 +00004842 if (isa<FieldDecl>(DRE->getDecl()) ||
4843 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4844 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004845 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004846 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004847 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4848 "Only non-static member pointers can make it here");
4849
4850 // Okay: this is the address of a non-static member, and therefore
4851 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004852 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004853 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004854 } else {
4855 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004856 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004857 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004858 return Invalid;
4859 }
4860
4861 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004862 S.Diag(Arg->getLocStart(),
4863 diag::err_template_arg_not_pointer_to_member_form)
4864 << Arg->getSourceRange();
4865 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004866 return true;
4867}
4868
Douglas Gregord32e0282009-02-09 23:23:08 +00004869/// \brief Check a template argument against its corresponding
4870/// non-type template parameter.
4871///
Douglas Gregor463421d2009-03-03 04:44:36 +00004872/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004873/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004874/// returns the converted template argument. \p ParamType is the
4875/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004876ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004877 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004878 TemplateArgument &Converted,
4879 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004880 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004881
Douglas Gregor86560402009-02-10 23:36:10 +00004882 // If either the parameter has a dependent type or the argument is
4883 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004884 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004885 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004886 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004887 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004888 }
Douglas Gregor86560402009-02-10 23:36:10 +00004889
Richard Smithd663fdd2014-12-17 20:42:37 +00004890 // We should have already dropped all cv-qualifiers by now.
4891 assert(!ParamType.hasQualifiers() &&
4892 "non-type template parameter type cannot be qualified");
4893
4894 if (CTAK == CTAK_Deduced &&
4895 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4896 // C++ [temp.deduct.type]p17:
4897 // If, in the declaration of a function template with a non-type
4898 // template-parameter, the non-type template-parameter is used
4899 // in an expression in the function parameter-list and, if the
4900 // corresponding template-argument is deduced, the
4901 // template-argument type shall match the type of the
4902 // template-parameter exactly, except that a template-argument
4903 // deduced from an array bound may be of any integral type.
4904 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4905 << Arg->getType().getUnqualifiedType()
4906 << ParamType.getUnqualifiedType();
4907 Diag(Param->getLocation(), diag::note_template_param_here);
4908 return ExprError();
4909 }
4910
Richard Smith410cc892014-11-26 03:26:53 +00004911 if (getLangOpts().CPlusPlus1z) {
4912 // FIXME: We can do some limited checking for a value-dependent but not
4913 // type-dependent argument.
4914 if (Arg->isValueDependent()) {
4915 Converted = TemplateArgument(Arg);
4916 return Arg;
4917 }
4918
4919 // C++1z [temp.arg.nontype]p1:
4920 // A template-argument for a non-type template parameter shall be
4921 // a converted constant expression of the type of the template-parameter.
4922 APValue Value;
4923 ExprResult ArgResult = CheckConvertedConstantExpression(
4924 Arg, ParamType, Value, CCEK_TemplateArg);
4925 if (ArgResult.isInvalid())
4926 return ExprError();
4927
Richard Smithd663fdd2014-12-17 20:42:37 +00004928 QualType CanonParamType = Context.getCanonicalType(ParamType);
4929
Richard Smith410cc892014-11-26 03:26:53 +00004930 // Convert the APValue to a TemplateArgument.
4931 switch (Value.getKind()) {
4932 case APValue::Uninitialized:
4933 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004934 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004935 break;
4936 case APValue::Int:
4937 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004938 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004939 break;
4940 case APValue::MemberPointer: {
4941 assert(ParamType->isMemberPointerType());
4942
4943 // FIXME: We need TemplateArgument representation and mangling for these.
4944 if (!Value.getMemberPointerPath().empty()) {
4945 Diag(Arg->getLocStart(),
4946 diag::err_template_arg_member_ptr_base_derived_not_supported)
4947 << Value.getMemberPointerDecl() << ParamType
4948 << Arg->getSourceRange();
4949 return ExprError();
4950 }
4951
4952 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004953 Converted = VD ? TemplateArgument(VD, CanonParamType)
4954 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004955 break;
4956 }
4957 case APValue::LValue: {
4958 // For a non-type template-parameter of pointer or reference type,
4959 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004960 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4961 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004962 // -- a temporary object
4963 // -- a string literal
4964 // -- the result of a typeid expression, or
4965 // -- a predefind __func__ variable
4966 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4967 if (isa<CXXUuidofExpr>(E)) {
4968 Converted = TemplateArgument(const_cast<Expr*>(E));
4969 break;
4970 }
4971 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4972 << Arg->getSourceRange();
4973 return ExprError();
4974 }
4975 auto *VD = const_cast<ValueDecl *>(
4976 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4977 // -- a subobject
4978 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4979 VD && VD->getType()->isArrayType() &&
4980 Value.getLValuePath()[0].ArrayIndex == 0 &&
4981 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4982 // Per defect report (no number yet):
4983 // ... other than a pointer to the first element of a complete array
4984 // object.
4985 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4986 Value.isLValueOnePastTheEnd()) {
4987 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4988 << Value.getAsString(Context, ParamType);
4989 return ExprError();
4990 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004991 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004992 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004993 assert((!VD || !ParamType->isNullPtrType()) &&
4994 "non-null value of type nullptr_t?");
4995 Converted = VD ? TemplateArgument(VD, CanonParamType)
4996 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004997 break;
4998 }
4999 case APValue::AddrLabelDiff:
5000 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5001 case APValue::Float:
5002 case APValue::ComplexInt:
5003 case APValue::ComplexFloat:
5004 case APValue::Vector:
5005 case APValue::Array:
5006 case APValue::Struct:
5007 case APValue::Union:
5008 llvm_unreachable("invalid kind for template argument");
5009 }
5010
5011 return ArgResult.get();
5012 }
5013
Douglas Gregor86560402009-02-10 23:36:10 +00005014 // C++ [temp.arg.nontype]p5:
5015 // The following conversions are performed on each expression used
5016 // as a non-type template-argument. If a non-type
5017 // template-argument cannot be converted to the type of the
5018 // corresponding template-parameter then the program is
5019 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005020 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005021 // C++11:
5022 // -- for a non-type template-parameter of integral or
5023 // enumeration type, conversions permitted in a converted
5024 // constant expression are applied.
5025 //
5026 // C++98:
5027 // -- for a non-type template-parameter of integral or
5028 // enumeration type, integral promotions (4.5) and integral
5029 // conversions (4.7) are applied.
5030
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005031 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005032 // We can't check arbitrary value-dependent arguments.
5033 // FIXME: If there's no viable conversion to the template parameter type,
5034 // we should be able to diagnose that prior to instantiation.
5035 if (Arg->isValueDependent()) {
5036 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005037 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005038 }
5039
5040 // C++ [temp.arg.nontype]p1:
5041 // A template-argument for a non-type, non-template template-parameter
5042 // shall be one of:
5043 //
5044 // -- for a non-type template-parameter of integral or enumeration
5045 // type, a converted constant expression of the type of the
5046 // template-parameter; or
5047 llvm::APSInt Value;
5048 ExprResult ArgResult =
5049 CheckConvertedConstantExpression(Arg, ParamType, Value,
5050 CCEK_TemplateArg);
5051 if (ArgResult.isInvalid())
5052 return ExprError();
5053
5054 // Widen the argument value to sizeof(parameter type). This is almost
5055 // always a no-op, except when the parameter type is bool. In
5056 // that case, this may extend the argument from 1 bit to 8 bits.
5057 QualType IntegerType = ParamType;
5058 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5059 IntegerType = Enum->getDecl()->getIntegerType();
5060 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5061
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005062 Converted = TemplateArgument(Context, Value,
5063 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005064 return ArgResult;
5065 }
5066
Richard Smith08b12f12011-10-27 22:11:44 +00005067 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5068 if (ArgResult.isInvalid())
5069 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005070 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005071
5072 QualType ArgType = Arg->getType();
5073
Douglas Gregor86560402009-02-10 23:36:10 +00005074 // C++ [temp.arg.nontype]p1:
5075 // A template-argument for a non-type, non-template
5076 // template-parameter shall be one of:
5077 //
5078 // -- an integral constant-expression of integral or enumeration
5079 // type; or
5080 // -- the name of a non-type template-parameter; or
5081 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005082 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005083 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005084 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005085 diag::err_template_arg_not_integral_or_enumeral)
5086 << ArgType << Arg->getSourceRange();
5087 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005088 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005089 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005090 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5091 QualType T;
5092
5093 public:
5094 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005095
5096 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5097 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005098 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5099 }
5100 } Diagnoser(ArgType);
5101
5102 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005103 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005104 if (!Arg)
5105 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005106 }
5107
Richard Smithd663fdd2014-12-17 20:42:37 +00005108 // From here on out, all we care about is the unqualified form
5109 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005110 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005111
5112 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005113 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005114 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005115 } else if (ParamType->isBooleanType()) {
5116 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005117 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005118 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5119 !ParamType->isEnumeralType()) {
5120 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005121 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005122 } else {
5123 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005124 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005125 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005126 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005127 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005128 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005129 }
5130
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005131 // Add the value of this argument to the list of converted
5132 // arguments. We use the bitwidth and signedness of the template
5133 // parameter.
5134 if (Arg->isValueDependent()) {
5135 // The argument is value-dependent. Create a new
5136 // TemplateArgument with the converted expression.
5137 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005138 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005139 }
5140
Douglas Gregor52aba872009-03-14 00:20:21 +00005141 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005142 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005143 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005144
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005145 if (ParamType->isBooleanType()) {
5146 // Value must be zero or one.
5147 Value = Value != 0;
5148 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5149 if (Value.getBitWidth() != AllowedBits)
5150 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005151 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005152 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005153 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005154
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005156 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005157 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005158 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005159 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005160 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005161
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005162 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005163 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005164 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005165 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005166 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5167 << Arg->getSourceRange();
5168 Diag(Param->getLocation(), diag::note_template_param_here);
5169 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005170
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005171 // Complain if we overflowed the template parameter's type.
5172 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005173 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005174 RequiredBits = OldValue.getActiveBits();
5175 else if (OldValue.isUnsigned())
5176 RequiredBits = OldValue.getActiveBits() + 1;
5177 else
5178 RequiredBits = OldValue.getMinSignedBits();
5179 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005180 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005181 diag::warn_template_arg_too_large)
5182 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5183 << Arg->getSourceRange();
5184 Diag(Param->getLocation(), diag::note_template_param_here);
5185 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005186 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005187
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005188 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005189 ParamType->isEnumeralType()
5190 ? Context.getCanonicalType(ParamType)
5191 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005192 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005193 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005194
Richard Smith08b12f12011-10-27 22:11:44 +00005195 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005196 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5197
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005198 // Handle pointer-to-function, reference-to-function, and
5199 // pointer-to-member-function all in (roughly) the same way.
5200 if (// -- For a non-type template-parameter of type pointer to
5201 // function, only the function-to-pointer conversion (4.3) is
5202 // applied. If the template-argument represents a set of
5203 // overloaded functions (or a pointer to such), the matching
5204 // function is selected from the set (13.4).
5205 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005206 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005207 // -- For a non-type template-parameter of type reference to
5208 // function, no conversions apply. If the template-argument
5209 // represents a set of overloaded functions, the matching
5210 // function is selected from the set (13.4).
5211 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005212 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005213 // -- For a non-type template-parameter of type pointer to
5214 // member function, no conversions apply. If the
5215 // template-argument represents a set of overloaded member
5216 // functions, the matching member function is selected from
5217 // the set (13.4).
5218 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005219 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005220 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005221
Douglas Gregor064fdb22010-04-14 23:11:21 +00005222 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005223 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005224 true,
5225 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005226 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005227 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005228
5229 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5230 ArgType = Arg->getType();
5231 } else
John Wiegley01296292011-04-08 18:41:53 +00005232 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005234
John Wiegley01296292011-04-08 18:41:53 +00005235 if (!ParamType->isMemberPointerType()) {
5236 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5237 ParamType,
5238 Arg, Converted))
5239 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005240 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005241 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005242
Douglas Gregor20fdef32012-04-10 17:08:25 +00005243 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5244 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005245 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005246 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005247 }
5248
Chris Lattner696197c2009-02-20 21:37:53 +00005249 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005250 // -- for a non-type template-parameter of type pointer to
5251 // object, qualification conversions (4.4) and the
5252 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005253 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005254 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005255 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005256
John Wiegley01296292011-04-08 18:41:53 +00005257 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5258 ParamType,
5259 Arg, Converted))
5260 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005261 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005262 }
Mike Stump11289f42009-09-09 15:08:12 +00005263
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005264 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005265 // -- For a non-type template-parameter of type reference to
5266 // object, no conversions apply. The type referred to by the
5267 // reference may be more cv-qualified than the (otherwise
5268 // identical) type of the template-argument. The
5269 // template-parameter is bound directly to the
5270 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005271 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005272 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005273
Douglas Gregor064fdb22010-04-14 23:11:21 +00005274 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005275 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5276 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005277 true,
5278 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005279 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005280 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005281
5282 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5283 ArgType = Arg->getType();
5284 } else
John Wiegley01296292011-04-08 18:41:53 +00005285 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005287
John Wiegley01296292011-04-08 18:41:53 +00005288 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5289 ParamType,
5290 Arg, Converted))
5291 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005292 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005293 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005294
Douglas Gregor20fdef32012-04-10 17:08:25 +00005295 // Deal with parameters of type std::nullptr_t.
5296 if (ParamType->isNullPtrType()) {
5297 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5298 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005299 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005300 }
5301
5302 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5303 case NPV_NotNullPointer:
5304 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5305 << Arg->getType() << ParamType;
5306 Diag(Param->getLocation(), diag::note_template_param_here);
5307 return ExprError();
5308
5309 case NPV_Error:
5310 return ExprError();
5311
5312 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005313 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005314 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5315 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005316 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005317 }
5318 }
5319
Douglas Gregor0e558532009-02-11 16:16:59 +00005320 // -- For a non-type template-parameter of type pointer to data
5321 // member, qualification conversions (4.4) are applied.
5322 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5323
Douglas Gregor20fdef32012-04-10 17:08:25 +00005324 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5325 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005326 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005327 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005328}
5329
5330/// \brief Check a template argument against its corresponding
5331/// template template parameter.
5332///
5333/// This routine implements the semantics of C++ [temp.arg.template].
5334/// It returns true if an error occurred, and false otherwise.
5335bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005336 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005337 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005338 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005339 TemplateDecl *Template = Name.getAsTemplateDecl();
5340 if (!Template) {
5341 // Any dependent template name is fine.
5342 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5343 return false;
5344 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005345
Richard Smith3f1b5d02011-05-05 21:57:07 +00005346 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005347 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005348 // the name of a class template or an alias template, expressed as an
5349 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005350 // primary class templates are considered when matching the
5351 // template template argument with the corresponding parameter;
5352 // partial specializations are not considered even if their
5353 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005354 //
5355 // Note that we also allow template template parameters here, which
5356 // will happen when we are dealing with, e.g., class template
5357 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005358 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005359 !isa<TemplateTemplateParmDecl>(Template) &&
5360 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005361 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005362 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005363 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005364 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005365 << Template;
5366 }
5367
Richard Smith1fde8ec2012-09-07 02:06:42 +00005368 TemplateParameterList *Params = Param->getTemplateParameters();
5369 if (Param->isExpandedParameterPack())
5370 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5371
Douglas Gregor85e0f662009-02-10 00:24:35 +00005372 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005373 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005375 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005376 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005377}
5378
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005379/// \brief Given a non-type template argument that refers to a
5380/// declaration and the type of its corresponding non-type template
5381/// parameter, produce an expression that properly refers to that
5382/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005383ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005384Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5385 QualType ParamType,
5386 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005387 // C++ [temp.param]p8:
5388 //
5389 // A non-type template-parameter of type "array of T" or
5390 // "function returning T" is adjusted to be of type "pointer to
5391 // T" or "pointer to function returning T", respectively.
5392 if (ParamType->isArrayType())
5393 ParamType = Context.getArrayDecayedType(ParamType);
5394 else if (ParamType->isFunctionType())
5395 ParamType = Context.getPointerType(ParamType);
5396
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005397 // For a NULL non-type template argument, return nullptr casted to the
5398 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005399 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005400 return ImpCastExprToType(
5401 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5402 ParamType,
5403 ParamType->getAs<MemberPointerType>()
5404 ? CK_NullToMemberPointer
5405 : CK_NullToPointer);
5406 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005407 assert(Arg.getKind() == TemplateArgument::Declaration &&
5408 "Only declaration template arguments permitted here");
5409
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005410 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005412 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005413 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5414 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005415 // If the value is a class member, we might have a pointer-to-member.
5416 // Determine whether the non-type template template parameter is of
5417 // pointer-to-member type. If so, we need to build an appropriate
5418 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5419 // would refer to the member itself.
5420 if (ParamType->isMemberPointerType()) {
5421 QualType ClassType
5422 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5423 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005424 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005425 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005426 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005427 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005428
5429 // The actual value-ness of this is unimportant, but for
5430 // internal consistency's sake, references to instance methods
5431 // are r-values.
5432 ExprValueKind VK = VK_LValue;
5433 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5434 VK = VK_RValue;
5435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005437 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005438 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005439 Loc,
5440 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005441 if (RefExpr.isInvalid())
5442 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005443
John McCalle3027922010-08-25 11:45:40 +00005444 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005446 // We might need to perform a trailing qualification conversion, since
5447 // the element type on the parameter could be more qualified than the
5448 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005449 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005450 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005451 ParamType.getUnqualifiedType(), false,
5452 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005453 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005454
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005455 assert(!RefExpr.isInvalid() &&
5456 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005457 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005458 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005459 }
5460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005461
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005462 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005463
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005464 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005465 // When the non-type template parameter is a pointer, take the
5466 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005467 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005468 if (RefExpr.isInvalid())
5469 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005470
5471 if (T->isFunctionType() || T->isArrayType()) {
5472 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005473 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005474 if (RefExpr.isInvalid())
5475 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005476
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005477 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479
Douglas Gregorb242683d2010-04-01 18:32:35 +00005480 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005481 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005482 }
5483
John McCall7decc9e2010-11-18 06:31:45 +00005484 ExprValueKind VK = VK_RValue;
5485
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005486 // If the non-type template parameter has reference type, qualify the
5487 // resulting declaration reference with the extra qualifiers on the
5488 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005489 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5490 VK = VK_LValue;
5491 T = Context.getQualifiedType(T,
5492 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005493 } else if (isa<FunctionDecl>(VD)) {
5494 // References to functions are always lvalues.
5495 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005497
John McCall7decc9e2010-11-18 06:31:45 +00005498 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005499}
5500
5501/// \brief Construct a new expression that refers to the given
5502/// integral template argument with the given source-location
5503/// information.
5504///
5505/// This routine takes care of the mapping from an integral template
5506/// argument (which may have any integral type) to the appropriate
5507/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005509Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5510 SourceLocation Loc) {
5511 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005512 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005513 QualType OrigT = Arg.getIntegralType();
5514
5515 // If this is an enum type that we're instantiating, we need to use an integer
5516 // type the same size as the enumerator. We don't want to build an
5517 // IntegerLiteral with enum type. The integer type of an enum type can be of
5518 // any integral type with C++11 enum classes, make sure we create the right
5519 // type of literal for it.
5520 QualType T = OrigT;
5521 if (const EnumType *ET = OrigT->getAs<EnumType>())
5522 T = ET->getDecl()->getIntegerType();
5523
5524 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005525 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005526 // This does not need to handle u8 character literals because those are
5527 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005528 CharacterLiteral::CharacterKind Kind;
5529 if (T->isWideCharType())
5530 Kind = CharacterLiteral::Wide;
5531 else if (T->isChar16Type())
5532 Kind = CharacterLiteral::UTF16;
5533 else if (T->isChar32Type())
5534 Kind = CharacterLiteral::UTF32;
5535 else
5536 Kind = CharacterLiteral::Ascii;
5537
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005538 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5539 Kind, T, Loc);
5540 } else if (T->isBooleanType()) {
5541 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5542 T, Loc);
5543 } else if (T->isNullPtrType()) {
5544 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5545 } else {
5546 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005547 }
5548
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005549 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005550 // FIXME: This is a hack. We need a better way to handle substituted
5551 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005552 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5553 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005554 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005555 Loc, Loc);
5556 }
5557
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005558 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005559}
5560
Douglas Gregor641040a2011-01-12 23:45:44 +00005561/// \brief Match two template parameters within template parameter lists.
5562static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5563 bool Complain,
5564 Sema::TemplateParameterListEqualKind Kind,
5565 SourceLocation TemplateArgLoc) {
5566 // Check the actual kind (type, non-type, template).
5567 if (Old->getKind() != New->getKind()) {
5568 if (Complain) {
5569 unsigned NextDiag = diag::err_template_param_different_kind;
5570 if (TemplateArgLoc.isValid()) {
5571 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5572 NextDiag = diag::note_template_param_different_kind;
5573 }
5574 S.Diag(New->getLocation(), NextDiag)
5575 << (Kind != Sema::TPL_TemplateMatch);
5576 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5577 << (Kind != Sema::TPL_TemplateMatch);
5578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579
Douglas Gregor641040a2011-01-12 23:45:44 +00005580 return false;
5581 }
5582
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005583 // Check that both are parameter packs are neither are parameter packs.
5584 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005585 // template template parameter, the template template parameter can have
5586 // a parameter pack where the template template argument does not.
5587 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5588 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5589 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005590 if (Complain) {
5591 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5592 if (TemplateArgLoc.isValid()) {
5593 S.Diag(TemplateArgLoc,
5594 diag::err_template_arg_template_params_mismatch);
5595 NextDiag = diag::note_template_parameter_pack_non_pack;
5596 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005597
Douglas Gregor641040a2011-01-12 23:45:44 +00005598 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5599 : isa<NonTypeTemplateParmDecl>(New)? 1
5600 : 2;
5601 S.Diag(New->getLocation(), NextDiag)
5602 << ParamKind << New->isParameterPack();
5603 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5604 << ParamKind << Old->isParameterPack();
5605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005606
Douglas Gregor641040a2011-01-12 23:45:44 +00005607 return false;
5608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregor641040a2011-01-12 23:45:44 +00005610 // For non-type template parameters, check the type of the parameter.
5611 if (NonTypeTemplateParmDecl *OldNTTP
5612 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5613 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005614
Douglas Gregor641040a2011-01-12 23:45:44 +00005615 // If we are matching a template template argument to a template
5616 // template parameter and one of the non-type template parameter types
5617 // is dependent, then we must wait until template instantiation time
5618 // to actually compare the arguments.
5619 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5620 (OldNTTP->getType()->isDependentType() ||
5621 NewNTTP->getType()->isDependentType()))
5622 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
Douglas Gregor641040a2011-01-12 23:45:44 +00005624 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5625 if (Complain) {
5626 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5627 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005629 diag::err_template_arg_template_params_mismatch);
5630 NextDiag = diag::note_template_nontype_parm_different_type;
5631 }
5632 S.Diag(NewNTTP->getLocation(), NextDiag)
5633 << NewNTTP->getType()
5634 << (Kind != Sema::TPL_TemplateMatch);
5635 S.Diag(OldNTTP->getLocation(),
5636 diag::note_template_nontype_parm_prev_declaration)
5637 << OldNTTP->getType();
5638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639
Douglas Gregor641040a2011-01-12 23:45:44 +00005640 return false;
5641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005642
Douglas Gregor641040a2011-01-12 23:45:44 +00005643 return true;
5644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005645
Douglas Gregor641040a2011-01-12 23:45:44 +00005646 // For template template parameters, check the template parameter types.
5647 // The template parameter lists of template template
5648 // parameters must agree.
5649 if (TemplateTemplateParmDecl *OldTTP
5650 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005651 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005652 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5653 OldTTP->getTemplateParameters(),
5654 Complain,
5655 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005657 : Kind),
5658 TemplateArgLoc);
5659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregor641040a2011-01-12 23:45:44 +00005661 return true;
5662}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005663
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005664/// \brief Diagnose a known arity mismatch when comparing template argument
5665/// lists.
5666static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005668 TemplateParameterList *New,
5669 TemplateParameterList *Old,
5670 Sema::TemplateParameterListEqualKind Kind,
5671 SourceLocation TemplateArgLoc) {
5672 unsigned NextDiag = diag::err_template_param_list_different_arity;
5673 if (TemplateArgLoc.isValid()) {
5674 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5675 NextDiag = diag::note_template_param_list_different_arity;
5676 }
5677 S.Diag(New->getTemplateLoc(), NextDiag)
5678 << (New->size() > Old->size())
5679 << (Kind != Sema::TPL_TemplateMatch)
5680 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5681 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5682 << (Kind != Sema::TPL_TemplateMatch)
5683 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5684}
5685
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005686/// \brief Determine whether the given template parameter lists are
5687/// equivalent.
5688///
Mike Stump11289f42009-09-09 15:08:12 +00005689/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005690/// source code as part of a new template declaration.
5691///
5692/// \param Old The old template parameter list, typically found via
5693/// name lookup of the template declared with this template parameter
5694/// list.
5695///
5696/// \param Complain If true, this routine will produce a diagnostic if
5697/// the template parameter lists are not equivalent.
5698///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005699/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005700///
5701/// \param TemplateArgLoc If this source location is valid, then we
5702/// are actually checking the template parameter list of a template
5703/// argument (New) against the template parameter list of its
5704/// corresponding template template parameter (Old). We produce
5705/// slightly different diagnostics in this scenario.
5706///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005707/// \returns True if the template parameter lists are equal, false
5708/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005709bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005710Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5711 TemplateParameterList *Old,
5712 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005713 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005714 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005715 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5716 if (Complain)
5717 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5718 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005719
5720 return false;
5721 }
5722
Douglas Gregor641040a2011-01-12 23:45:44 +00005723 // C++0x [temp.arg.template]p3:
5724 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005725 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005726 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005727 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005728 // template-parameter-list of P. [...]
5729 TemplateParameterList::iterator NewParm = New->begin();
5730 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005731 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005732 OldParmEnd = Old->end();
5733 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005734 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5735 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005736 if (NewParm == NewParmEnd) {
5737 if (Complain)
5738 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5739 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005741 return false;
5742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005743
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005744 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5745 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746 return false;
5747
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005748 ++NewParm;
5749 continue;
5750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005752 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005753 // [...] When P's template- parameter-list contains a template parameter
5754 // pack (14.5.3), the template parameter pack will match zero or more
5755 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005756 // template-parameter-list of A with the same type and form as the
5757 // template parameter pack in P (ignoring whether those template
5758 // parameters are template parameter packs).
5759 for (; NewParm != NewParmEnd; ++NewParm) {
5760 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5761 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005762 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005763 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005766 // Make sure we exhausted all of the arguments.
5767 if (NewParm != NewParmEnd) {
5768 if (Complain)
5769 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5770 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005771
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005772 return false;
5773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005775 return true;
5776}
5777
5778/// \brief Check whether a template can be declared within this scope.
5779///
5780/// If the template declaration is valid in this scope, returns
5781/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005782bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005783Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005784 if (!S)
5785 return false;
5786
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005787 // Find the nearest enclosing declaration scope.
5788 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5789 (S->getFlags() & Scope::TemplateParamScope) != 0)
5790 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005791
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005792 // C++ [temp]p4:
5793 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005794 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005795 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005796 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005797 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005798
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005799 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005800 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005801
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005802 // C++ [temp]p2:
5803 // A template-declaration can appear only as a namespace scope or
5804 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005805 if (Ctx) {
5806 if (Ctx->isFileContext())
5807 return false;
5808 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5809 // C++ [temp.mem]p2:
5810 // A local class shall not have member templates.
5811 if (RD->isLocalClass())
5812 return Diag(TemplateParams->getTemplateLoc(),
5813 diag::err_template_inside_local_class)
5814 << TemplateParams->getSourceRange();
5815 else
5816 return false;
5817 }
5818 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005819
Mike Stump11289f42009-09-09 15:08:12 +00005820 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005821 diag::err_template_outside_namespace_or_class_scope)
5822 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005823}
Douglas Gregor67a65642009-02-17 23:15:12 +00005824
Douglas Gregor54888652009-10-07 00:13:32 +00005825/// \brief Determine what kind of template specialization the given declaration
5826/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005827static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005828 if (!D)
5829 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005830
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005831 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5832 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005833 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5834 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005835 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5836 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005837
Douglas Gregor54888652009-10-07 00:13:32 +00005838 return TSK_Undeclared;
5839}
5840
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005841/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005842/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005843///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005844/// This routine determines whether a template specialization can be declared
5845/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005846///
5847/// \param S the semantic analysis object for which this check is being
5848/// performed.
5849///
5850/// \param Specialized the entity being specialized or instantiated, which
5851/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005853/// member class).
5854///
5855/// \param PrevDecl the previous declaration of this entity, if any.
5856///
5857/// \param Loc the location of the explicit specialization or instantiation of
5858/// this entity.
5859///
5860/// \param IsPartialSpecialization whether this is a partial specialization of
5861/// a class template.
5862///
Douglas Gregor54888652009-10-07 00:13:32 +00005863/// \returns true if there was an error that we cannot recover from, false
5864/// otherwise.
5865static bool CheckTemplateSpecializationScope(Sema &S,
5866 NamedDecl *Specialized,
5867 NamedDecl *PrevDecl,
5868 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005869 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005870 // Keep these "kind" numbers in sync with the %select statements in the
5871 // various diagnostics emitted by this routine.
5872 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005873 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005874 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005875 else if (isa<VarTemplateDecl>(Specialized))
5876 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005877 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005878 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005879 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005880 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005881 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005882 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005883 else if (isa<RecordDecl>(Specialized))
5884 EntityKind = 7;
5885 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5886 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005887 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005888 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005889 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005890 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005891 return true;
5892 }
5893
Douglas Gregorf47b9112009-02-25 22:02:03 +00005894 // C++ [temp.expl.spec]p2:
5895 // An explicit specialization shall be declared in the namespace
5896 // of which the template is a member, or, for member templates, in
5897 // the namespace of which the enclosing class or enclosing class
5898 // template is a member. An explicit specialization of a member
5899 // function, member class or static data member of a class
5900 // template shall be declared in the namespace of which the class
5901 // template is a member. Such a declaration may also be a
5902 // definition. If the declaration is not a definition, the
5903 // specialization may be defined later in the name- space in which
5904 // the explicit specialization was declared, or in a namespace
5905 // that encloses the one in which the explicit specialization was
5906 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005907 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005908 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005909 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005910 return true;
5911 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005912
Douglas Gregor40fb7442009-10-07 17:30:37 +00005913 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005914 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005915 // Do not warn for class scope explicit specialization during
5916 // instantiation, warning was already emitted during pattern
5917 // semantic analysis.
5918 if (!S.ActiveTemplateInstantiations.size())
5919 S.Diag(Loc, diag::ext_function_specialization_in_class)
5920 << Specialized;
5921 } else {
5922 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5923 << Specialized;
5924 return true;
5925 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005927
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005928 if (S.CurContext->isRecord() &&
5929 !S.CurContext->Equals(Specialized->getDeclContext())) {
5930 // Make sure that we're specializing in the right record context.
5931 // Otherwise, things can go horribly wrong.
5932 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5933 << Specialized;
5934 return true;
5935 }
5936
Douglas Gregore4b05162009-10-07 17:21:34 +00005937 // C++ [temp.class.spec]p6:
5938 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005939 // in any namespace scope in which its definition may be defined (14.5.1
5940 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005941 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005942 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005943 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005944
5945 // Make sure that this redeclaration (or definition) occurs in an enclosing
5946 // namespace.
5947 // Note that HandleDeclarator() performs this check for explicit
5948 // specializations of function templates, static data members, and member
5949 // functions, so we skip the check here for those kinds of entities.
5950 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5951 // Should we refactor that check, so that it occurs later?
5952 if (!DC->Encloses(SpecializedContext) &&
5953 !(isa<FunctionTemplateDecl>(Specialized) ||
5954 isa<FunctionDecl>(Specialized) ||
5955 isa<VarTemplateDecl>(Specialized) ||
5956 isa<VarDecl>(Specialized))) {
5957 if (isa<TranslationUnitDecl>(SpecializedContext))
5958 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5959 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005960 else if (isa<NamespaceDecl>(SpecializedContext)) {
5961 int Diag = diag::err_template_spec_redecl_out_of_scope;
5962 if (S.getLangOpts().MicrosoftExt)
5963 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5964 S.Diag(Loc, Diag) << EntityKind << Specialized
5965 << cast<NamedDecl>(SpecializedContext);
5966 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005967 llvm_unreachable("unexpected namespace context for specialization");
5968
5969 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5970 } else if ((!PrevDecl ||
5971 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5972 getTemplateSpecializationKind(PrevDecl) ==
5973 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005974 // C++ [temp.exp.spec]p2:
5975 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005976 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005977 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005978 // An explicit specialization of a member function, member class or
5979 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005980 // namespace of which the class template is a member.
5981 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005982 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005983 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005984 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005985 // C++11 [temp.explicit]p3:
5986 // An explicit instantiation shall appear in an enclosing namespace of its
5987 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005988 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005989 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005990 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005991 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005992 "DC encloses TU but isn't in enclosing namespace set");
5993 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005994 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005995 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5996 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005997 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005998 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005999 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006000 Diag = diag::ext_template_spec_decl_out_of_scope;
6001 else
6002 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6003 S.Diag(Loc, Diag)
6004 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006006
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006007 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006008 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006010
Douglas Gregorf47b9112009-02-25 22:02:03 +00006011 return false;
6012}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006013
Richard Smith6056d5e2014-02-09 00:54:43 +00006014static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6015 if (!E->isInstantiationDependent())
6016 return SourceLocation();
6017 DependencyChecker Checker(Depth);
6018 Checker.TraverseStmt(E);
6019 if (Checker.Match && Checker.MatchLoc.isInvalid())
6020 return E->getSourceRange();
6021 return Checker.MatchLoc;
6022}
6023
6024static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6025 if (!TL.getType()->isDependentType())
6026 return SourceLocation();
6027 DependencyChecker Checker(Depth);
6028 Checker.TraverseTypeLoc(TL);
6029 if (Checker.Match && Checker.MatchLoc.isInvalid())
6030 return TL.getSourceRange();
6031 return Checker.MatchLoc;
6032}
6033
Larisse Voufo39a1e502013-08-06 01:03:05 +00006034/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006035/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006036static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006037 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6038 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006039 for (unsigned I = 0; I != NumArgs; ++I) {
6040 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006041 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006042 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6043 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006044 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006045
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006046 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006048
Eli Friedmanb826a002012-09-26 02:36:12 +00006049 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006050 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006051
6052 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006053
Douglas Gregor98318c22011-01-03 21:37:45 +00006054 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006055 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6056 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006057
6058 // Strip off any implicit casts we added as part of type checking.
6059 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6060 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006061
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006062 // C++ [temp.class.spec]p8:
6063 // A non-type argument is non-specialized if it is the name of a
6064 // non-type parameter. All other non-type arguments are
6065 // specialized.
6066 //
6067 // Below, we check the two conditions that only apply to
6068 // specialized non-type arguments, so skip any non-specialized
6069 // arguments.
6070 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006071 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006072 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006073
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006074 // C++ [temp.class.spec]p9:
6075 // Within the argument list of a class template partial
6076 // specialization, the following restrictions apply:
6077 // -- A partially specialized non-type argument expression
6078 // shall not involve a template parameter of the partial
6079 // specialization except when the argument expression is a
6080 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006081 SourceRange ParamUseRange =
6082 findTemplateParameter(Param->getDepth(), ArgExpr);
6083 if (ParamUseRange.isValid()) {
6084 if (IsDefaultArgument) {
6085 S.Diag(TemplateNameLoc,
6086 diag::err_dependent_non_type_arg_in_partial_spec);
6087 S.Diag(ParamUseRange.getBegin(),
6088 diag::note_dependent_non_type_default_arg_in_partial_spec)
6089 << ParamUseRange;
6090 } else {
6091 S.Diag(ParamUseRange.getBegin(),
6092 diag::err_dependent_non_type_arg_in_partial_spec)
6093 << ParamUseRange;
6094 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006095 return true;
6096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006097
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006098 // -- The type of a template parameter corresponding to a
6099 // specialized non-type argument shall not be dependent on a
6100 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006101 //
6102 // FIXME: We need to delay this check until instantiation in some cases:
6103 //
6104 // template<template<typename> class X> struct A {
6105 // template<typename T, X<T> N> struct B;
6106 // template<typename T> struct B<T, 0>;
6107 // };
6108 // template<typename> using X = int;
6109 // A<X>::B<int, 0> b;
6110 ParamUseRange = findTemplateParameter(
6111 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6112 if (ParamUseRange.isValid()) {
6113 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6114 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6115 << Param->getType() << ParamUseRange;
6116 S.Diag(Param->getLocation(), diag::note_template_param_here)
6117 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006118 return true;
6119 }
6120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006121
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006122 return false;
6123}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006124
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006125/// \brief Check the non-type template arguments of a class template
6126/// partial specialization according to C++ [temp.class.spec]p9.
6127///
Richard Smith6056d5e2014-02-09 00:54:43 +00006128/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006129/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006130/// template.
6131/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006132/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006133/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006134///
Richard Smith6056d5e2014-02-09 00:54:43 +00006135/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006136static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006137 Sema &S, SourceLocation TemplateNameLoc,
6138 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006139 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006140 const TemplateArgument *ArgList = TemplateArgs.data();
6141
6142 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6143 NonTypeTemplateParmDecl *Param
6144 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6145 if (!Param)
6146 continue;
6147
Richard Smith6056d5e2014-02-09 00:54:43 +00006148 if (CheckNonTypeTemplatePartialSpecializationArgs(
6149 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006150 return true;
6151 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006152
6153 return false;
6154}
6155
John McCall48871652010-08-21 09:40:31 +00006156DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006157Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6158 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006159 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006160 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006161 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006162 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006163 MultiTemplateParamsArg
6164 TemplateParameterLists,
6165 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006166 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006167
Richard Smith4b55a9c2014-04-17 03:29:33 +00006168 CXXScopeSpec &SS = TemplateId.SS;
6169
Abramo Bagnara60804e12011-03-18 15:16:37 +00006170 // NOTE: KWLoc is the location of the tag keyword. This will instead
6171 // store the location of the outermost template keyword in the declaration.
6172 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006173 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6174 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6175 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6176 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006177
Douglas Gregor67a65642009-02-17 23:15:12 +00006178 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006179 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006180 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006181 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6182
6183 if (!ClassTemplate) {
6184 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006185 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006186 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6187 return true;
6188 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006189
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006190 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006191 bool isPartialSpecialization = false;
6192
Douglas Gregorf47b9112009-02-25 22:02:03 +00006193 // Check the validity of the template headers that introduce this
6194 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006195 // FIXME: We probably shouldn't complain about these headers for
6196 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006197 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006198 TemplateParameterList *TemplateParams =
6199 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006200 KWLoc, TemplateNameLoc, SS, &TemplateId,
6201 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6202 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006203 if (Invalid)
6204 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006205
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006206 if (TemplateParams && TemplateParams->size() > 0) {
6207 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006208
Douglas Gregorec9518b2010-12-21 08:14:57 +00006209 if (TUK == TUK_Friend) {
6210 Diag(KWLoc, diag::err_partial_specialization_friend)
6211 << SourceRange(LAngleLoc, RAngleLoc);
6212 return true;
6213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006214
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006215 // C++ [temp.class.spec]p10:
6216 // The template parameter list of a specialization shall not
6217 // contain default template argument values.
6218 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6219 Decl *Param = TemplateParams->getParam(I);
6220 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6221 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006222 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006223 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006224 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006225 }
6226 } else if (NonTypeTemplateParmDecl *NTTP
6227 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6228 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006229 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006230 diag::err_default_arg_in_partial_spec)
6231 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006232 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006233 }
6234 } else {
6235 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006236 if (TTP->hasDefaultArgument()) {
6237 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006238 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006239 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006240 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006241 }
6242 }
6243 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006244 } else if (TemplateParams) {
6245 if (TUK == TUK_Friend)
6246 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006247 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006248 SourceRange(TemplateParams->getTemplateLoc(),
6249 TemplateParams->getRAngleLoc()))
6250 << SourceRange(LAngleLoc, RAngleLoc);
6251 else
6252 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006253 } else {
6254 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006255 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006256
Douglas Gregor67a65642009-02-17 23:15:12 +00006257 // Check that the specialization uses the same tag kind as the
6258 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006259 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6260 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006261 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006262 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006263 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006264 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006265 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006266 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006267 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006268 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006269 diag::note_previous_use);
6270 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6271 }
6272
Douglas Gregorc40290e2009-03-09 23:48:35 +00006273 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006274 TemplateArgumentListInfo TemplateArgs =
6275 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006276
Douglas Gregor14406932011-01-03 20:35:03 +00006277 // Check for unexpanded parameter packs in any of the template arguments.
6278 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006279 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006280 UPPC_PartialSpecialization))
6281 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006282
Douglas Gregor67a65642009-02-17 23:15:12 +00006283 // Check that the template argument list is well-formed for this
6284 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006285 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006286 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6287 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006288 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006289
Douglas Gregor2373c592009-05-31 09:31:02 +00006290 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006291 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006292 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006293 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006294 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6295 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006296 return true;
6297
Douglas Gregor678d76c2011-07-01 01:22:09 +00006298 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006299 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006300 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006301 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006302 TemplateArgs.size(),
6303 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006304 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6305 << ClassTemplate->getDeclName();
6306 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006307 }
6308 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006309
Craig Topperc3ec1492014-05-26 06:22:03 +00006310 void *InsertPos = nullptr;
6311 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006312
6313 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006314 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006315 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006316 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006317 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006318
Craig Topperc3ec1492014-05-26 06:22:03 +00006319 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006320
Douglas Gregorf47b9112009-02-25 22:02:03 +00006321 // Check whether we can declare a class template specialization in
6322 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006323 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006324 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6325 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006326 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006327 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006328
Douglas Gregor15301382009-07-30 17:40:51 +00006329 // The canonical type
6330 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006331 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006332 // Build the canonical type that describes the converted template
6333 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006334 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6335 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006336 Converted.data(),
6337 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006338
6339 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006340 ClassTemplate->getInjectedClassNameSpecialization())) {
6341 // C++ [temp.class.spec]p9b3:
6342 //
6343 // -- The argument list of the specialization shall not be identical
6344 // to the implicit argument list of the primary template.
6345 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006346 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006347 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006348 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6349 ClassTemplate->getIdentifier(),
6350 TemplateNameLoc,
6351 Attr,
6352 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006353 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006354 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006355 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006356 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006357 }
Douglas Gregor15301382009-07-30 17:40:51 +00006358
Douglas Gregor2373c592009-05-31 09:31:02 +00006359 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006360 ClassTemplatePartialSpecializationDecl *PrevPartial
6361 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006362 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006363 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006364 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006365 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006366 TemplateParams,
6367 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006368 Converted.data(),
6369 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006370 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006371 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006372 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006373 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006374 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006375 Partial->setTemplateParameterListsInfo(
6376 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006377 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006378
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006379 if (!PrevPartial)
6380 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006381 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006382
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006383 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006384 // template specialization, make a note of that.
6385 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6386 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006387
Douglas Gregor91772d12009-06-13 00:26:55 +00006388 // Check that all of the template parameters of the class template
6389 // partial specialization are deducible from the template
6390 // arguments. If not, this class template partial specialization
6391 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006392 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006393 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006394 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006395 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006396
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006397 if (!DeducibleParams.all()) {
6398 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006399 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006400 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006401 << SourceRange(TemplateNameLoc, RAngleLoc);
6402 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6403 if (!DeducibleParams[I]) {
6404 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6405 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006406 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006407 diag::note_partial_spec_unused_parameter)
6408 << Param->getDeclName();
6409 else
Mike Stump11289f42009-09-09 15:08:12 +00006410 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006411 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006412 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006413 }
6414 }
6415 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006416 } else {
6417 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006418 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006419 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006420 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006421 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006422 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006423 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006424 Converted.data(),
6425 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006426 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006427 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006428 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006429 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006430 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006431 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006432
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006433 if (!PrevDecl)
6434 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006435
David Majnemer678f50b2015-11-18 19:49:19 +00006436 if (CurContext->isDependentContext()) {
6437 // -fms-extensions permits specialization of nested classes without
6438 // fully specializing the outer class(es).
6439 assert(getLangOpts().MicrosoftExt &&
6440 "Only possible with -fms-extensions!");
6441 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6442 CanonType = Context.getTemplateSpecializationType(
6443 CanonTemplate, Converted.data(), Converted.size());
6444 } else {
6445 CanonType = Context.getTypeDeclType(Specialization);
6446 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006447 }
6448
Douglas Gregor06db9f52009-10-12 20:18:28 +00006449 // C++ [temp.expl.spec]p6:
6450 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006451 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006452 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006454 // use occurs; no diagnostic is required.
6455 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006456 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006457 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006458 // Is there any previous explicit specialization declaration?
6459 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6460 Okay = true;
6461 break;
6462 }
6463 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006464
Douglas Gregorc854c662010-02-26 06:03:23 +00006465 if (!Okay) {
6466 SourceRange Range(TemplateNameLoc, RAngleLoc);
6467 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6468 << Context.getTypeDeclType(Specialization) << Range;
6469
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006470 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006471 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006473 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006474 return true;
6475 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477
Douglas Gregor2208a292009-09-26 20:57:03 +00006478 // If this is not a friend, note that this is an explicit specialization.
6479 if (TUK != TUK_Friend)
6480 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006481
6482 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006483 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006484 RecordDecl *Def = Specialization->getDefinition();
6485 NamedDecl *Hidden = nullptr;
6486 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6487 SkipBody->ShouldSkip = true;
6488 makeMergedDefinitionVisible(Hidden, KWLoc);
6489 // From here on out, treat this as just a redeclaration.
6490 TUK = TUK_Declaration;
6491 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006492 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006493 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006494 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006495 Diag(Def->getLocation(), diag::note_previous_definition);
6496 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006497 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006498 }
6499 }
6500
John McCall659a3372010-12-18 03:30:47 +00006501 if (Attr)
6502 ProcessDeclAttributeList(S, Specialization, Attr);
6503
Richard Smith034b94a2012-08-17 03:20:55 +00006504 // Add alignment attributes if necessary; these attributes are checked when
6505 // the ASTContext lays out the structure.
6506 if (TUK == TUK_Definition) {
6507 AddAlignmentAttributesForRecord(Specialization);
6508 AddMsStructLayoutForRecord(Specialization);
6509 }
6510
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006511 if (ModulePrivateLoc.isValid())
6512 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6513 << (isPartialSpecialization? 1 : 0)
6514 << FixItHint::CreateRemoval(ModulePrivateLoc);
6515
Douglas Gregord56a91e2009-02-26 22:19:44 +00006516 // Build the fully-sugared type for this class template
6517 // specialization as the user wrote in the specialization
6518 // itself. This means that we'll pretty-print the type retrieved
6519 // from the specialization's declaration the way that the user
6520 // actually wrote the specialization, rather than formatting the
6521 // name based on the "canonical" representation used to store the
6522 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006523 TypeSourceInfo *WrittenTy
6524 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6525 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006526 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006527 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006528 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006529 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006530
Douglas Gregor1e249f82009-02-25 22:18:32 +00006531 // C++ [temp.expl.spec]p9:
6532 // A template explicit specialization is in the scope of the
6533 // namespace in which the template was defined.
6534 //
6535 // We actually implement this paragraph where we set the semantic
6536 // context (in the creation of the ClassTemplateSpecializationDecl),
6537 // but we also maintain the lexical context where the actual
6538 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006539 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006540
Douglas Gregor67a65642009-02-17 23:15:12 +00006541 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006542 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006543 Specialization->startDefinition();
6544
Douglas Gregor2208a292009-09-26 20:57:03 +00006545 if (TUK == TUK_Friend) {
6546 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6547 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006548 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006549 /*FIXME:*/KWLoc);
6550 Friend->setAccess(AS_public);
6551 CurContext->addDecl(Friend);
6552 } else {
6553 // Add the specialization into its lexical context, so that it can
6554 // be seen when iterating through the list of declarations in that
6555 // context. However, specializations are not found by name lookup.
6556 CurContext->addDecl(Specialization);
6557 }
John McCall48871652010-08-21 09:40:31 +00006558 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006559}
Douglas Gregor333489b2009-03-27 23:10:48 +00006560
John McCall48871652010-08-21 09:40:31 +00006561Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006562 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006563 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006564 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006565 ActOnDocumentableDecl(NewDecl);
6566 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006567}
6568
John McCall4f7ced62010-02-11 01:33:53 +00006569/// \brief Strips various properties off an implicit instantiation
6570/// that has just been explicitly specialized.
6571static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006572 D->dropAttr<DLLImportAttr>();
6573 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006574
Nico Webere4974382014-12-19 23:52:45 +00006575 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006576 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006577}
6578
Nico Webera8f80b32012-01-09 19:52:25 +00006579/// \brief Compute the diagnostic location for an explicit instantiation
6580// declaration or definition.
6581static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006582 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006583 // Explicit instantiations following a specialization have no effect and
6584 // hence no PointOfInstantiation. In that case, walk decl backwards
6585 // until a valid name loc is found.
6586 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006587 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6588 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006589 PrevDiagLoc = Prev->getLocation();
6590 }
6591 assert(PrevDiagLoc.isValid() &&
6592 "Explicit instantiation without point of instantiation?");
6593 return PrevDiagLoc;
6594}
6595
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006597/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006598/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006599/// new specialization/instantiation will have any effect.
6600///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006602/// instantiation.
6603///
6604/// \param NewTSK the kind of the new explicit specialization or instantiation.
6605///
6606/// \param PrevDecl the previous declaration of the entity.
6607///
6608/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6609///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006611/// declaration was instantiated (either implicitly or explicitly).
6612///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006613/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006614/// specialization or instantiation has no effect and should be ignored.
6615///
6616/// \returns true if there was an error that should prevent the introduction of
6617/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006618bool
6619Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6620 TemplateSpecializationKind NewTSK,
6621 NamedDecl *PrevDecl,
6622 TemplateSpecializationKind PrevTSK,
6623 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006624 bool &HasNoEffect) {
6625 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006626
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006627 switch (NewTSK) {
6628 case TSK_Undeclared:
6629 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006630 assert(
6631 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6632 "previous declaration must be implicit!");
6633 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006635 case TSK_ExplicitSpecialization:
6636 switch (PrevTSK) {
6637 case TSK_Undeclared:
6638 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006640 // explicitly specialized or has merely been mentioned without any
6641 // instantiation.
6642 return false;
6643
6644 case TSK_ImplicitInstantiation:
6645 if (PrevPointOfInstantiation.isInvalid()) {
6646 // The declaration itself has not actually been instantiated, so it is
6647 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006648 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006649 return false;
6650 }
6651 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006653 case TSK_ExplicitInstantiationDeclaration:
6654 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006655 assert((PrevTSK == TSK_ImplicitInstantiation ||
6656 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006657 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006659 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006661 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006662 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006663 // implicit instantiation to take place, in every translation unit in
6664 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006665 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006666 // Is there any previous explicit specialization declaration?
6667 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6668 return false;
6669 }
6670
Douglas Gregor1d957a32009-10-27 18:42:08 +00006671 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006672 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006673 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006674 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006675
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006676 return true;
6677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006679 case TSK_ExplicitInstantiationDeclaration:
6680 switch (PrevTSK) {
6681 case TSK_ExplicitInstantiationDeclaration:
6682 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006683 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006684 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006685
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006686 case TSK_Undeclared:
6687 case TSK_ImplicitInstantiation:
6688 // We're explicitly instantiating something that may have already been
6689 // implicitly instantiated; that's fine.
6690 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006691
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006692 case TSK_ExplicitSpecialization:
6693 // C++0x [temp.explicit]p4:
6694 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006695 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006696 // specialization for that template, the explicit instantiation has no
6697 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006698 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006699 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006700
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006701 case TSK_ExplicitInstantiationDefinition:
6702 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703 // If an entity is the subject of both an explicit instantiation
6704 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006705 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006706 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006707 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006708
6709 // Explicit instantiations following a specialization have no effect and
6710 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6711 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006712 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6713 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006714 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006715 return false;
6716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006718 case TSK_ExplicitInstantiationDefinition:
6719 switch (PrevTSK) {
6720 case TSK_Undeclared:
6721 case TSK_ImplicitInstantiation:
6722 // We're explicitly instantiating something that may have already been
6723 // implicitly instantiated; that's fine.
6724 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006725
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006726 case TSK_ExplicitSpecialization:
6727 // C++ DR 259, C++0x [temp.explicit]p4:
6728 // For a given set of template parameters, if an explicit
6729 // instantiation of a template appears after a declaration of
6730 // an explicit specialization for that template, the explicit
6731 // instantiation has no effect.
6732 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006733 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006734 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006735 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006736 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006737 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6738 diag::ext_explicit_instantiation_after_specialization)
6739 << PrevDecl;
6740 Diag(PrevDecl->getLocation(),
6741 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006742 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006743 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006744
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006745 case TSK_ExplicitInstantiationDeclaration:
6746 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006748
6749 // C++0x [temp.explicit]p4:
6750 // For a given set of template parameters, if an explicit instantiation
6751 // of a template appears after a declaration of an explicit
6752 // specialization for that template, the explicit instantiation has no
6753 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006754 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006755 // Is there any previous explicit specialization declaration?
6756 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6757 HasNoEffect = true;
6758 break;
6759 }
6760 }
6761
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006762 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006764 case TSK_ExplicitInstantiationDefinition:
6765 // C++0x [temp.spec]p5:
6766 // For a given template and a given set of template-arguments,
6767 // - an explicit instantiation definition shall appear at most once
6768 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006769
6770 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6771 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006772 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006773 : diag::err_explicit_instantiation_duplicate)
6774 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006775 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006776 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006777 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006778 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006779 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006781
David Blaikie83d382b2011-09-23 05:06:16 +00006782 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006783}
6784
John McCallb9c78482010-04-08 09:05:18 +00006785/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006786/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006787///
James Dennettf14a6e52012-06-15 22:23:43 +00006788/// The only possible way to get a dependent function template specialization
6789/// is with a friend declaration, like so:
6790///
6791/// \code
6792/// template \<class T> void foo(T);
6793/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006794/// friend void foo<>(T);
6795/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006796/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006797///
6798/// There really isn't any useful analysis we can do here, so we
6799/// just store the information.
6800bool
6801Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6802 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6803 LookupResult &Previous) {
6804 // Remove anything from Previous that isn't a function template in
6805 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006806 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006807 LookupResult::Filter F = Previous.makeFilter();
6808 while (F.hasNext()) {
6809 NamedDecl *D = F.next()->getUnderlyingDecl();
6810 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006811 !FDLookupContext->InEnclosingNamespaceSetOf(
6812 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006813 F.erase();
6814 }
6815 F.done();
6816
6817 // Should this be diagnosed here?
6818 if (Previous.empty()) return true;
6819
6820 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6821 ExplicitTemplateArgs);
6822 return false;
6823}
6824
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006825/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006826/// specialization.
6827///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006828/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006829/// explicit function template specialization. On successful completion,
6830/// the function declaration \p FD will become a function template
6831/// specialization.
6832///
6833/// \param FD the function declaration, which will be updated to become a
6834/// function template specialization.
6835///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006836/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6837/// if any. Note that this may be valid info even when 0 arguments are
6838/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6839/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006840///
Francois Pichet3a44e432011-07-08 06:21:47 +00006841/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006842/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006843bool Sema::CheckFunctionTemplateSpecialization(
6844 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6845 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006846 // The set of function template specializations that could match this
6847 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006848 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006849 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6850 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006851
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006852 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6853 ConvertedTemplateArgs;
6854
Sebastian Redl50c68252010-08-31 00:36:30 +00006855 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006856 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6857 I != E; ++I) {
6858 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6859 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006861 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006862 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6863 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006864 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006865
Richard Smith574f4f62013-01-14 05:37:29 +00006866 // When matching a constexpr member function template specialization
6867 // against the primary template, we don't yet know whether the
6868 // specialization has an implicit 'const' (because we don't know whether
6869 // it will be a static member function until we know which template it
6870 // specializes), so adjust it now assuming it specializes this template.
6871 QualType FT = FD->getType();
6872 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006873 CXXMethodDecl *OldMD =
6874 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006875 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006876 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006877 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6878 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006879 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006880 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006881 }
6882 }
6883
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006884 TemplateArgumentListInfo Args;
6885 if (ExplicitTemplateArgs)
6886 Args = *ExplicitTemplateArgs;
6887
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006888 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889 // A trailing template-argument can be left unspecified in the
6890 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006891 // provided it can be deduced from the function argument type.
6892 // Perform template argument deduction to determine whether we may be
6893 // specializing this template.
6894 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006895 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006896 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006897 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6898 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00006899 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
6900 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006901 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006902 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00006903 FailedCandidates.addCandidate().set(
6904 I.getPair(), FunTmpl->getTemplatedDecl(),
6905 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006906 (void)TDK;
6907 continue;
6908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006909
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006910 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006911 if (ExplicitTemplateArgs)
6912 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006913 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006914 }
6915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916
Douglas Gregor5de279c2009-09-26 03:41:46 +00006917 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006918 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006919 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006920 FD->getLocation(),
6921 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6922 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006923 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006924 PDiag(diag::note_function_template_spec_matched));
6925
John McCall58cc69d2010-01-27 01:50:18 +00006926 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006927 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006928
6929 // Ignore access information; it doesn't figure into redeclaration checking.
6930 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006931
Nathan Wilson83839122016-04-09 02:55:27 +00006932 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6933 // an explicit specialization (14.8.3) [...] of a concept definition.
6934 if (Specialization->getPrimaryTemplate()->isConcept()) {
6935 Diag(FD->getLocation(), diag::err_concept_specialized)
6936 << 0 /*function*/ << 1 /*explicitly specialized*/;
6937 Diag(Specialization->getLocation(), diag::note_previous_declaration);
6938 return true;
6939 }
6940
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006941 FunctionTemplateSpecializationInfo *SpecInfo
6942 = Specialization->getTemplateSpecializationInfo();
6943 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006944
6945 // Note: do not overwrite location info if previous template
6946 // specialization kind was explicit.
6947 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006948 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006949 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006950 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6951 // function can differ from the template declaration with respect to
6952 // the constexpr specifier.
6953 Specialization->setConstexpr(FD->isConstexpr());
6954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006955
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006956 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006957 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006958
6959 // If this is a friend declaration, then we're not really declaring
6960 // an explicit specialization.
6961 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregor54888652009-10-07 00:13:32 +00006963 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006964 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006966 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006968 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006969 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006970
6971 // C++ [temp.expl.spec]p6:
6972 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006973 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006974 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006976 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006977 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006978 if (!isFriend &&
6979 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006980 TSK_ExplicitSpecialization,
6981 Specialization,
6982 SpecInfo->getTemplateSpecializationKind(),
6983 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006984 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006985 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006986
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006987 // Mark the prior declaration as an explicit specialization, so that later
6988 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006989 if (!isFriend) {
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00006990 // Explicit specializations do not inherit '=delete' from their primary
6991 // function template.
6992 if (Specialization->isDeleted()) {
6993 assert(!SpecInfo->isExplicitSpecialization());
6994 assert(Specialization->getCanonicalDecl() == Specialization);
6995 Specialization->setDeletedAsWritten(false);
6996 }
John McCall816d75b2010-03-24 07:46:06 +00006997 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006998 MarkUnusedFileScopedDecl(Specialization);
6999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007000
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007001 // Turn the given function declaration into a function template
7002 // specialization, with the template arguments from the previous
7003 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007004 // Take copies of (semantic and syntactic) template argument lists.
7005 const TemplateArgumentList* TemplArgs = new (Context)
7006 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007007 FD->setFunctionTemplateSpecialization(
7008 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7009 SpecInfo->getTemplateSpecializationKind(),
7010 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007011
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007012 // The "previous declaration" for this function template specialization is
7013 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007014 Previous.clear();
7015 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007016 return false;
7017}
7018
Douglas Gregor86d142a2009-10-08 07:24:58 +00007019/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007020/// specialization.
7021///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007023/// explicit member function specialization. On successful completion,
7024/// the function declaration \p FD will become a member function
7025/// specialization.
7026///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007027/// \param Member the member declaration, which will be updated to become a
7028/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007029///
John McCall1f82f242009-11-18 22:49:29 +00007030/// \param Previous the set of declarations, one of which may be specialized
7031/// by this function specialization; the set will be modified to contain the
7032/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007033bool
John McCall1f82f242009-11-18 22:49:29 +00007034Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007035 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007036
Douglas Gregor86d142a2009-10-08 07:24:58 +00007037 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007038 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007039 NamedDecl *Instantiation = nullptr;
7040 NamedDecl *InstantiatedFrom = nullptr;
7041 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007042
John McCall1f82f242009-11-18 22:49:29 +00007043 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007044 // Nowhere to look anyway.
7045 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007046 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7047 I != E; ++I) {
7048 NamedDecl *D = (*I)->getUnderlyingDecl();
7049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007050 QualType Adjusted = Function->getType();
7051 if (!hasExplicitCallingConv(Adjusted))
7052 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7053 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007054 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007055 Instantiation = Method;
7056 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007057 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007058 break;
7059 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007060 }
7061 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007062 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007063 VarDecl *PrevVar;
7064 if (Previous.isSingleResult() &&
7065 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007066 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007067 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007068 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007069 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007070 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007071 }
7072 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007073 CXXRecordDecl *PrevRecord;
7074 if (Previous.isSingleResult() &&
7075 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007076 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007077 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007078 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007079 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007080 }
Richard Smith7d137e32012-03-23 03:33:32 +00007081 } else if (isa<EnumDecl>(Member)) {
7082 EnumDecl *PrevEnum;
7083 if (Previous.isSingleResult() &&
7084 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007085 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007086 Instantiation = PrevEnum;
7087 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7088 MSInfo = PrevEnum->getMemberSpecializationInfo();
7089 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007092 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007093 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007094 // specializations are always out-of-line, the caller will complain about
7095 // this mismatch later.
7096 return false;
7097 }
John McCalle820e5e2010-04-13 20:37:33 +00007098
7099 // If this is a friend, just bail out here before we start turning
7100 // things into explicit specializations.
7101 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7102 // Preserve instantiation information.
7103 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7104 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7105 cast<CXXMethodDecl>(InstantiatedFrom),
7106 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7107 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7108 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7109 cast<CXXRecordDecl>(InstantiatedFrom),
7110 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7111 }
7112
7113 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007114 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007115 return false;
7116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117
Douglas Gregor86d142a2009-10-08 07:24:58 +00007118 // Make sure that this is a specialization of a member.
7119 if (!InstantiatedFrom) {
7120 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7121 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007122 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7123 return true;
7124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007125
Douglas Gregor06db9f52009-10-12 20:18:28 +00007126 // C++ [temp.expl.spec]p6:
7127 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007128 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007129 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007131 // use occurs; no diagnostic is required.
7132 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007133
Abramo Bagnara8075c852010-06-12 07:44:57 +00007134 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007135 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7136 TSK_ExplicitSpecialization,
7137 Instantiation,
7138 MSInfo->getTemplateSpecializationKind(),
7139 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007140 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007141 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007142
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007143 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007144 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007145 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007146 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007147 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007148 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007149
Douglas Gregor86d142a2009-10-08 07:24:58 +00007150 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007151 // the original declaration to note that it is an explicit specialization
7152 // (if it was previously an implicit instantiation). This latter step
7153 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007154 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007155 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7156 if (InstantiationFunction->getTemplateSpecializationKind() ==
7157 TSK_ImplicitInstantiation) {
7158 InstantiationFunction->setTemplateSpecializationKind(
7159 TSK_ExplicitSpecialization);
7160 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007161 // Explicit specializations of member functions of class templates do not
7162 // inherit '=delete' from the member function they are specializing.
7163 if (InstantiationFunction->isDeleted()) {
7164 assert(InstantiationFunction->getCanonicalDecl() ==
7165 InstantiationFunction);
7166 InstantiationFunction->setDeletedAsWritten(false);
7167 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007169
Douglas Gregor86d142a2009-10-08 07:24:58 +00007170 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7171 cast<CXXMethodDecl>(InstantiatedFrom),
7172 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007173 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007174 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007175 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7176 if (InstantiationVar->getTemplateSpecializationKind() ==
7177 TSK_ImplicitInstantiation) {
7178 InstantiationVar->setTemplateSpecializationKind(
7179 TSK_ExplicitSpecialization);
7180 InstantiationVar->setLocation(Member->getLocation());
7181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007182
Larisse Voufo39a1e502013-08-06 01:03:05 +00007183 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7184 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007185 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007186 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007187 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7188 if (InstantiationClass->getTemplateSpecializationKind() ==
7189 TSK_ImplicitInstantiation) {
7190 InstantiationClass->setTemplateSpecializationKind(
7191 TSK_ExplicitSpecialization);
7192 InstantiationClass->setLocation(Member->getLocation());
7193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007194
Douglas Gregor86d142a2009-10-08 07:24:58 +00007195 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007196 cast<CXXRecordDecl>(InstantiatedFrom),
7197 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007198 } else {
7199 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7200 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7201 if (InstantiationEnum->getTemplateSpecializationKind() ==
7202 TSK_ImplicitInstantiation) {
7203 InstantiationEnum->setTemplateSpecializationKind(
7204 TSK_ExplicitSpecialization);
7205 InstantiationEnum->setLocation(Member->getLocation());
7206 }
7207
7208 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7209 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007211
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007212 // Save the caller the trouble of having to figure out which declaration
7213 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007214 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007215 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007216 return false;
7217}
7218
Douglas Gregore47f5a72009-10-14 23:41:34 +00007219/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007220///
7221/// \returns true if a serious error occurs, false otherwise.
7222static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007223 SourceLocation InstLoc,
7224 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007225 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7226 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007227
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007228 if (CurContext->isRecord()) {
7229 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7230 << D;
7231 return true;
7232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007233
Richard Smith050d2612011-10-18 02:28:33 +00007234 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007235 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007236 // template. If the name declared in the explicit instantiation is an
7237 // unqualified name, the explicit instantiation shall appear in the
7238 // namespace where its template is declared or, if that namespace is inline
7239 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007240 //
7241 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007242 if (WasQualifiedName) {
7243 if (CurContext->Encloses(OrigContext))
7244 return false;
7245 } else {
7246 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7247 return false;
7248 }
7249
7250 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7251 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007252 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007253 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007254 diag::err_explicit_instantiation_out_of_scope :
7255 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007256 << D << NS;
7257 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007258 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007259 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007260 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7261 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7262 << D << NS;
7263 } else
7264 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007265 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007266 diag::err_explicit_instantiation_must_be_global :
7267 diag::warn_explicit_instantiation_must_be_global_0x)
7268 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007269 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007270 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007271}
7272
7273/// \brief Determine whether the given scope specifier has a template-id in it.
7274static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7275 if (!SS.isSet())
7276 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007277
Richard Smith050d2612011-10-18 02:28:33 +00007278 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007279 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007280 // or a static data member of a class template specialization, the name of
7281 // the class template specialization in the qualified-id for the member
7282 // name shall be a simple-template-id.
7283 //
7284 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007285 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7286 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007287 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007288 if (isa<TemplateSpecializationType>(T))
7289 return true;
7290
7291 return false;
7292}
7293
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007294// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007295DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007296Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007297 SourceLocation ExternLoc,
7298 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007299 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007300 SourceLocation KWLoc,
7301 const CXXScopeSpec &SS,
7302 TemplateTy TemplateD,
7303 SourceLocation TemplateNameLoc,
7304 SourceLocation LAngleLoc,
7305 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007306 SourceLocation RAngleLoc,
7307 AttributeList *Attr) {
7308 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007309 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007310 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007311 // Check that the specialization uses the same tag kind as the
7312 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007313 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7314 assert(Kind != TTK_Enum &&
7315 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007316
Richard Trieu265c3442016-04-05 21:13:54 +00007317 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7318
7319 if (!ClassTemplate) {
7320 unsigned ErrorKind = 0;
7321 if (isa<TypeAliasTemplateDecl>(TD)) {
7322 ErrorKind = 4;
7323 } else if (isa<TemplateTemplateParmDecl>(TD)) {
7324 ErrorKind = 5;
7325 }
7326
7327 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7328 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007329 return true;
7330 }
7331
Douglas Gregord9034f02009-05-14 16:41:31 +00007332 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007333 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007334 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007335 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007336 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007337 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007338 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007339 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007340 diag::note_previous_use);
7341 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7342 }
7343
Douglas Gregore47f5a72009-10-14 23:41:34 +00007344 // C++0x [temp.explicit]p2:
7345 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007346 // definition and an explicit instantiation declaration. An explicit
7347 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007348 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7349 ? TSK_ExplicitInstantiationDefinition
7350 : TSK_ExplicitInstantiationDeclaration;
7351
7352 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7353 // Check for dllexport class template instantiation declarations.
7354 for (AttributeList *A = Attr; A; A = A->getNext()) {
7355 if (A->getKind() == AttributeList::AT_DLLExport) {
7356 Diag(ExternLoc,
7357 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7358 Diag(A->getLoc(), diag::note_attribute);
7359 break;
7360 }
7361 }
7362
7363 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7364 Diag(ExternLoc,
7365 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7366 Diag(A->getLocation(), diag::note_attribute);
7367 }
7368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007369
Hans Wennborga86a83b2016-05-26 19:42:56 +00007370 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7371 // instantiation declarations for most purposes.
7372 bool DLLImportExplicitInstantiationDef = false;
7373 if (TSK == TSK_ExplicitInstantiationDefinition &&
7374 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7375 // Check for dllimport class template instantiation definitions.
7376 bool DLLImport =
7377 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7378 for (AttributeList *A = Attr; A; A = A->getNext()) {
7379 if (A->getKind() == AttributeList::AT_DLLImport)
7380 DLLImport = true;
7381 if (A->getKind() == AttributeList::AT_DLLExport) {
7382 // dllexport trumps dllimport here.
7383 DLLImport = false;
7384 break;
7385 }
7386 }
7387 if (DLLImport) {
7388 TSK = TSK_ExplicitInstantiationDeclaration;
7389 DLLImportExplicitInstantiationDef = true;
7390 }
7391 }
7392
Douglas Gregora1f49972009-05-13 00:25:59 +00007393 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007394 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007395 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007396
7397 // Check that the template argument list is well-formed for this
7398 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007399 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007400 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7401 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007402 return true;
7403
Douglas Gregora1f49972009-05-13 00:25:59 +00007404 // Find the class template specialization declaration that
7405 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007406 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007407 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007408 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007409
Abramo Bagnara8075c852010-06-12 07:44:57 +00007410 TemplateSpecializationKind PrevDecl_TSK
7411 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7412
Douglas Gregor54888652009-10-07 00:13:32 +00007413 // C++0x [temp.explicit]p2:
7414 // [...] An explicit instantiation shall appear in an enclosing
7415 // namespace of its template. [...]
7416 //
7417 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007418 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7419 SS.isSet()))
7420 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007421
Craig Topperc3ec1492014-05-26 06:22:03 +00007422 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007423
Abramo Bagnara8075c852010-06-12 07:44:57 +00007424 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007425 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007426 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007427 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007428 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007429 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007430 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007431
Abramo Bagnara8075c852010-06-12 07:44:57 +00007432 // Even though HasNoEffect == true means that this explicit instantiation
7433 // has no effect on semantics, we go on to put its syntax in the AST.
7434
7435 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7436 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007437 // Since the only prior class template specialization with these
7438 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007439 // declaration node as our own, updating the source location
7440 // for the template name to reflect our new declaration.
7441 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007442 Specialization = PrevDecl;
7443 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007444 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007445 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007446
7447 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7448 DLLImportExplicitInstantiationDef) {
7449 // The new specialization might add a dllimport attribute.
7450 HasNoEffect = false;
7451 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007452 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007453
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007454 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007455 // Create a new class template specialization declaration node for
7456 // this explicit specialization.
7457 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007458 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007459 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007460 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007461 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007462 Converted.data(),
7463 Converted.size(),
7464 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007465 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007466
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007467 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007468 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007469 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007470 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007471 }
7472
7473 // Build the fully-sugared type for this explicit instantiation as
7474 // the user wrote in the explicit instantiation itself. This means
7475 // that we'll pretty-print the type retrieved from the
7476 // specialization's declaration the way that the user actually wrote
7477 // the explicit instantiation, rather than formatting the name based
7478 // on the "canonical" representation used to store the template
7479 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007480 TypeSourceInfo *WrittenTy
7481 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7482 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007483 Context.getTypeDeclType(Specialization));
7484 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007485
Abramo Bagnara8075c852010-06-12 07:44:57 +00007486 // Set source locations for keywords.
7487 Specialization->setExternLoc(ExternLoc);
7488 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007489 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007490
Rafael Espindola0b062072012-01-03 06:04:21 +00007491 if (Attr)
7492 ProcessDeclAttributeList(S, Specialization, Attr);
7493
Abramo Bagnara8075c852010-06-12 07:44:57 +00007494 // Add the explicit instantiation into its lexical context. However,
7495 // since explicit instantiations are never found by name lookup, we
7496 // just put it into the declaration context directly.
7497 Specialization->setLexicalDeclContext(CurContext);
7498 CurContext->addDecl(Specialization);
7499
7500 // Syntax is now OK, so return if it has no other effect on semantics.
7501 if (HasNoEffect) {
7502 // Set the template specialization kind.
7503 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007504 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007505 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007506
7507 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007508 // A definition of a class template or class member template
7509 // shall be in scope at the point of the explicit instantiation of
7510 // the class template or class member template.
7511 //
7512 // This check comes when we actually try to perform the
7513 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007514 ClassTemplateSpecializationDecl *Def
7515 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007516 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007517 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007518 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007519 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007520 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007521 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7522 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007523
Douglas Gregor1d957a32009-10-27 18:42:08 +00007524 // Instantiate the members of this class template specialization.
7525 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007526 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007527 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007528 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007529 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7530 // TSK_ExplicitInstantiationDefinition
7531 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007532 (TSK == TSK_ExplicitInstantiationDefinition ||
7533 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007534 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007535 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007536
Hans Wennborgc0875502015-06-09 00:39:05 +00007537 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7538 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7539 // In the MS ABI, an explicit instantiation definition can add a dll
7540 // attribute to a template with a previous instantiation declaration.
7541 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007542 auto *A = cast<InheritableAttr>(
7543 getDLLAttr(Specialization)->clone(getASTContext()));
7544 A->setInherited(true);
7545 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007546
7547 // We reject explicit instantiations in class scope, so there should
7548 // never be any delayed exported classes to worry about.
7549 assert(DelayedDllExportClasses.empty() &&
7550 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007551 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007552 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007553
7554 // Propagate attribute to base class templates.
7555 for (auto &B : Def->bases()) {
7556 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7557 B.getType()->getAsCXXRecordDecl()))
7558 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7559 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007560 }
7561 }
7562
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007563 // Set the template specialization kind. Make sure it is set before
7564 // instantiating the members which will trigger ASTConsumer callbacks.
7565 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007566 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007567 } else {
7568
7569 // Set the template specialization kind.
7570 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007571 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007572
John McCall48871652010-08-21 09:40:31 +00007573 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007574}
7575
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007576// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007577DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007578Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007579 SourceLocation ExternLoc,
7580 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007581 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007582 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007583 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007584 IdentifierInfo *Name,
7585 SourceLocation NameLoc,
7586 AttributeList *Attr) {
7587
Douglas Gregord6ab8742009-05-28 23:31:59 +00007588 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007589 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007590 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007591 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007592 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007593 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007594 SourceLocation(), false, TypeResult(),
7595 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007596 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7597
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007598 if (!TagD)
7599 return true;
7600
John McCall48871652010-08-21 09:40:31 +00007601 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007602 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007603
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007604 if (Tag->isInvalidDecl())
7605 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007606
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007607 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7608 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7609 if (!Pattern) {
7610 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7611 << Context.getTypeDeclType(Record);
7612 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7613 return true;
7614 }
7615
Douglas Gregore47f5a72009-10-14 23:41:34 +00007616 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007617 // If the explicit instantiation is for a class or member class, the
7618 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007619 // simple-template-id.
7620 //
7621 // C++98 has the same restriction, just worded differently.
7622 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007623 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007624 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625
Douglas Gregore47f5a72009-10-14 23:41:34 +00007626 // C++0x [temp.explicit]p2:
7627 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007628 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007629 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007630 TemplateSpecializationKind TSK
7631 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7632 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007633
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007634 // C++0x [temp.explicit]p2:
7635 // [...] An explicit instantiation shall appear in an enclosing
7636 // namespace of its template. [...]
7637 //
7638 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007639 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007640
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007641 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007642 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007643 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007644 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007645 PrevDecl = Record;
7646 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007647 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007648 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007649 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007650 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007651 PrevDecl,
7652 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007653 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007654 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007655 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007656 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007657 return TagD;
7658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007659
Douglas Gregor12e49d32009-10-15 22:53:21 +00007660 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007661 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007662 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007663 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007664 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007665 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007666 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007667 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007668 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007669 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7670 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007671 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7672 << Pattern;
7673 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007674 } else {
7675 if (InstantiateClass(NameLoc, Record, Def,
7676 getTemplateInstantiationArgs(Record),
7677 TSK))
7678 return true;
7679
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007680 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007681 if (!RecordDef)
7682 return true;
7683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684 }
7685
Douglas Gregor1d957a32009-10-27 18:42:08 +00007686 // Instantiate all of the members of the class.
7687 InstantiateClassMembers(NameLoc, RecordDef,
7688 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007689
Douglas Gregor88d292c2010-05-13 16:44:06 +00007690 if (TSK == TSK_ExplicitInstantiationDefinition)
7691 MarkVTableUsed(NameLoc, RecordDef, true);
7692
Mike Stump87c57ac2009-05-16 07:39:55 +00007693 // FIXME: We don't have any representation for explicit instantiations of
7694 // member classes. Such a representation is not needed for compilation, but it
7695 // should be available for clients that want to see all of the declarations in
7696 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007697 return TagD;
7698}
7699
John McCallfaf5fb42010-08-26 23:41:50 +00007700DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7701 SourceLocation ExternLoc,
7702 SourceLocation TemplateLoc,
7703 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007704 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007705 // TODO: check if/when DNInfo should replace Name.
7706 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7707 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007708 if (!Name) {
7709 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007710 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007711 diag::err_explicit_instantiation_requires_name)
7712 << D.getDeclSpec().getSourceRange()
7713 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007714
Douglas Gregor450f00842009-09-25 18:43:00 +00007715 return true;
7716 }
7717
7718 // The scope passed in may not be a decl scope. Zip up the scope tree until
7719 // we find one that is.
7720 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7721 (S->getFlags() & Scope::TemplateParamScope) != 0)
7722 S = S->getParent();
7723
7724 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007725 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7726 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007727 if (R.isNull())
7728 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007729
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007730 // C++ [dcl.stc]p1:
7731 // A storage-class-specifier shall not be specified in [...] an explicit
7732 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007733 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007734 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7735 << Name;
7736 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007737 } else if (D.getDeclSpec().getStorageClassSpec()
7738 != DeclSpec::SCS_unspecified) {
7739 // Complain about then remove the storage class specifier.
7740 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7741 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7742
7743 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007744 }
7745
Douglas Gregor3c74d412009-10-14 20:14:33 +00007746 // C++0x [temp.explicit]p1:
7747 // [...] An explicit instantiation of a function template shall not use the
7748 // inline or constexpr specifiers.
7749 // Presumably, this also applies to member functions of class templates as
7750 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007751 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007752 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007753 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007754 diag::err_explicit_instantiation_inline :
7755 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007756 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007757 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007758 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7759 // not already specified.
7760 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7761 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007762
Nathan Wilsonde498452016-02-08 05:34:00 +00007763 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7764 // applied only to the definition of a function template or variable template,
7765 // declared in namespace scope.
7766 if (D.getDeclSpec().isConceptSpecified()) {
7767 Diag(D.getDeclSpec().getConceptSpecLoc(),
7768 diag::err_concept_specified_specialization) << 0;
7769 return true;
7770 }
7771
Douglas Gregore47f5a72009-10-14 23:41:34 +00007772 // C++0x [temp.explicit]p2:
7773 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007774 // definition and an explicit instantiation declaration. An explicit
7775 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007776 TemplateSpecializationKind TSK
7777 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7778 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007780 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007781 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007782
7783 if (!R->isFunctionType()) {
7784 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007785 // A [...] static data member of a class template can be explicitly
7786 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007787 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007788 // C++1y [temp.explicit]p1:
7789 // A [...] variable [...] template specialization can be explicitly
7790 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007791 if (Previous.isAmbiguous())
7792 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007793
John McCall67c00872009-12-02 08:25:40 +00007794 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007795 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007796
Larisse Voufo39a1e502013-08-06 01:03:05 +00007797 if (!PrevTemplate) {
7798 if (!Prev || !Prev->isStaticDataMember()) {
7799 // We expect to see a data data member here.
7800 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7801 << Name;
7802 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7803 P != PEnd; ++P)
7804 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7805 return true;
7806 }
7807
7808 if (!Prev->getInstantiatedFromStaticDataMember()) {
7809 // FIXME: Check for explicit specialization?
7810 Diag(D.getIdentifierLoc(),
7811 diag::err_explicit_instantiation_data_member_not_instantiated)
7812 << Prev;
7813 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7814 // FIXME: Can we provide a note showing where this was declared?
7815 return true;
7816 }
7817 } else {
7818 // Explicitly instantiate a variable template.
7819
7820 // C++1y [dcl.spec.auto]p6:
7821 // ... A program that uses auto or decltype(auto) in a context not
7822 // explicitly allowed in this section is ill-formed.
7823 //
7824 // This includes auto-typed variable template instantiations.
7825 if (R->isUndeducedType()) {
7826 Diag(T->getTypeLoc().getLocStart(),
7827 diag::err_auto_not_allowed_var_inst);
7828 return true;
7829 }
7830
Richard Smithef985ac2013-09-18 02:10:12 +00007831 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7832 // C++1y [temp.explicit]p3:
7833 // If the explicit instantiation is for a variable, the unqualified-id
7834 // in the declaration shall be a template-id.
7835 Diag(D.getIdentifierLoc(),
7836 diag::err_explicit_instantiation_without_template_id)
7837 << PrevTemplate;
7838 Diag(PrevTemplate->getLocation(),
7839 diag::note_explicit_instantiation_here);
7840 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007841 }
7842
Nathan Wilson83839122016-04-09 02:55:27 +00007843 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7844 // explicit instantiation (14.8.2) [...] of a concept definition.
7845 if (PrevTemplate->isConcept()) {
7846 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7847 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7848 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7849 return true;
7850 }
7851
Richard Smithef985ac2013-09-18 02:10:12 +00007852 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007853 TemplateArgumentListInfo TemplateArgs =
7854 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007855
Larisse Voufo39a1e502013-08-06 01:03:05 +00007856 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7857 D.getIdentifierLoc(), TemplateArgs);
7858 if (Res.isInvalid())
7859 return true;
7860
7861 // Ignore access control bits, we don't need them for redeclaration
7862 // checking.
7863 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865
Douglas Gregore47f5a72009-10-14 23:41:34 +00007866 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007868 // or a static data member of a class template specialization, the name of
7869 // the class template specialization in the qualified-id for the member
7870 // name shall be a simple-template-id.
7871 //
7872 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007873 //
Richard Smith5977d872013-09-18 21:55:14 +00007874 // This does not apply to variable template specializations, where the
7875 // template-id is in the unqualified-id instead.
7876 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007877 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007878 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007879 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007880
Douglas Gregore47f5a72009-10-14 23:41:34 +00007881 // Check the scope of this explicit instantiation.
7882 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007883
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007884 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007885 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7886 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007887 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007888 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007889 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007890 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007891
Larisse Voufo39a1e502013-08-06 01:03:05 +00007892 if (!HasNoEffect) {
7893 // Instantiate static data member or variable template.
7894
7895 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7896 if (PrevTemplate) {
7897 // Merge attributes.
7898 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7899 ProcessDeclAttributeList(S, Prev, Attr);
7900 }
7901 if (TSK == TSK_ExplicitInstantiationDefinition)
7902 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7903 }
7904
7905 // Check the new variable specialization against the parsed input.
7906 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7907 Diag(T->getTypeLoc().getLocStart(),
7908 diag::err_invalid_var_template_spec_type)
7909 << 0 << PrevTemplate << R << Prev->getType();
7910 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7911 << 2 << PrevTemplate->getDeclName();
7912 return true;
7913 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007914
Douglas Gregor450f00842009-09-25 18:43:00 +00007915 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007916 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007918
7919 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007920 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007921 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007922 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007923 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007924 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007925 HasExplicitTemplateArgs = true;
7926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007927
Douglas Gregor450f00842009-09-25 18:43:00 +00007928 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007929 // A [...] function [...] can be explicitly instantiated from its template.
7930 // A member function [...] of a class template can be explicitly
7931 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007932 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007933 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007934 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007935 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7936 P != PEnd; ++P) {
7937 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007938 if (!HasExplicitTemplateArgs) {
7939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007940 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7941 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007942 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007943
John McCall58cc69d2010-01-27 01:50:18 +00007944 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007945 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7946 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007947 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007948 }
7949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007950
Douglas Gregor450f00842009-09-25 18:43:00 +00007951 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7952 if (!FunTmpl)
7953 continue;
7954
Larisse Voufo98b20f12013-07-19 23:00:19 +00007955 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007956 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007957 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007959 (HasExplicitTemplateArgs ? &TemplateArgs
7960 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007961 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007962 // Keep track of almost-matches.
7963 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00007964 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007965 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007966 (void)TDK;
7967 continue;
7968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007969
John McCall58cc69d2010-01-27 01:50:18 +00007970 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007972
Douglas Gregor450f00842009-09-25 18:43:00 +00007973 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007974 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007975 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007976 D.getIdentifierLoc(),
7977 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7978 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7979 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007980
John McCall58cc69d2010-01-27 01:50:18 +00007981 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007982 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007983
7984 // Ignore access control bits, we don't need them for redeclaration checking.
7985 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986
Alexey Bataev73983912014-11-06 10:10:50 +00007987 // C++11 [except.spec]p4
7988 // In an explicit instantiation an exception-specification may be specified,
7989 // but is not required.
7990 // If an exception-specification is specified in an explicit instantiation
7991 // directive, it shall be compatible with the exception-specifications of
7992 // other declarations of that function.
7993 if (auto *FPT = R->getAs<FunctionProtoType>())
7994 if (FPT->hasExceptionSpec()) {
7995 unsigned DiagID =
7996 diag::err_mismatched_exception_spec_explicit_instantiation;
7997 if (getLangOpts().MicrosoftExt)
7998 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7999 bool Result = CheckEquivalentExceptionSpec(
8000 PDiag(DiagID) << Specialization->getType(),
8001 PDiag(diag::note_explicit_instantiation_here),
8002 Specialization->getType()->getAs<FunctionProtoType>(),
8003 Specialization->getLocation(), FPT, D.getLocStart());
8004 // In Microsoft mode, mismatching exception specifications just cause a
8005 // warning.
8006 if (!getLangOpts().MicrosoftExt && Result)
8007 return true;
8008 }
8009
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008010 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008011 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008012 diag::err_explicit_instantiation_member_function_not_instantiated)
8013 << Specialization
8014 << (Specialization->getTemplateSpecializationKind() ==
8015 TSK_ExplicitSpecialization);
8016 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8017 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018 }
8019
Douglas Gregorec9fd132012-01-14 16:38:05 +00008020 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008021 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8022 PrevDecl = Specialization;
8023
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008024 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008025 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008026 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008027 PrevDecl,
8028 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008029 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008030 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008031 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008032
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008033 // FIXME: We may still want to build some representation of this
8034 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008035 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008036 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008037 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008038
8039 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008040 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8041 if (Attr)
8042 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008043
Richard Smitheb36ddf2014-04-24 22:45:46 +00008044 if (Specialization->isDefined()) {
8045 // Let the ASTConsumer know that this function has been explicitly
8046 // instantiated now, and its linkage might have changed.
8047 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8048 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008049 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008050
Douglas Gregore47f5a72009-10-14 23:41:34 +00008051 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008052 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008053 // or a static data member of a class template specialization, the name of
8054 // the class template specialization in the qualified-id for the member
8055 // name shall be a simple-template-id.
8056 //
8057 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008058 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008059 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008060 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008061 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008062 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008063 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008064 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065
Nathan Wilson83839122016-04-09 02:55:27 +00008066 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8067 // explicit instantiation (14.8.2) [...] of a concept definition.
8068 if (FunTmpl && FunTmpl->isConcept() &&
8069 !D.getDeclSpec().isConceptSpecified()) {
8070 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8071 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8072 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8073 return true;
8074 }
8075
Douglas Gregore47f5a72009-10-14 23:41:34 +00008076 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008077 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008078 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008079 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008080 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008081
Douglas Gregor450f00842009-09-25 18:43:00 +00008082 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008083 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008084}
8085
John McCallfaf5fb42010-08-26 23:41:50 +00008086TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008087Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8088 const CXXScopeSpec &SS, IdentifierInfo *Name,
8089 SourceLocation TagLoc, SourceLocation NameLoc) {
8090 // This has to hold, because SS is expected to be defined.
8091 assert(Name && "Expected a name in a dependent tag");
8092
Aaron Ballman4a979672014-01-03 13:56:08 +00008093 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008094 if (!NNS)
8095 return true;
8096
Abramo Bagnara6150c882010-05-11 21:36:43 +00008097 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008098
Douglas Gregorba41d012010-04-24 16:38:41 +00008099 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8100 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008101 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008102 return true;
8103 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008104
Douglas Gregore7c20652011-03-02 00:47:37 +00008105 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008106 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008107 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8108
8109 // Create type-source location information for this type.
8110 TypeLocBuilder TLB;
8111 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008112 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008113 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8114 TL.setNameLoc(NameLoc);
8115 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008116}
8117
John McCallfaf5fb42010-08-26 23:41:50 +00008118TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8120 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008121 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008122 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008123 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008124
Richard Smith0bf8a4922011-10-18 20:49:44 +00008125 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8126 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008127 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008128 diag::warn_cxx98_compat_typename_outside_of_template :
8129 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008130 << FixItHint::CreateRemoval(TypenameLoc);
8131
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008132 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008133 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8134 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008135 if (T.isNull())
8136 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008137
8138 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8139 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008140 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008141 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008142 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008143 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008144 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008145 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008146 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008147 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008148 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008150
John McCallba7bf592010-08-24 05:47:05 +00008151 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008152}
8153
John McCallfaf5fb42010-08-26 23:41:50 +00008154TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008155Sema::ActOnTypenameType(Scope *S,
8156 SourceLocation TypenameLoc,
8157 const CXXScopeSpec &SS,
8158 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008159 TemplateTy TemplateIn,
8160 SourceLocation TemplateNameLoc,
8161 SourceLocation LAngleLoc,
8162 ASTTemplateArgsPtr TemplateArgsIn,
8163 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008164 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8165 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008166 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008167 diag::warn_cxx98_compat_typename_outside_of_template :
8168 diag::ext_typename_outside_of_template)
8169 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008170
8171 // Translate the parser's template argument list in our AST format.
8172 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8173 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8174
8175 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008176 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8177 // Construct a dependent template specialization type.
8178 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008179 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008180 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8181 DTN->getQualifier(),
8182 DTN->getIdentifier(),
8183 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008184
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008185 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008186 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008187 DependentTemplateSpecializationTypeLoc SpecTL
8188 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008189 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8190 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008191 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008192 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008193 SpecTL.setLAngleLoc(LAngleLoc);
8194 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008195 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8196 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008197 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008198 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008199
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008200 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8201 if (T.isNull())
8202 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008203
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008204 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008205 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008206 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008207 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008208 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8209 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008210 SpecTL.setLAngleLoc(LAngleLoc);
8211 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008212 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8213 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8214
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008215 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8216 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008217 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008218 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8219
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008220 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8221 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008222}
8223
Douglas Gregorb09518c2011-02-27 22:46:49 +00008224
Richard Smith6f8d2c62012-05-09 05:17:00 +00008225/// Determine whether this failed name lookup should be treated as being
8226/// disabled by a usage of std::enable_if.
8227static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8228 SourceRange &CondRange) {
8229 // We must be looking for a ::type...
8230 if (!II.isStr("type"))
8231 return false;
8232
8233 // ... within an explicitly-written template specialization...
8234 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8235 return false;
8236 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008237 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8238 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8239 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008240 return false;
8241 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008242 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008243
8244 // ... which names a complete class template declaration...
8245 const TemplateDecl *EnableIfDecl =
8246 EnableIfTST->getTemplateName().getAsTemplateDecl();
8247 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8248 return false;
8249
8250 // ... called "enable_if".
8251 const IdentifierInfo *EnableIfII =
8252 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8253 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8254 return false;
8255
8256 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008257 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008258 return true;
8259}
8260
Douglas Gregor333489b2009-03-27 23:10:48 +00008261/// \brief Build the type that describes a C++ typename specifier,
8262/// e.g., "typename T::type".
8263QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008264Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8265 SourceLocation KeywordLoc,
8266 NestedNameSpecifierLoc QualifierLoc,
8267 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008268 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008269 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008270 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008271
John McCall0b66eb32010-05-01 00:40:08 +00008272 DeclContext *Ctx = computeDeclContext(SS);
8273 if (!Ctx) {
8274 // If the nested-name-specifier is dependent and couldn't be
8275 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008276 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8277 return Context.getDependentNameType(Keyword,
8278 QualifierLoc.getNestedNameSpecifier(),
8279 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008280 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008281
John McCall0b66eb32010-05-01 00:40:08 +00008282 // If the nested-name-specifier refers to the current instantiation,
8283 // the "typename" keyword itself is superfluous. In C++03, the
8284 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8285 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008286 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008287
John McCall0b66eb32010-05-01 00:40:08 +00008288 if (RequireCompleteDeclContext(SS, Ctx))
8289 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008290
8291 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008292 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008293 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008294 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008295 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008296 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008297 case LookupResult::NotFound: {
8298 // If we're looking up 'type' within a template named 'enable_if', produce
8299 // a more specific diagnostic.
8300 SourceRange CondRange;
8301 if (isEnableIf(QualifierLoc, II, CondRange)) {
8302 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8303 << Ctx << CondRange;
8304 return QualType();
8305 }
8306
Douglas Gregore40876a2009-10-13 21:16:44 +00008307 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008308 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008309 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008310
8311 case LookupResult::FoundUnresolvedValue: {
8312 // We found a using declaration that is a value. Most likely, the using
8313 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008314 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008315 IILoc);
8316 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8317 << Name << Ctx << FullRange;
8318 if (UnresolvedUsingValueDecl *Using
8319 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008320 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008321 Diag(Loc, diag::note_using_value_decl_missing_typename)
8322 << FixItHint::CreateInsertion(Loc, "typename ");
8323 }
8324 }
8325 // Fall through to create a dependent typename type, from which we can recover
8326 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008327
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008328 case LookupResult::NotFoundInCurrentInstantiation:
8329 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008330 return Context.getDependentNameType(Keyword,
8331 QualifierLoc.getNestedNameSpecifier(),
8332 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008333
8334 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008335 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008336 // We found a type. Build an ElaboratedType, since the
8337 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008338 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008339 return Context.getElaboratedType(ETK_Typename,
8340 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008341 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008342 }
8343
8344 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008345 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008346 break;
8347
8348 case LookupResult::FoundOverloaded:
8349 DiagID = diag::err_typename_nested_not_type;
8350 Referenced = *Result.begin();
8351 break;
8352
John McCall6538c932009-10-10 05:48:19 +00008353 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008354 return QualType();
8355 }
8356
8357 // If we get here, it's because name lookup did not find a
8358 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008359 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008360 IILoc);
8361 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008362 if (Referenced)
8363 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8364 << Name;
8365 return QualType();
8366}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008367
8368namespace {
8369 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008370 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008371 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008372 SourceLocation Loc;
8373 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008374
Douglas Gregor15acfb92009-08-06 16:20:37 +00008375 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008376 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008377
Mike Stump11289f42009-09-09 15:08:12 +00008378 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008379 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008380 DeclarationName Entity)
8381 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008382 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008383
8384 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008385 /// transformed.
8386 ///
8387 /// For the purposes of type reconstruction, a type has already been
8388 /// transformed if it is NULL or if it is not dependent.
8389 bool AlreadyTransformed(QualType T) {
8390 return T.isNull() || !T->isDependentType();
8391 }
Mike Stump11289f42009-09-09 15:08:12 +00008392
8393 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008394 /// rebuilt.
8395 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008396
Douglas Gregor15acfb92009-08-06 16:20:37 +00008397 /// \brief Returns the name of the entity whose type is being rebuilt.
8398 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008399
Douglas Gregoref6ab412009-10-27 06:26:26 +00008400 /// \brief Sets the "base" location and entity when that
8401 /// information is known based on another transformation.
8402 void setBase(SourceLocation Loc, DeclarationName Entity) {
8403 this->Loc = Loc;
8404 this->Entity = Entity;
8405 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008406
8407 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8408 // Lambdas never need to be transformed.
8409 return E;
8410 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008411 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008412} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008413
Douglas Gregor15acfb92009-08-06 16:20:37 +00008414/// \brief Rebuilds a type within the context of the current instantiation.
8415///
Mike Stump11289f42009-09-09 15:08:12 +00008416/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008417/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008418/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008419/// partial specialization thereof). This routine will rebuild that type now
8420/// that we have entered the declarator's scope, which may produce different
8421/// canonical types, e.g.,
8422///
8423/// \code
8424/// template<typename T>
8425/// struct X {
8426/// typedef T* pointer;
8427/// pointer data();
8428/// };
8429///
8430/// template<typename T>
8431/// typename X<T>::pointer X<T>::data() { ... }
8432/// \endcode
8433///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008434/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008435/// since we do not know that we can look into X<T> when we parsed the type.
8436/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008437/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008438/// as the canonical type of T*, allowing the return types of the out-of-line
8439/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008440TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8441 SourceLocation Loc,
8442 DeclarationName Name) {
8443 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008444 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008445
Douglas Gregor15acfb92009-08-06 16:20:37 +00008446 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8447 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008448}
Douglas Gregorbe999392009-09-15 16:23:51 +00008449
John McCalldadc5752010-08-24 06:29:42 +00008450ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008451 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8452 DeclarationName());
8453 return Rebuilder.TransformExpr(E);
8454}
8455
John McCall99b2fe52010-04-29 23:50:39 +00008456bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008457 if (SS.isInvalid())
8458 return true;
John McCall2408e322010-04-27 00:57:59 +00008459
Douglas Gregor10176412011-02-25 16:07:42 +00008460 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008461 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8462 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008463 NestedNameSpecifierLoc Rebuilt
8464 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8465 if (!Rebuilt)
8466 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008467
Douglas Gregor10176412011-02-25 16:07:42 +00008468 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008469 return false;
John McCall2408e322010-04-27 00:57:59 +00008470}
8471
Douglas Gregor041b0842011-10-14 15:31:12 +00008472/// \brief Rebuild the template parameters now that we know we're in a current
8473/// instantiation.
8474bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8475 TemplateParameterList *Params) {
8476 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8477 Decl *Param = Params->getParam(I);
8478
8479 // There is nothing to rebuild in a type parameter.
8480 if (isa<TemplateTypeParmDecl>(Param))
8481 continue;
8482
8483 // Rebuild the template parameter list of a template template parameter.
8484 if (TemplateTemplateParmDecl *TTP
8485 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8486 if (RebuildTemplateParamsInCurrentInstantiation(
8487 TTP->getTemplateParameters()))
8488 return true;
8489
8490 continue;
8491 }
8492
8493 // Rebuild the type of a non-type template parameter.
8494 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8495 TypeSourceInfo *NewTSI
8496 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8497 NTTP->getLocation(),
8498 NTTP->getDeclName());
8499 if (!NewTSI)
8500 return true;
8501
8502 if (NewTSI != NTTP->getTypeSourceInfo()) {
8503 NTTP->setTypeSourceInfo(NewTSI);
8504 NTTP->setType(NewTSI->getType());
8505 }
8506 }
8507
8508 return false;
8509}
8510
Douglas Gregorbe999392009-09-15 16:23:51 +00008511/// \brief Produces a formatted string that describes the binding of
8512/// template parameters to template arguments.
8513std::string
8514Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8515 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008516 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008517}
8518
8519std::string
8520Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8521 const TemplateArgument *Args,
8522 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008523 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008524 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008525
Douglas Gregore62e6a02009-11-11 19:13:48 +00008526 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008527 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008528
Douglas Gregorbe999392009-09-15 16:23:51 +00008529 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008530 if (I >= NumArgs)
8531 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008532
Douglas Gregorbe999392009-09-15 16:23:51 +00008533 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008534 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008535 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008536 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008537
Douglas Gregorbe999392009-09-15 16:23:51 +00008538 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008539 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008540 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008541 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008543
Douglas Gregor0192c232010-12-20 16:52:59 +00008544 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008545 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008546 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008547
8548 Out << ']';
8549 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008550}
Francois Pichet1c229c02011-04-22 22:18:13 +00008551
Richard Smithe40f2ba2013-08-07 21:41:30 +00008552void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8553 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008554 if (!FD)
8555 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008556
8557 LateParsedTemplate *LPT = new LateParsedTemplate;
8558
8559 // Take tokens to avoid allocations
8560 LPT->Toks.swap(Toks);
8561 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008562 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008563
8564 FD->setLateTemplateParsed(true);
8565}
8566
8567void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8568 if (!FD)
8569 return;
8570 FD->setLateTemplateParsed(false);
8571}
Francois Pichet1c229c02011-04-22 22:18:13 +00008572
8573bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8574 DeclContext *DC = CurContext;
8575
8576 while (DC) {
8577 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8578 const FunctionDecl *FD = RD->isLocalClass();
8579 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8580 } else if (DC->isTranslationUnit() || DC->isNamespace())
8581 return false;
8582
8583 DC = DC->getParent();
8584 }
8585 return false;
8586}
Richard Smith6739a102016-05-05 00:56:12 +00008587
8588/// \brief Walk the path from which a declaration was instantiated, and check
8589/// that every explicit specialization along that path is visible. This enforces
8590/// C++ [temp.expl.spec]/6:
8591///
8592/// If a template, a member template or a member of a class template is
8593/// explicitly specialized then that specialization shall be declared before
8594/// the first use of that specialization that would cause an implicit
8595/// instantiation to take place, in every translation unit in which such a
8596/// use occurs; no diagnostic is required.
8597///
8598/// and also C++ [temp.class.spec]/1:
8599///
8600/// A partial specialization shall be declared before the first use of a
8601/// class template specialization that would make use of the partial
8602/// specialization as the result of an implicit or explicit instantiation
8603/// in every translation unit in which such a use occurs; no diagnostic is
8604/// required.
8605class ExplicitSpecializationVisibilityChecker {
8606 Sema &S;
8607 SourceLocation Loc;
8608 llvm::SmallVector<Module *, 8> Modules;
8609
8610public:
8611 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8612 : S(S), Loc(Loc) {}
8613
8614 void check(NamedDecl *ND) {
8615 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8616 return checkImpl(FD);
8617 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8618 return checkImpl(RD);
8619 if (auto *VD = dyn_cast<VarDecl>(ND))
8620 return checkImpl(VD);
8621 if (auto *ED = dyn_cast<EnumDecl>(ND))
8622 return checkImpl(ED);
8623 }
8624
8625private:
8626 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8627 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8628 : Sema::MissingImportKind::ExplicitSpecialization;
8629 const bool Recover = true;
8630
8631 // If we got a custom set of modules (because only a subset of the
8632 // declarations are interesting), use them, otherwise let
8633 // diagnoseMissingImport intelligently pick some.
8634 if (Modules.empty())
8635 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8636 else
8637 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8638 }
8639
8640 // Check a specific declaration. There are three problematic cases:
8641 //
8642 // 1) The declaration is an explicit specialization of a template
8643 // specialization.
8644 // 2) The declaration is an explicit specialization of a member of an
8645 // templated class.
8646 // 3) The declaration is an instantiation of a template, and that template
8647 // is an explicit specialization of a member of a templated class.
8648 //
8649 // We don't need to go any deeper than that, as the instantiation of the
8650 // surrounding class / etc is not triggered by whatever triggered this
8651 // instantiation, and thus should be checked elsewhere.
8652 template<typename SpecDecl>
8653 void checkImpl(SpecDecl *Spec) {
8654 bool IsHiddenExplicitSpecialization = false;
8655 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8656 IsHiddenExplicitSpecialization =
8657 Spec->getMemberSpecializationInfo()
8658 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8659 : !S.hasVisibleDeclaration(Spec);
8660 } else {
8661 checkInstantiated(Spec);
8662 }
8663
8664 if (IsHiddenExplicitSpecialization)
8665 diagnose(Spec->getMostRecentDecl(), false);
8666 }
8667
8668 void checkInstantiated(FunctionDecl *FD) {
8669 if (auto *TD = FD->getPrimaryTemplate())
8670 checkTemplate(TD);
8671 }
8672
8673 void checkInstantiated(CXXRecordDecl *RD) {
8674 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8675 if (!SD)
8676 return;
8677
8678 auto From = SD->getSpecializedTemplateOrPartial();
8679 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8680 checkTemplate(TD);
8681 else if (auto *TD =
8682 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8683 if (!S.hasVisibleDeclaration(TD))
8684 diagnose(TD, true);
8685 checkTemplate(TD);
8686 }
8687 }
8688
8689 void checkInstantiated(VarDecl *RD) {
8690 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8691 if (!SD)
8692 return;
8693
8694 auto From = SD->getSpecializedTemplateOrPartial();
8695 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8696 checkTemplate(TD);
8697 else if (auto *TD =
8698 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8699 if (!S.hasVisibleDeclaration(TD))
8700 diagnose(TD, true);
8701 checkTemplate(TD);
8702 }
8703 }
8704
8705 void checkInstantiated(EnumDecl *FD) {}
8706
8707 template<typename TemplDecl>
8708 void checkTemplate(TemplDecl *TD) {
8709 if (TD->isMemberSpecialization()) {
8710 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8711 diagnose(TD->getMostRecentDecl(), false);
8712 }
8713 }
8714};
8715
8716void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8717 if (!getLangOpts().Modules)
8718 return;
8719
8720 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8721}
8722
8723/// \brief Check whether a template partial specialization that we've discovered
8724/// is hidden, and produce suitable diagnostics if so.
8725void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8726 NamedDecl *Spec) {
8727 llvm::SmallVector<Module *, 8> Modules;
8728 if (!hasVisibleDeclaration(Spec, &Modules))
8729 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8730 MissingImportKind::PartialSpecialization,
8731 /*Recover*/true);
8732}