blob: 58da453e2a8e58cc7a1d7ca098316ab376395cb1 [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
Serge Pavlove50bf752016-06-10 04:39:07 +0000932 if (PrevDecl && PrevDecl->isTemplateParameter()) {
933 // Maybe we will complain about the shadowed template parameter.
934 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
935 // Just pretend that we didn't see the previous declaration.
936 PrevDecl = nullptr;
937 }
938
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000939 // If there is a previous declaration with the same name, check
940 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000941 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000942 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000943
944 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000946 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000947 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000948 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
949 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000950 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000951 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
952 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
953 PrevClassTemplate
954 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
955 ->getSpecializedTemplate();
956 }
957 }
958
John McCalld43784f2009-12-18 11:25:59 +0000959 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000960 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961 // [...] When looking for a prior declaration of a class or a function
962 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000963 // function is neither a qualified name nor a template-id, scopes outside
964 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000965 if (!SS.isSet()) {
966 DeclContext *OutermostContext = CurContext;
967 while (!OutermostContext->isFileContext())
968 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000969
Richard Smith61e582f2012-04-20 07:12:26 +0000970 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000971 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
972 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
973 SemanticContext = PrevDecl->getDeclContext();
974 } else {
975 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000976 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000977 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000978 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000979 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000980
981 // Check that the chosen semantic context doesn't already contain a
982 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000983 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000984 DeclContext *LookupContext = SemanticContext;
985 while (LookupContext->isTransparentContext())
986 LookupContext = LookupContext->getLookupParent();
987 LookupQualifiedName(Previous, LookupContext);
988
989 if (Previous.isAmbiguous())
990 return true;
991
992 if (Previous.begin() != Previous.end())
993 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000994 }
John McCall90d3bb92009-12-17 23:21:11 +0000995 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000996 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000997 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
998 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000999 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000
Richard Smithfc805ca2015-07-06 04:43:58 +00001001 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1002 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1003 if (SS.isEmpty() &&
1004 !(PrevClassTemplate &&
1005 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1006 SemanticContext->getRedeclContext()))) {
1007 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1008 Diag(Shadow->getTargetDecl()->getLocation(),
1009 diag::note_using_decl_target);
1010 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1011 // Recover by ignoring the old declaration.
1012 PrevDecl = PrevClassTemplate = nullptr;
1013 }
1014 }
1015
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001016 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001017 // Ensure that the template parameter lists are compatible. Skip this check
1018 // for a friend in a dependent context: the template parameter list itself
1019 // could be dependent.
1020 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1021 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001022 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001023 /*Complain=*/true,
1024 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001025 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001026
1027 // C++ [temp.class]p4:
1028 // In a redeclaration, partial specialization, explicit
1029 // specialization or explicit instantiation of a class template,
1030 // the class-key shall agree in kind with the original class
1031 // template declaration (7.1.5.3).
1032 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001033 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001034 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001035 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001036 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001037 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001038 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001039 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040 }
1041
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001042 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001043 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001044 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001045 // If we have a prior definition that is not visible, treat this as
1046 // simply making that previous definition visible.
1047 NamedDecl *Hidden = nullptr;
1048 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001049 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001050 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1051 assert(Tmpl && "original definition of a class template is not a "
1052 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001053 makeMergedDefinitionVisible(Hidden, KWLoc);
1054 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001055 return Def;
1056 }
1057
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001058 Diag(NameLoc, diag::err_redefinition) << Name;
1059 Diag(Def->getLocation(), diag::note_previous_definition);
1060 // FIXME: Would it make sense to try to "forget" the previous
1061 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001062 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001063 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001064 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001065 } else if (PrevDecl) {
1066 // C++ [temp]p5:
1067 // A class template shall not have the same name as any other
1068 // template, class, function, object, enumeration, enumerator,
1069 // namespace, or type in the same scope (3.3), except as specified
1070 // in (14.5.4).
1071 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1072 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001073 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001074 }
1075
Douglas Gregordba32632009-02-10 19:49:53 +00001076 // Check the template parameter list of this declaration, possibly
1077 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001078 // template declaration. Skip this check for a friend in a dependent
1079 // context, because the template parameter list might be dependent.
1080 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001081 CheckTemplateParameterList(
1082 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001083 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1084 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001085 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1086 SemanticContext->isDependentContext())
1087 ? TPC_ClassTemplateMember
1088 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1089 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001090 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001091
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001092 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001094 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001095 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1096 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001097 : diag::err_member_decl_does_not_match)
1098 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001099 Invalid = true;
1100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101 }
1102
Mike Stump11289f42009-09-09 15:08:12 +00001103 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001104 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001105 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001106 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001107 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001108 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001109 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001110 NewClass->setTemplateParameterListsInfo(
1111 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1112 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001113
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001114 // Add alignment attributes if necessary; these attributes are checked when
1115 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001116 if (TUK == TUK_Definition) {
1117 AddAlignmentAttributesForRecord(NewClass);
1118 AddMsStructLayoutForRecord(NewClass);
1119 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001120
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001121 ClassTemplateDecl *NewTemplate
1122 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1123 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001124 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001125 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001126
Douglas Gregor21823bf2011-12-20 18:11:52 +00001127 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001128 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001129
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001130 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001131 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001132 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001133 assert(T->isDependentType() && "Class template type is not dependent?");
1134 (void)T;
1135
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001137 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001139 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1140 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141
Anders Carlsson137108d2009-03-26 01:24:28 +00001142 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001143 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001144 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001146 // Set the lexical context of these templates
1147 NewClass->setLexicalDeclContext(CurContext);
1148 NewTemplate->setLexicalDeclContext(CurContext);
1149
John McCall9bb74a52009-07-31 02:45:11 +00001150 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001151 NewClass->startDefinition();
1152
1153 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001154 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001155
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001156 if (PrevClassTemplate)
1157 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1158
Rafael Espindola385c0422012-07-13 18:04:45 +00001159 AddPushedVisibilityAttribute(NewClass);
1160
Richard Smith234ff472014-08-23 00:49:01 +00001161 if (TUK != TUK_Friend) {
1162 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1163 Scope *Outer = S;
1164 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1165 Outer = Outer->getParent();
1166 PushOnScopeChains(NewTemplate, Outer);
1167 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001168 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001169 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001170 NewClass->setAccess(PrevClassTemplate->getAccess());
1171 }
John McCall27b5c252009-09-14 21:59:20 +00001172
Richard Smith64017682013-07-17 23:53:16 +00001173 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001174
John McCall27b5c252009-09-14 21:59:20 +00001175 // Friend templates are visible in fairly strange ways.
1176 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001177 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001178 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001179 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1180 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001184 FriendDecl *Friend = FriendDecl::Create(
1185 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001186 Friend->setAccess(AS_public);
1187 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001188 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001189
Douglas Gregordba32632009-02-10 19:49:53 +00001190 if (Invalid) {
1191 NewTemplate->setInvalidDecl();
1192 NewClass->setInvalidDecl();
1193 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001194
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001195 ActOnDocumentableDecl(NewTemplate);
1196
John McCall48871652010-08-21 09:40:31 +00001197 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001198}
1199
Douglas Gregored5731f2009-11-25 17:50:39 +00001200/// \brief Diagnose the presence of a default template argument on a
1201/// template parameter, which is ill-formed in certain contexts.
1202///
1203/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001204static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001205 Sema::TemplateParamListContext TPC,
1206 SourceLocation ParamLoc,
1207 SourceRange DefArgRange) {
1208 switch (TPC) {
1209 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001210 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001211 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001212 return false;
1213
1214 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001215 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001216 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001217 // A default template-argument shall not be specified in a
1218 // function template declaration or a function template
1219 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001220 // If a friend function template declaration specifies a default
1221 // template-argument, that declaration shall be a definition and shall be
1222 // the only declaration of the function template in the translation unit.
1223 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001224 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001225 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1226 : diag::ext_template_parameter_default_in_function_template)
1227 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001228 return false;
1229
1230 case Sema::TPC_ClassTemplateMember:
1231 // C++0x [temp.param]p9:
1232 // A default template-argument shall not be specified in the
1233 // template-parameter-lists of the definition of a member of a
1234 // class template that appears outside of the member's class.
1235 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1236 << DefArgRange;
1237 return true;
1238
David Majnemerba8f17a2013-06-25 22:08:55 +00001239 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001240 case Sema::TPC_FriendFunctionTemplate:
1241 // C++ [temp.param]p9:
1242 // A default template-argument shall not be specified in a
1243 // friend template declaration.
1244 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1245 << DefArgRange;
1246 return true;
1247
1248 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1249 // for friend function templates if there is only a single
1250 // declaration (and it is a definition). Strange!
1251 }
1252
David Blaikie8a40f702012-01-17 06:56:22 +00001253 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001254}
1255
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001256/// \brief Check for unexpanded parameter packs within the template parameters
1257/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001258static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1259 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001260 // A template template parameter which is a parameter pack is also a pack
1261 // expansion.
1262 if (TTP->isParameterPack())
1263 return false;
1264
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001265 TemplateParameterList *Params = TTP->getTemplateParameters();
1266 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1267 NamedDecl *P = Params->getParam(I);
1268 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001269 if (!NTTP->isParameterPack() &&
1270 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001271 NTTP->getTypeSourceInfo(),
1272 Sema::UPPC_NonTypeTemplateParameterType))
1273 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001275 continue;
1276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001277
1278 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001279 = dyn_cast<TemplateTemplateParmDecl>(P))
1280 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1281 return true;
1282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001284 return false;
1285}
1286
Douglas Gregordba32632009-02-10 19:49:53 +00001287/// \brief Checks the validity of a template parameter list, possibly
1288/// considering the template parameter list from a previous
1289/// declaration.
1290///
1291/// If an "old" template parameter list is provided, it must be
1292/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1293/// template parameter list.
1294///
1295/// \param NewParams Template parameter list for a new template
1296/// declaration. This template parameter list will be updated with any
1297/// default arguments that are carried through from the previous
1298/// template parameter list.
1299///
1300/// \param OldParams If provided, template parameter list from a
1301/// previous declaration of the same template. Default template
1302/// arguments will be merged from the old template parameter list to
1303/// the new template parameter list.
1304///
Douglas Gregored5731f2009-11-25 17:50:39 +00001305/// \param TPC Describes the context in which we are checking the given
1306/// template parameter list.
1307///
Douglas Gregordba32632009-02-10 19:49:53 +00001308/// \returns true if an error occurred, false otherwise.
1309bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001310 TemplateParameterList *OldParams,
1311 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001312 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001313
Douglas Gregordba32632009-02-10 19:49:53 +00001314 // C++ [temp.param]p10:
1315 // The set of default template-arguments available for use with a
1316 // template declaration or definition is obtained by merging the
1317 // default arguments from the definition (if in scope) and all
1318 // declarations in scope in the same way default function
1319 // arguments are (8.3.6).
1320 bool SawDefaultArgument = false;
1321 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001322
Mike Stumpc89c8e32009-02-11 23:03:27 +00001323 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001324 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001325 if (OldParams)
1326 OldParam = OldParams->begin();
1327
Douglas Gregor0693def2011-01-27 01:40:17 +00001328 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001329 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1330 NewParamEnd = NewParams->end();
1331 NewParam != NewParamEnd; ++NewParam) {
1332 // Variables used to diagnose redundant default arguments
1333 bool RedundantDefaultArg = false;
1334 SourceLocation OldDefaultLoc;
1335 SourceLocation NewDefaultLoc;
1336
David Blaikie651c73c2011-10-19 05:19:50 +00001337 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001338 bool MissingDefaultArg = false;
1339
David Blaikie651c73c2011-10-19 05:19:50 +00001340 // Variable used to diagnose non-final parameter packs
1341 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001342
Douglas Gregordba32632009-02-10 19:49:53 +00001343 if (TemplateTypeParmDecl *NewTypeParm
1344 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001345 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001346 if (NewTypeParm->hasDefaultArgument() &&
1347 DiagnoseDefaultTemplateArgument(*this, TPC,
1348 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001349 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001350 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001351 NewTypeParm->removeDefaultArgument();
1352
1353 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001354 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001355 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001356 if (NewTypeParm->isParameterPack()) {
1357 assert(!NewTypeParm->hasDefaultArgument() &&
1358 "Parameter packs can't have a default argument!");
1359 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001360 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001361 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001362 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1363 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1364 SawDefaultArgument = true;
1365 RedundantDefaultArg = true;
1366 PreviousDefaultArgLoc = NewDefaultLoc;
1367 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1368 // Merge the default argument from the old declaration to the
1369 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001370 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001371 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1372 } else if (NewTypeParm->hasDefaultArgument()) {
1373 SawDefaultArgument = true;
1374 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1375 } else if (SawDefaultArgument)
1376 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001377 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001378 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001379 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001380 if (!NewNonTypeParm->isParameterPack() &&
1381 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001383 UPPC_NonTypeTemplateParameterType)) {
1384 Invalid = true;
1385 continue;
1386 }
1387
Douglas Gregored5731f2009-11-25 17:50:39 +00001388 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389 if (NewNonTypeParm->hasDefaultArgument() &&
1390 DiagnoseDefaultTemplateArgument(*this, TPC,
1391 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001392 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001393 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001394 }
1395
Mike Stump12b8ce12009-08-04 21:02:39 +00001396 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001397 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001398 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001399 if (NewNonTypeParm->isParameterPack()) {
1400 assert(!NewNonTypeParm->hasDefaultArgument() &&
1401 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001402 if (!NewNonTypeParm->isPackExpansion())
1403 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001404 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001405 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001406 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1407 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1408 SawDefaultArgument = true;
1409 RedundantDefaultArg = true;
1410 PreviousDefaultArgLoc = NewDefaultLoc;
1411 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1412 // Merge the default argument from the old declaration to the
1413 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001414 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001415 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1416 } else if (NewNonTypeParm->hasDefaultArgument()) {
1417 SawDefaultArgument = true;
1418 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1419 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001420 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001421 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001422 TemplateTemplateParmDecl *NewTemplateParm
1423 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001424
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001425 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001426 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001427 Invalid = true;
1428 continue;
1429 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430
David Blaikie651c73c2011-10-19 05:19:50 +00001431 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001432 if (NewTemplateParm->hasDefaultArgument() &&
1433 DiagnoseDefaultTemplateArgument(*this, TPC,
1434 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001435 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001436 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001437
1438 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001439 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001440 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001441 if (NewTemplateParm->isParameterPack()) {
1442 assert(!NewTemplateParm->hasDefaultArgument() &&
1443 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001444 if (!NewTemplateParm->isPackExpansion())
1445 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001446 } else if (OldTemplateParm &&
1447 hasVisibleDefaultArgument(OldTemplateParm) &&
1448 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001449 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1450 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001451 SawDefaultArgument = true;
1452 RedundantDefaultArg = true;
1453 PreviousDefaultArgLoc = NewDefaultLoc;
1454 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1455 // Merge the default argument from the old declaration to the
1456 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001457 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001458 PreviousDefaultArgLoc
1459 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001460 } else if (NewTemplateParm->hasDefaultArgument()) {
1461 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001462 PreviousDefaultArgLoc
1463 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001464 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001465 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001466 }
1467
Richard Smith1fde8ec2012-09-07 02:06:42 +00001468 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001469 // If a template parameter of a primary class template or alias template
1470 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001471 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001472 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1473 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001474 Diag((*NewParam)->getLocation(),
1475 diag::err_template_param_pack_must_be_last_template_parameter);
1476 Invalid = true;
1477 }
1478
Douglas Gregordba32632009-02-10 19:49:53 +00001479 if (RedundantDefaultArg) {
1480 // C++ [temp.param]p12:
1481 // A template-parameter shall not be given default arguments
1482 // by two different declarations in the same scope.
1483 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1484 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1485 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001486 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001487 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488 // If a template-parameter of a class template has a default
1489 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001490 // have a default template-argument supplied or be a template parameter
1491 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001492 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001493 diag::err_template_param_default_arg_missing);
1494 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1495 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001496 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001497 }
1498
1499 // If we have an old template parameter list that we're merging
1500 // in, move on to the next parameter.
1501 if (OldParams)
1502 ++OldParam;
1503 }
1504
Douglas Gregor0693def2011-01-27 01:40:17 +00001505 // We were missing some default arguments at the end of the list, so remove
1506 // all of the default arguments.
1507 if (RemoveDefaultArguments) {
1508 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1509 NewParamEnd = NewParams->end();
1510 NewParam != NewParamEnd; ++NewParam) {
1511 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1512 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001513 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001514 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1515 NTTP->removeDefaultArgument();
1516 else
1517 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1518 }
1519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
Douglas Gregordba32632009-02-10 19:49:53 +00001521 return Invalid;
1522}
Douglas Gregord32e0282009-02-09 23:23:08 +00001523
John McCalla020a012010-10-20 05:44:58 +00001524namespace {
1525
1526/// A class which looks for a use of a certain level of template
1527/// parameter.
1528struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1529 typedef RecursiveASTVisitor<DependencyChecker> super;
1530
1531 unsigned Depth;
1532 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001533 SourceLocation MatchLoc;
1534
1535 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001536
1537 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1538 NamedDecl *ND = Params->getParam(0);
1539 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1540 Depth = PD->getDepth();
1541 } else if (NonTypeTemplateParmDecl *PD =
1542 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1543 Depth = PD->getDepth();
1544 } else {
1545 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1546 }
1547 }
1548
Richard Smith6056d5e2014-02-09 00:54:43 +00001549 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001550 if (ParmDepth >= Depth) {
1551 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001552 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001553 return true;
1554 }
1555 return false;
1556 }
1557
Richard Smith6056d5e2014-02-09 00:54:43 +00001558 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1559 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1560 }
1561
John McCalla020a012010-10-20 05:44:58 +00001562 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1563 return !Matches(T->getDepth());
1564 }
1565
1566 bool TraverseTemplateName(TemplateName N) {
1567 if (TemplateTemplateParmDecl *PD =
1568 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001569 if (Matches(PD->getDepth()))
1570 return false;
John McCalla020a012010-10-20 05:44:58 +00001571 return super::TraverseTemplateName(N);
1572 }
1573
1574 bool VisitDeclRefExpr(DeclRefExpr *E) {
1575 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001576 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1577 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001578 return false;
John McCalla020a012010-10-20 05:44:58 +00001579 return super::VisitDeclRefExpr(E);
1580 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001581
1582 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1583 return TraverseType(T->getReplacementType());
1584 }
1585
1586 bool
1587 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1588 return TraverseTemplateArgument(T->getArgumentPack());
1589 }
1590
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001591 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1592 return TraverseType(T->getInjectedSpecializationType());
1593 }
John McCalla020a012010-10-20 05:44:58 +00001594};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001595} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001596
Douglas Gregor972fe532011-05-10 18:27:06 +00001597/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001598/// list.
1599static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001600DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001601 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001602 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001603 return Checker.Match;
1604}
1605
Douglas Gregor972fe532011-05-10 18:27:06 +00001606// Find the source range corresponding to the named type in the given
1607// nested-name-specifier, if any.
1608static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1609 QualType T,
1610 const CXXScopeSpec &SS) {
1611 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1612 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1613 if (const Type *CurType = NNS->getAsType()) {
1614 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1615 return NNSLoc.getTypeLoc().getSourceRange();
1616 } else
1617 break;
1618
1619 NNSLoc = NNSLoc.getPrefix();
1620 }
1621
1622 return SourceRange();
1623}
1624
Mike Stump11289f42009-09-09 15:08:12 +00001625/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001626/// specifier, returning the template parameter list that applies to the
1627/// name.
1628///
1629/// \param DeclStartLoc the start of the declaration that has a scope
1630/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001631///
Douglas Gregor972fe532011-05-10 18:27:06 +00001632/// \param DeclLoc The location of the declaration itself.
1633///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001634/// \param SS the scope specifier that will be matched to the given template
1635/// parameter lists. This scope specifier precedes a qualified name that is
1636/// being declared.
1637///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001638/// \param TemplateId The template-id following the scope specifier, if there
1639/// is one. Used to check for a missing 'template<>'.
1640///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001641/// \param ParamLists the template parameter lists, from the outermost to the
1642/// innermost template parameter lists.
1643///
John McCalle820e5e2010-04-13 20:37:33 +00001644/// \param IsFriend Whether to apply the slightly different rules for
1645/// matching template parameters to scope specifiers in friend
1646/// declarations.
1647///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001648/// \param IsExplicitSpecialization will be set true if the entity being
1649/// declared is an explicit specialization, false otherwise.
1650///
Mike Stump11289f42009-09-09 15:08:12 +00001651/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001652/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001653/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001654/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001655/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001656/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001657TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1658 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001659 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001660 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1661 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001662 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001663 Invalid = false;
1664
1665 // The sequence of nested types to which we will match up the template
1666 // parameter lists. We first build this list by starting with the type named
1667 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001668 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001669 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001670 if (SS.getScopeRep()) {
1671 if (CXXRecordDecl *Record
1672 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1673 T = Context.getTypeDeclType(Record);
1674 else
1675 T = QualType(SS.getScopeRep()->getAsType(), 0);
1676 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001677
1678 // If we found an explicit specialization that prevents us from needing
1679 // 'template<>' headers, this will be set to the location of that
1680 // explicit specialization.
1681 SourceLocation ExplicitSpecLoc;
1682
1683 while (!T.isNull()) {
1684 NestedTypes.push_back(T);
1685
1686 // Retrieve the parent of a record type.
1687 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1688 // If this type is an explicit specialization, we're done.
1689 if (ClassTemplateSpecializationDecl *Spec
1690 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1691 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1692 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1693 ExplicitSpecLoc = Spec->getLocation();
1694 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001695 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001696 } else if (Record->getTemplateSpecializationKind()
1697 == TSK_ExplicitSpecialization) {
1698 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001699 break;
1700 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001701
1702 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1703 T = Context.getTypeDeclType(Parent);
1704 else
1705 T = QualType();
1706 continue;
1707 }
1708
1709 if (const TemplateSpecializationType *TST
1710 = T->getAs<TemplateSpecializationType>()) {
1711 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1712 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1713 T = Context.getTypeDeclType(Parent);
1714 else
1715 T = QualType();
1716 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001717 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001718 }
1719
1720 // Look one step prior in a dependent template specialization type.
1721 if (const DependentTemplateSpecializationType *DependentTST
1722 = T->getAs<DependentTemplateSpecializationType>()) {
1723 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1724 T = QualType(NNS->getAsType(), 0);
1725 else
1726 T = QualType();
1727 continue;
1728 }
1729
1730 // Look one step prior in a dependent name type.
1731 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1732 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1733 T = QualType(NNS->getAsType(), 0);
1734 else
1735 T = QualType();
1736 continue;
1737 }
1738
1739 // Retrieve the parent of an enumeration type.
1740 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1741 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1742 // check here.
1743 EnumDecl *Enum = EnumT->getDecl();
1744
1745 // Get to the parent type.
1746 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1747 T = Context.getTypeDeclType(Parent);
1748 else
1749 T = QualType();
1750 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
Douglas Gregor972fe532011-05-10 18:27:06 +00001753 T = QualType();
1754 }
1755 // Reverse the nested types list, since we want to traverse from the outermost
1756 // to the innermost while checking template-parameter-lists.
1757 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001758
Douglas Gregor972fe532011-05-10 18:27:06 +00001759 // C++0x [temp.expl.spec]p17:
1760 // A member or a member template may be nested within many
1761 // enclosing class templates. In an explicit specialization for
1762 // such a member, the member declaration shall be preceded by a
1763 // template<> for each enclosing class template that is
1764 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001765 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001766
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001767 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001768 if (SawNonEmptyTemplateParameterList) {
1769 Diag(DeclLoc, diag::err_specialize_member_of_template)
1770 << !Recovery << Range;
1771 Invalid = true;
1772 IsExplicitSpecialization = false;
1773 return true;
1774 }
1775
1776 return false;
1777 };
1778
1779 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1780 // Check that we can have an explicit specialization here.
1781 if (CheckExplicitSpecialization(Range, true))
1782 return true;
1783
1784 // We don't have a template header, but we should.
1785 SourceLocation ExpectedTemplateLoc;
1786 if (!ParamLists.empty())
1787 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1788 else
1789 ExpectedTemplateLoc = DeclStartLoc;
1790
1791 Diag(DeclLoc, diag::err_template_spec_needs_header)
1792 << Range
1793 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1794 return false;
1795 };
1796
Douglas Gregor972fe532011-05-10 18:27:06 +00001797 unsigned ParamIdx = 0;
1798 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1799 ++TypeIdx) {
1800 T = NestedTypes[TypeIdx];
1801
1802 // Whether we expect a 'template<>' header.
1803 bool NeedEmptyTemplateHeader = false;
1804
1805 // Whether we expect a template header with parameters.
1806 bool NeedNonemptyTemplateHeader = false;
1807
1808 // For a dependent type, the set of template parameters that we
1809 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001810 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001811
Douglas Gregor373af9b2011-05-11 23:26:17 +00001812 // C++0x [temp.expl.spec]p15:
1813 // A member or a member template may be nested within many enclosing
1814 // class templates. In an explicit specialization for such a member, the
1815 // member declaration shall be preceded by a template<> for each
1816 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001817 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1818 if (ClassTemplatePartialSpecializationDecl *Partial
1819 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1820 ExpectedTemplateParams = Partial->getTemplateParameters();
1821 NeedNonemptyTemplateHeader = true;
1822 } else if (Record->isDependentType()) {
1823 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001824 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001825 ->getTemplateParameters();
1826 NeedNonemptyTemplateHeader = true;
1827 }
1828 } else if (ClassTemplateSpecializationDecl *Spec
1829 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1830 // C++0x [temp.expl.spec]p4:
1831 // Members of an explicitly specialized class template are defined
1832 // in the same manner as members of normal classes, and not using
1833 // the template<> syntax.
1834 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1835 NeedEmptyTemplateHeader = true;
1836 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001837 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001838 } else if (Record->getTemplateSpecializationKind()) {
1839 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001840 != TSK_ExplicitSpecialization &&
1841 TypeIdx == NumTypes - 1)
1842 IsExplicitSpecialization = true;
1843
1844 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001845 }
1846 } else if (const TemplateSpecializationType *TST
1847 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001848 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001849 ExpectedTemplateParams = Template->getTemplateParameters();
1850 NeedNonemptyTemplateHeader = true;
1851 }
1852 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1853 // FIXME: We actually could/should check the template arguments here
1854 // against the corresponding template parameter list.
1855 NeedNonemptyTemplateHeader = false;
1856 }
1857
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001858 // C++ [temp.expl.spec]p16:
1859 // In an explicit specialization declaration for a member of a class
1860 // template or a member template that ap- pears in namespace scope, the
1861 // member template and some of its enclosing class templates may remain
1862 // unspecialized, except that the declaration shall not explicitly
1863 // specialize a class member template if its en- closing class templates
1864 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001865 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001866 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001867 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1868 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001869 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001870 } else
1871 SawNonEmptyTemplateParameterList = true;
1872 }
1873
Douglas Gregor972fe532011-05-10 18:27:06 +00001874 if (NeedEmptyTemplateHeader) {
1875 // If we're on the last of the types, and we need a 'template<>' header
1876 // here, then it's an explicit specialization.
1877 if (TypeIdx == NumTypes - 1)
1878 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001879
1880 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001881 if (ParamLists[ParamIdx]->size() > 0) {
1882 // The header has template parameters when it shouldn't. Complain.
1883 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1884 diag::err_template_param_list_matches_nontemplate)
1885 << T
1886 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1887 ParamLists[ParamIdx]->getRAngleLoc())
1888 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1889 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001890 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001891 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001892
Douglas Gregor972fe532011-05-10 18:27:06 +00001893 // Consume this template header.
1894 ++ParamIdx;
1895 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001896 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001897
1898 if (!IsFriend)
1899 if (DiagnoseMissingExplicitSpecialization(
1900 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001901 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001902
Douglas Gregor972fe532011-05-10 18:27:06 +00001903 continue;
1904 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001905
Douglas Gregor972fe532011-05-10 18:27:06 +00001906 if (NeedNonemptyTemplateHeader) {
1907 // In friend declarations we can have template-ids which don't
1908 // depend on the corresponding template parameter lists. But
1909 // assume that empty parameter lists are supposed to match this
1910 // template-id.
1911 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001912 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001913 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001914 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001915 else
1916 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001917 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001918
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001919 if (ParamIdx < ParamLists.size()) {
1920 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001921 if (ExpectedTemplateParams &&
1922 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1923 ExpectedTemplateParams,
1924 true, TPL_TemplateMatch))
1925 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001926
Douglas Gregor972fe532011-05-10 18:27:06 +00001927 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001928 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001929 TPC_ClassTemplateMember))
1930 Invalid = true;
1931
1932 ++ParamIdx;
1933 continue;
1934 }
1935
1936 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1937 << T
1938 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1939 Invalid = true;
1940 continue;
1941 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001942 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001943
Douglas Gregord8d297c2009-07-21 23:53:31 +00001944 // If there were at least as many template-ids as there were template
1945 // parameter lists, then there are no template parameter lists remaining for
1946 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001947 if (ParamIdx >= ParamLists.size()) {
1948 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001949 // We don't have a template header for the declaration itself, but we
1950 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001951 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001952 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1953 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001954
1955 // Fabricate an empty template parameter list for the invented header.
1956 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00001957 SourceLocation(), None,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001958 SourceLocation());
1959 }
1960
Craig Topperc3ec1492014-05-26 06:22:03 +00001961 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregord8d297c2009-07-21 23:53:31 +00001964 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001965 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001966 bool HasAnyExplicitSpecHeader = false;
1967 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001968 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001969 if (ParamLists[I]->size() == 0)
1970 HasAnyExplicitSpecHeader = true;
1971 else
1972 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001973 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001974
Douglas Gregor972fe532011-05-10 18:27:06 +00001975 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001976 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1977 : diag::err_template_spec_extra_headers)
1978 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1979 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001980
1981 // If there was a specialization somewhere, such that 'template<>' is
1982 // not required, and there were any 'template<>' headers, note where the
1983 // specialization occurred.
1984 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1985 Diag(ExplicitSpecLoc,
1986 diag::note_explicit_template_spec_does_not_need_header)
1987 << NestedTypes.back();
1988
1989 // We have a template parameter list with no corresponding scope, which
1990 // means that the resulting template declaration can't be instantiated
1991 // properly (we'll end up with dependent nodes when we shouldn't).
1992 if (!AllExplicitSpecHeaders)
1993 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001994 }
Mike Stump11289f42009-09-09 15:08:12 +00001995
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001996 // C++ [temp.expl.spec]p16:
1997 // In an explicit specialization declaration for a member of a class
1998 // template or a member template that ap- pears in namespace scope, the
1999 // member template and some of its enclosing class templates may remain
2000 // unspecialized, except that the declaration shall not explicitly
2001 // specialize a class member template if its en- closing class templates
2002 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002003 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002004 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2005 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002006 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002007
Douglas Gregord8d297c2009-07-21 23:53:31 +00002008 // Return the last template parameter list, which corresponds to the
2009 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002010 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002011}
2012
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002013void Sema::NoteAllFoundTemplates(TemplateName Name) {
2014 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2015 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002016 << (isa<FunctionTemplateDecl>(Template)
2017 ? 0
2018 : isa<ClassTemplateDecl>(Template)
2019 ? 1
2020 : isa<VarTemplateDecl>(Template)
2021 ? 2
2022 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2023 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002024 return;
2025 }
2026
2027 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2028 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2029 IEnd = OST->end();
2030 I != IEnd; ++I)
2031 Diag((*I)->getLocation(), diag::note_template_declared_here)
2032 << 0 << (*I)->getDeclName();
2033
2034 return;
2035 }
2036}
2037
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002038static QualType
2039checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2040 const SmallVectorImpl<TemplateArgument> &Converted,
2041 SourceLocation TemplateLoc,
2042 TemplateArgumentListInfo &TemplateArgs) {
2043 ASTContext &Context = SemaRef.getASTContext();
2044 switch (BTD->getBuiltinTemplateKind()) {
2045 case BTK__make_integer_seq:
2046 // Specializations of __make_integer_seq<S, T, N> are treated like
2047 // S<T, 0, ..., N-1>.
2048
2049 // C++14 [inteseq.intseq]p1:
2050 // T shall be an integer type.
2051 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2052 SemaRef.Diag(TemplateArgs[1].getLocation(),
2053 diag::err_integer_sequence_integral_element_type);
2054 return QualType();
2055 }
2056
2057 // C++14 [inteseq.make]p1:
2058 // If N is negative the program is ill-formed.
2059 TemplateArgument NumArgsArg = Converted[2];
2060 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2061 if (NumArgs < 0) {
2062 SemaRef.Diag(TemplateArgs[2].getLocation(),
2063 diag::err_integer_sequence_negative_length);
2064 return QualType();
2065 }
2066
2067 QualType ArgTy = NumArgsArg.getIntegralType();
2068 TemplateArgumentListInfo SyntheticTemplateArgs;
2069 // The type argument gets reused as the first template argument in the
2070 // synthetic template argument list.
2071 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2072 // Expand N into 0 ... N-1.
2073 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2074 I < NumArgs; ++I) {
2075 TemplateArgument TA(Context, I, ArgTy);
2076 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2077 TA, TemplateArgs[2].getLocation())
2078 .getAs<Expr>();
2079 SyntheticTemplateArgs.addArgument(
2080 TemplateArgumentLoc(TemplateArgument(E), E));
2081 }
2082 // The first template argument will be reused as the template decl that
2083 // our synthetic template arguments will be applied to.
2084 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2085 TemplateLoc, SyntheticTemplateArgs);
2086 }
2087 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2088}
2089
Douglas Gregordc572a32009-03-30 22:58:21 +00002090QualType Sema::CheckTemplateIdType(TemplateName Name,
2091 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002092 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002093 DependentTemplateName *DTN
2094 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002095 if (DTN && DTN->isIdentifier())
2096 // When building a template-id where the template-name is dependent,
2097 // assume the template is a type template. Either our assumption is
2098 // correct, or the code is ill-formed and will be diagnosed when the
2099 // dependent name is substituted.
2100 return Context.getDependentTemplateSpecializationType(ETK_None,
2101 DTN->getQualifier(),
2102 DTN->getIdentifier(),
2103 TemplateArgs);
2104
Douglas Gregordc572a32009-03-30 22:58:21 +00002105 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002106 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2107 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002108 // We might have a substituted template template parameter pack. If so,
2109 // build a template specialization type for it.
2110 if (Name.getAsSubstTemplateTemplateParmPack())
2111 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002112
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002113 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2114 << Name;
2115 NoteAllFoundTemplates(Name);
2116 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002117 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002118
Douglas Gregorc40290e2009-03-09 23:48:35 +00002119 // Check that the template argument list is well-formed for this
2120 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002121 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002122 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002123 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002124 return QualType();
2125
Douglas Gregorc40290e2009-03-09 23:48:35 +00002126 QualType CanonType;
2127
Douglas Gregor678d76c2011-07-01 01:22:09 +00002128 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002129 if (TypeAliasTemplateDecl *AliasTemplate =
2130 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002131 // Find the canonical type for this type alias template specialization.
2132 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2133 if (Pattern->isInvalidDecl())
2134 return QualType();
2135
2136 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2137 Converted.data(), Converted.size());
2138
2139 // Only substitute for the innermost template argument list.
2140 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002141 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002142 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2143 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002144 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002145
Richard Smith802c4b72012-08-23 06:16:52 +00002146 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002147 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002148 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002149 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002150
Richard Smith3f1b5d02011-05-05 21:57:07 +00002151 CanonType = SubstType(Pattern->getUnderlyingType(),
2152 TemplateArgLists, AliasTemplate->getLocation(),
2153 AliasTemplate->getDeclName());
2154 if (CanonType.isNull())
2155 return QualType();
2156 } else if (Name.isDependent() ||
2157 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002158 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002159 // This class template specialization is a dependent
2160 // type. Therefore, its canonical type is another class template
2161 // specialization type that contains all of the converted
2162 // arguments in canonical form. This ensures that, e.g., A<T> and
2163 // A<T, T> have identical types when A is declared as:
2164 //
2165 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002166 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002167 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002168 Converted.data(),
2169 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002170
Douglas Gregora8e02e72009-07-28 23:00:59 +00002171 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002172 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002173 // In the future, we need to teach getTemplateSpecializationType to only
2174 // build the canonical type and return that to us.
2175 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002176
2177 // This might work out to be a current instantiation, in which
2178 // case the canonical type needs to be the InjectedClassNameType.
2179 //
2180 // TODO: in theory this could be a simple hashtable lookup; most
2181 // changes to CurContext don't change the set of current
2182 // instantiations.
2183 if (isa<ClassTemplateDecl>(Template)) {
2184 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2185 // If we get out to a namespace, we're done.
2186 if (Ctx->isFileContext()) break;
2187
2188 // If this isn't a record, keep looking.
2189 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2190 if (!Record) continue;
2191
2192 // Look for one of the two cases with InjectedClassNameTypes
2193 // and check whether it's the same template.
2194 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2195 !Record->getDescribedClassTemplate())
2196 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
John McCall2408e322010-04-27 00:57:59 +00002198 // Fetch the injected class name type and check whether its
2199 // injected type is equal to the type we just built.
2200 QualType ICNT = Context.getTypeDeclType(Record);
2201 QualType Injected = cast<InjectedClassNameType>(ICNT)
2202 ->getInjectedSpecializationType();
2203
2204 if (CanonType != Injected->getCanonicalTypeInternal())
2205 continue;
2206
2207 // If so, the canonical type of this TST is the injected
2208 // class name type of the record we just found.
2209 assert(ICNT.isCanonical());
2210 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002211 break;
2212 }
2213 }
Mike Stump11289f42009-09-09 15:08:12 +00002214 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002215 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002216 // Find the class template specialization declaration that
2217 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002218 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002219 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002220 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002221 if (!Decl) {
2222 // This is the first time we have referenced this class template
2223 // specialization. Create the canonical declaration and add it to
2224 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002225 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002226 ClassTemplate->getTemplatedDecl()->getTagKind(),
2227 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002228 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002229 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002230 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002231 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002232 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002233 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002234 if (ClassTemplate->isOutOfLine())
2235 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002236 }
2237
Chandler Carruth2acfb222013-09-27 22:14:40 +00002238 // Diagnose uses of this specialization.
2239 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2240
Douglas Gregorc40290e2009-03-09 23:48:35 +00002241 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002242 assert(isa<RecordType>(CanonType) &&
2243 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002244 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2245 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2246 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Douglas Gregorc40290e2009-03-09 23:48:35 +00002249 // Build the fully-sugared type for this class template
2250 // specialization, which refers back to the class template
2251 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002252 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002253}
2254
John McCallfaf5fb42010-08-26 23:41:50 +00002255TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002256Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002257 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002258 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002259 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002260 SourceLocation RAngleLoc,
2261 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002262 if (SS.isInvalid())
2263 return true;
2264
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002265 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002266
Douglas Gregorc40290e2009-03-09 23:48:35 +00002267 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002268 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002269 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002270
Douglas Gregor5a064722011-02-28 17:23:35 +00002271 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002272 QualType T
2273 = Context.getDependentTemplateSpecializationType(ETK_None,
2274 DTN->getQualifier(),
2275 DTN->getIdentifier(),
2276 TemplateArgs);
2277 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002278 TypeLocBuilder TLB;
2279 DependentTemplateSpecializationTypeLoc SpecTL
2280 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002281 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2282 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002283 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002284 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002285 SpecTL.setLAngleLoc(LAngleLoc);
2286 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002287 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2288 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2289 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2290 }
2291
John McCall6b51f282009-11-23 01:53:49 +00002292 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002293
2294 if (Result.isNull())
2295 return true;
2296
Douglas Gregore7c20652011-03-02 00:47:37 +00002297 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002298 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002299 TemplateSpecializationTypeLoc SpecTL
2300 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002301 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002302 SpecTL.setTemplateNameLoc(TemplateLoc);
2303 SpecTL.setLAngleLoc(LAngleLoc);
2304 SpecTL.setRAngleLoc(RAngleLoc);
2305 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2306 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002307
Abramo Bagnara4244b432012-01-27 08:46:19 +00002308 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2309 // constructor or destructor name (in such a case, the scope specifier
2310 // will be attached to the enclosing Decl or Expr node).
2311 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002312 // Create an elaborated-type-specifier containing the nested-name-specifier.
2313 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2314 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002315 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002316 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2317 }
2318
2319 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002320}
John McCall06f6fe8d2009-09-04 01:14:41 +00002321
Douglas Gregore7c20652011-03-02 00:47:37 +00002322TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002323 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002324 SourceLocation TagLoc,
2325 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002326 SourceLocation TemplateKWLoc,
2327 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002328 SourceLocation TemplateLoc,
2329 SourceLocation LAngleLoc,
2330 ASTTemplateArgsPtr TemplateArgsIn,
2331 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002332 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002333
2334 // Translate the parser's template argument list in our AST format.
2335 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2336 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2337
2338 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002339 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002340 ElaboratedTypeKeyword Keyword
2341 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002342
Douglas Gregore7c20652011-03-02 00:47:37 +00002343 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2344 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2345 DTN->getQualifier(),
2346 DTN->getIdentifier(),
2347 TemplateArgs);
2348
2349 // Build type-source information.
2350 TypeLocBuilder TLB;
2351 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002352 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2353 SpecTL.setElaboratedKeywordLoc(TagLoc);
2354 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002355 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002356 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002357 SpecTL.setLAngleLoc(LAngleLoc);
2358 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002359 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2360 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2361 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2362 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002363
2364 if (TypeAliasTemplateDecl *TAT =
2365 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2366 // C++0x [dcl.type.elab]p2:
2367 // If the identifier resolves to a typedef-name or the simple-template-id
2368 // resolves to an alias template specialization, the
2369 // elaborated-type-specifier is ill-formed.
2370 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2371 Diag(TAT->getLocation(), diag::note_declared_at);
2372 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002373
2374 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2375 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002376 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002377
2378 // Check the tag kind
2379 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002380 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002381
John McCalld8fe9af2009-09-08 17:47:29 +00002382 IdentifierInfo *Id = D->getIdentifier();
2383 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002384
Richard Trieucaa33d32011-06-10 03:11:26 +00002385 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002386 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002387 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002388 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002389 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002390 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002391 }
2392 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002393
Douglas Gregore7c20652011-03-02 00:47:37 +00002394 // Provide source-location information for the template specialization.
2395 TypeLocBuilder TLB;
2396 TemplateSpecializationTypeLoc SpecTL
2397 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002398 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002399 SpecTL.setTemplateNameLoc(TemplateLoc);
2400 SpecTL.setLAngleLoc(LAngleLoc);
2401 SpecTL.setRAngleLoc(RAngleLoc);
2402 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2403 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002404
Douglas Gregore7c20652011-03-02 00:47:37 +00002405 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002406 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002407 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2408 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002409 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002410 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2411 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002412}
2413
Larisse Voufo39a1e502013-08-06 01:03:05 +00002414static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002415 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2416 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002417
2418static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2419 NamedDecl *PrevDecl,
2420 SourceLocation Loc,
2421 bool IsPartialSpecialization);
2422
2423static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002424
Richard Smith300e0c32013-09-24 04:49:23 +00002425static bool isTemplateArgumentTemplateParameter(
2426 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2427 switch (Arg.getKind()) {
2428 case TemplateArgument::Null:
2429 case TemplateArgument::NullPtr:
2430 case TemplateArgument::Integral:
2431 case TemplateArgument::Declaration:
2432 case TemplateArgument::Pack:
2433 case TemplateArgument::TemplateExpansion:
2434 return false;
2435
2436 case TemplateArgument::Type: {
2437 QualType Type = Arg.getAsType();
2438 const TemplateTypeParmType *TPT =
2439 Arg.getAsType()->getAs<TemplateTypeParmType>();
2440 return TPT && !Type.hasQualifiers() &&
2441 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2442 }
2443
2444 case TemplateArgument::Expression: {
2445 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2446 if (!DRE || !DRE->getDecl())
2447 return false;
2448 const NonTypeTemplateParmDecl *NTTP =
2449 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2450 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2451 }
2452
2453 case TemplateArgument::Template:
2454 const TemplateTemplateParmDecl *TTP =
2455 dyn_cast_or_null<TemplateTemplateParmDecl>(
2456 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2457 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2458 }
2459 llvm_unreachable("unexpected kind of template argument");
2460}
2461
2462static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2463 ArrayRef<TemplateArgument> Args) {
2464 if (Params->size() != Args.size())
2465 return false;
2466
2467 unsigned Depth = Params->getDepth();
2468
2469 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2470 TemplateArgument Arg = Args[I];
2471
2472 // If the parameter is a pack expansion, the argument must be a pack
2473 // whose only element is a pack expansion.
2474 if (Params->getParam(I)->isParameterPack()) {
2475 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2476 !Arg.pack_begin()->isPackExpansion())
2477 return false;
2478 Arg = Arg.pack_begin()->getPackExpansionPattern();
2479 }
2480
2481 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2482 return false;
2483 }
2484
2485 return true;
2486}
2487
Richard Smith4b55a9c2014-04-17 03:29:33 +00002488/// Convert the parser's template argument list representation into our form.
2489static TemplateArgumentListInfo
2490makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2491 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2492 TemplateId.RAngleLoc);
2493 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2494 TemplateId.NumArgs);
2495 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2496 return TemplateArgs;
2497}
2498
Larisse Voufo39a1e502013-08-06 01:03:05 +00002499DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002500 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002501 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002502 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002503 // D must be variable template id.
2504 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2505 "Variable template specialization is declared with a template it.");
2506
2507 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002508 TemplateArgumentListInfo TemplateArgs =
2509 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002510 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2511 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2512 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002513
Richard Smithbeef3452014-01-16 23:39:20 +00002514 TemplateName Name = TemplateId->Template.get();
2515
2516 // The template-id must name a variable template.
2517 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002518 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2519 if (!VarTemplate) {
2520 NamedDecl *FnTemplate;
2521 if (auto *OTS = Name.getAsOverloadedTemplate())
2522 FnTemplate = *OTS->begin();
2523 else
2524 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2525 if (FnTemplate)
2526 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2527 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002528 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2529 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002530 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002531
2532 // Check for unexpanded parameter packs in any of the template arguments.
2533 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2534 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2535 UPPC_PartialSpecialization))
2536 return true;
2537
2538 // Check that the template argument list is well-formed for this
2539 // template.
2540 SmallVector<TemplateArgument, 4> Converted;
2541 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2542 false, Converted))
2543 return true;
2544
Larisse Voufo39a1e502013-08-06 01:03:05 +00002545 // Find the variable template (partial) specialization declaration that
2546 // corresponds to these arguments.
2547 if (IsPartialSpecialization) {
2548 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002549 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2550 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002551 return true;
2552
2553 bool InstantiationDependent;
2554 if (!Name.isDependent() &&
2555 !TemplateSpecializationType::anyDependentTemplateArguments(
2556 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2557 InstantiationDependent)) {
2558 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2559 << VarTemplate->getDeclName();
2560 IsPartialSpecialization = false;
2561 }
Richard Smith300e0c32013-09-24 04:49:23 +00002562
2563 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2564 Converted)) {
2565 // C++ [temp.class.spec]p9b3:
2566 //
2567 // -- The argument list of the specialization shall not be identical
2568 // to the implicit argument list of the primary template.
2569 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2570 << /*variable template*/ 1
2571 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2572 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2573 // FIXME: Recover from this by treating the declaration as a redeclaration
2574 // of the primary template.
2575 return true;
2576 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002577 }
2578
Craig Topperc3ec1492014-05-26 06:22:03 +00002579 void *InsertPos = nullptr;
2580 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002581
2582 if (IsPartialSpecialization)
2583 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002584 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002585 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002586 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002587
Craig Topperc3ec1492014-05-26 06:22:03 +00002588 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002589
2590 // Check whether we can declare a variable template specialization in
2591 // the current scope.
2592 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2593 TemplateNameLoc,
2594 IsPartialSpecialization))
2595 return true;
2596
2597 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2598 // Since the only prior variable template specialization with these
2599 // arguments was referenced but not declared, reuse that
2600 // declaration node as our own, updating its source location and
2601 // the list of outer template parameters to reflect our new declaration.
2602 Specialization = PrevDecl;
2603 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002604 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002605 } else if (IsPartialSpecialization) {
2606 // Create a new class template partial specialization declaration node.
2607 VarTemplatePartialSpecializationDecl *PrevPartial =
2608 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002609 VarTemplatePartialSpecializationDecl *Partial =
2610 VarTemplatePartialSpecializationDecl::Create(
2611 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2612 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002613 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002614
2615 if (!PrevPartial)
2616 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2617 Specialization = Partial;
2618
2619 // If we are providing an explicit specialization of a member variable
2620 // template specialization, make a note of that.
2621 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002622 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002623
2624 // Check that all of the template parameters of the variable template
2625 // partial specialization are deducible from the template
2626 // arguments. If not, this variable template partial specialization
2627 // will never be used.
2628 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2629 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2630 TemplateParams->getDepth(), DeducibleParams);
2631
2632 if (!DeducibleParams.all()) {
2633 unsigned NumNonDeducible =
2634 DeducibleParams.size() - DeducibleParams.count();
2635 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002636 << /*variable template*/ 1 << (NumNonDeducible > 1)
2637 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002638 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2639 if (!DeducibleParams[I]) {
2640 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2641 if (Param->getDeclName())
2642 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2643 << Param->getDeclName();
2644 else
2645 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002646 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002647 }
2648 }
2649 }
2650 } else {
2651 // Create a new class template specialization declaration node for
2652 // this explicit specialization or friend declaration.
2653 Specialization = VarTemplateSpecializationDecl::Create(
2654 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2655 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2656 Specialization->setTemplateArgsInfo(TemplateArgs);
2657
2658 if (!PrevDecl)
2659 VarTemplate->AddSpecialization(Specialization, InsertPos);
2660 }
2661
2662 // C++ [temp.expl.spec]p6:
2663 // If a template, a member template or the member of a class template is
2664 // explicitly specialized then that specialization shall be declared
2665 // before the first use of that specialization that would cause an implicit
2666 // instantiation to take place, in every translation unit in which such a
2667 // use occurs; no diagnostic is required.
2668 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2669 bool Okay = false;
2670 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2671 // Is there any previous explicit specialization declaration?
2672 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2673 Okay = true;
2674 break;
2675 }
2676 }
2677
2678 if (!Okay) {
2679 SourceRange Range(TemplateNameLoc, RAngleLoc);
2680 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2681 << Name << Range;
2682
2683 Diag(PrevDecl->getPointOfInstantiation(),
2684 diag::note_instantiation_required_here)
2685 << (PrevDecl->getTemplateSpecializationKind() !=
2686 TSK_ImplicitInstantiation);
2687 return true;
2688 }
2689 }
2690
2691 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2692 Specialization->setLexicalDeclContext(CurContext);
2693
2694 // Add the specialization into its lexical context, so that it can
2695 // be seen when iterating through the list of declarations in that
2696 // context. However, specializations are not found by name lookup.
2697 CurContext->addDecl(Specialization);
2698
2699 // Note that this is an explicit specialization.
2700 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2701
2702 if (PrevDecl) {
2703 // Check that this isn't a redefinition of this specialization,
2704 // merging with previous declarations.
2705 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2706 ForRedeclaration);
2707 PrevSpec.addDecl(PrevDecl);
2708 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002709 } else if (Specialization->isStaticDataMember() &&
2710 Specialization->isOutOfLine()) {
2711 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002712 }
2713
2714 // Link instantiations of static data members back to the template from
2715 // which they were instantiated.
2716 if (Specialization->isStaticDataMember())
2717 Specialization->setInstantiationOfStaticDataMember(
2718 VarTemplate->getTemplatedDecl(),
2719 Specialization->getSpecializationKind());
2720
2721 return Specialization;
2722}
2723
2724namespace {
2725/// \brief A partial specialization whose template arguments have matched
2726/// a given template-id.
2727struct PartialSpecMatchResult {
2728 VarTemplatePartialSpecializationDecl *Partial;
2729 TemplateArgumentList *Args;
2730};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002731} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002732
2733DeclResult
2734Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2735 SourceLocation TemplateNameLoc,
2736 const TemplateArgumentListInfo &TemplateArgs) {
2737 assert(Template && "A variable template id without template?");
2738
2739 // Check that the template argument list is well-formed for this template.
2740 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002741 if (CheckTemplateArgumentList(
2742 Template, TemplateNameLoc,
2743 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002744 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002745 return true;
2746
2747 // Find the variable template specialization declaration that
2748 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002749 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002750 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002751 Converted, InsertPos)) {
2752 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002753 // If we already have a variable template specialization, return it.
2754 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002755 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002756
2757 // This is the first time we have referenced this variable template
2758 // specialization. Create the canonical declaration and add it to
2759 // the set of specializations, based on the closest partial specialization
2760 // that it represents. That is,
2761 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2762 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2763 Converted.data(), Converted.size());
2764 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2765 bool AmbiguousPartialSpec = false;
2766 typedef PartialSpecMatchResult MatchResult;
2767 SmallVector<MatchResult, 4> Matched;
2768 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002769 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2770 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002771
2772 // 1. Attempt to find the closest partial specialization that this
2773 // specializes, if any.
2774 // If any of the template arguments is dependent, then this is probably
2775 // a placeholder for an incomplete declarative context; which must be
2776 // complete by instantiation time. Thus, do not search through the partial
2777 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002778 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2779 // Perhaps better after unification of DeduceTemplateArguments() and
2780 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002781 bool InstantiationDependent = false;
2782 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2783 TemplateArgs, InstantiationDependent)) {
2784
2785 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2786 Template->getPartialSpecializations(PartialSpecs);
2787
2788 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2789 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2790 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2791
2792 if (TemplateDeductionResult Result =
2793 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2794 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002795 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002796 FailedCandidates.addCandidate().set(
2797 DeclAccessPair::make(Template, AS_public), Partial,
2798 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002799 (void)Result;
2800 } else {
2801 Matched.push_back(PartialSpecMatchResult());
2802 Matched.back().Partial = Partial;
2803 Matched.back().Args = Info.take();
2804 }
2805 }
2806
Larisse Voufo39a1e502013-08-06 01:03:05 +00002807 if (Matched.size() >= 1) {
2808 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2809 if (Matched.size() == 1) {
2810 // -- If exactly one matching specialization is found, the
2811 // instantiation is generated from that specialization.
2812 // We don't need to do anything for this.
2813 } else {
2814 // -- If more than one matching specialization is found, the
2815 // partial order rules (14.5.4.2) are used to determine
2816 // whether one of the specializations is more specialized
2817 // than the others. If none of the specializations is more
2818 // specialized than all of the other matching
2819 // specializations, then the use of the variable template is
2820 // ambiguous and the program is ill-formed.
2821 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2822 PEnd = Matched.end();
2823 P != PEnd; ++P) {
2824 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2825 PointOfInstantiation) ==
2826 P->Partial)
2827 Best = P;
2828 }
2829
2830 // Determine if the best partial specialization is more specialized than
2831 // the others.
2832 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2833 PEnd = Matched.end();
2834 P != PEnd; ++P) {
2835 if (P != Best && getMoreSpecializedPartialSpecialization(
2836 P->Partial, Best->Partial,
2837 PointOfInstantiation) != Best->Partial) {
2838 AmbiguousPartialSpec = true;
2839 break;
2840 }
2841 }
2842 }
2843
2844 // Instantiate using the best variable template partial specialization.
2845 InstantiationPattern = Best->Partial;
2846 InstantiationArgs = Best->Args;
2847 } else {
2848 // -- If no match is found, the instantiation is generated
2849 // from the primary template.
2850 // InstantiationPattern = Template->getTemplatedDecl();
2851 }
2852 }
2853
Larisse Voufo39a1e502013-08-06 01:03:05 +00002854 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00002855 // Note that we do not instantiate a definition until we see an odr-use
2856 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002857 // FIXME: LateAttrs et al.?
2858 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2859 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2860 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2861 if (!Decl)
2862 return true;
2863
2864 if (AmbiguousPartialSpec) {
2865 // Partial ordering did not produce a clear winner. Complain.
2866 Decl->setInvalidDecl();
2867 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2868 << Decl;
2869
2870 // Print the matching partial specializations.
2871 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2872 PEnd = Matched.end();
2873 P != PEnd; ++P)
2874 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2875 << getTemplateArgumentBindingsText(
2876 P->Partial->getTemplateParameters(), *P->Args);
2877 return true;
2878 }
2879
2880 if (VarTemplatePartialSpecializationDecl *D =
2881 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2882 Decl->setInstantiationOf(D, InstantiationArgs);
2883
Richard Smith6739a102016-05-05 00:56:12 +00002884 checkSpecializationVisibility(TemplateNameLoc, Decl);
2885
Larisse Voufo39a1e502013-08-06 01:03:05 +00002886 assert(Decl && "No variable template specialization?");
2887 return Decl;
2888}
2889
2890ExprResult
2891Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2892 const DeclarationNameInfo &NameInfo,
2893 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2894 const TemplateArgumentListInfo *TemplateArgs) {
2895
2896 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2897 *TemplateArgs);
2898 if (Decl.isInvalid())
2899 return ExprError();
2900
2901 VarDecl *Var = cast<VarDecl>(Decl.get());
2902 if (!Var->getTemplateSpecializationKind())
2903 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2904 NameInfo.getLoc());
2905
2906 // Build an ordinary singleton decl ref.
2907 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002908 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002909}
2910
John McCalldadc5752010-08-24 06:29:42 +00002911ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002912 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002913 LookupResult &R,
2914 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002915 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002916 // FIXME: Can we do any checking at this point? I guess we could check the
2917 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002918 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002919 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002920 // foo<int> could identify a single function unambiguously
2921 // This approach does NOT work, since f<int>(1);
2922 // gets resolved prior to resorting to overload resolution
2923 // i.e., template<class T> void f(double);
2924 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002925
2926 // These should be filtered out by our callers.
2927 assert(!R.empty() && "empty lookup results when building templateid");
2928 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2929
Larisse Voufo39a1e502013-08-06 01:03:05 +00002930 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002931 bool InstantiationDependent;
2932 if (R.getAsSingle<VarTemplateDecl>() &&
2933 !TemplateSpecializationType::anyDependentTemplateArguments(
2934 *TemplateArgs, InstantiationDependent)) {
2935 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2936 R.getAsSingle<VarTemplateDecl>(),
2937 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002938 }
2939
John McCall58cc69d2010-01-27 01:50:18 +00002940 // We don't want lookup warnings at this point.
2941 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942
John McCalle66edc12009-11-24 19:00:30 +00002943 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002944 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002945 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002946 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002947 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002949 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002950
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002951 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002952}
2953
John McCalle66edc12009-11-24 19:00:30 +00002954// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002955ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002956Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002957 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002958 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002959 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002960
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002961 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002962 DeclContext *DC;
2963 if (!(DC = computeDeclContext(SS, false)) ||
2964 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002965 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002966 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002967
Douglas Gregor786123d2010-05-21 23:18:07 +00002968 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002969 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002970 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002971 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002972
John McCalle66edc12009-11-24 19:00:30 +00002973 if (R.isAmbiguous())
2974 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975
John McCalle66edc12009-11-24 19:00:30 +00002976 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002977 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2978 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002979 return ExprError();
2980 }
2981
2982 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002983 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002984 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002985 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002986 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2987 return ExprError();
2988 }
2989
Abramo Bagnara7945c982012-01-27 09:46:47 +00002990 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002991}
2992
Douglas Gregorb67535d2009-03-31 00:43:58 +00002993/// \brief Form a dependent template name.
2994///
2995/// This action forms a dependent template name given the template
2996/// name and its (presumably dependent) scope specifier. For
2997/// example, given "MetaFun::template apply", the scope specifier \p
2998/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2999/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003001 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003002 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003003 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003004 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003005 bool EnteringContext,
3006 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003007 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3008 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003009 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003010 diag::warn_cxx98_compat_template_outside_of_template :
3011 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003012 << FixItHint::CreateRemoval(TemplateKWLoc);
3013
Craig Topperc3ec1492014-05-26 06:22:03 +00003014 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003015 if (SS.isSet())
3016 LookupCtx = computeDeclContext(SS, EnteringContext);
3017 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003018 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003019 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003020 // C++0x [temp.names]p5:
3021 // If a name prefixed by the keyword template is not the name of
3022 // a template, the program is ill-formed. [Note: the keyword
3023 // template may not be applied to non-template members of class
3024 // templates. -end note ] [ Note: as is the case with the
3025 // typename prefix, the template prefix is allowed in cases
3026 // where it is not strictly necessary; i.e., when the
3027 // nested-name-specifier or the expression on the left of the ->
3028 // or . is not dependent on a template-parameter, or the use
3029 // does not appear in the scope of a template. -end note]
3030 //
3031 // Note: C++03 was more strict here, because it banned the use of
3032 // the "template" keyword prior to a template-name that was not a
3033 // dependent name. C++ DR468 relaxed this requirement (the
3034 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003035 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003036 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003037 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003038 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003039 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003040 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3041 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003042 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3043 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003044 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003045 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003046 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003047 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003048 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003049 << Name.getSourceRange()
3050 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003051 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003052 } else {
3053 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003054 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003055 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003056 }
3057
Aaron Ballman4a979672014-01-03 13:56:08 +00003058 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059
Douglas Gregor3cf81312009-11-03 23:16:33 +00003060 switch (Name.getKind()) {
3061 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003063 Name.Identifier));
3064 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003065
Douglas Gregor71395fa2009-11-04 00:56:37 +00003066 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003067 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003068 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003069 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003070
3071 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003072 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003073
Douglas Gregor3cf81312009-11-03 23:16:33 +00003074 default:
3075 break;
3076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003077
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003078 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003079 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003080 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003081 << Name.getSourceRange()
3082 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003083 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003084}
3085
Mike Stump11289f42009-09-09 15:08:12 +00003086bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003087 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003088 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003089 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003090 QualType ArgType;
3091 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003092
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003093 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003094 switch(Arg.getKind()) {
3095 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003096 // C++ [temp.arg.type]p1:
3097 // A template-argument for a template-parameter which is a
3098 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003099 ArgType = Arg.getAsType();
3100 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003101 break;
3102 case TemplateArgument::Template: {
3103 // We have a template type parameter but the template argument
3104 // is a template without any arguments.
3105 SourceRange SR = AL.getSourceRange();
3106 TemplateName Name = Arg.getAsTemplate();
3107 Diag(SR.getBegin(), diag::err_template_missing_args)
3108 << Name << SR;
3109 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3110 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003111
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003112 return true;
3113 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003114 case TemplateArgument::Expression: {
3115 // We have a template type parameter but the template argument is an
3116 // expression; see if maybe it is missing the "typename" keyword.
3117 CXXScopeSpec SS;
3118 DeclarationNameInfo NameInfo;
3119
3120 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3121 SS.Adopt(ArgExpr->getQualifierLoc());
3122 NameInfo = ArgExpr->getNameInfo();
3123 } else if (DependentScopeDeclRefExpr *ArgExpr =
3124 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3125 SS.Adopt(ArgExpr->getQualifierLoc());
3126 NameInfo = ArgExpr->getNameInfo();
3127 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3128 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003129 if (ArgExpr->isImplicitAccess()) {
3130 SS.Adopt(ArgExpr->getQualifierLoc());
3131 NameInfo = ArgExpr->getMemberNameInfo();
3132 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003133 }
3134
Reid Kleckner377c1592014-06-10 23:29:48 +00003135 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003136 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3137 LookupParsedName(Result, CurScope, &SS);
3138
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003139 if (Result.getAsSingle<TypeDecl>() ||
3140 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003141 LookupResult::NotFoundInCurrentInstantiation) {
3142 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003143 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003144 Diag(Loc, getLangOpts().MSVCCompat
3145 ? diag::ext_ms_template_type_arg_missing_typename
3146 : diag::err_template_arg_must_be_type_suggest)
3147 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003148 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003149
3150 // Recover by synthesizing a type using the location information that we
3151 // already have.
3152 ArgType =
3153 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3154 TypeLocBuilder TLB;
3155 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3156 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3157 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3158 TL.setNameLoc(NameInfo.getLoc());
3159 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3160
3161 // Overwrite our input TemplateArgumentLoc so that we can recover
3162 // properly.
3163 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3164 TemplateArgumentLocInfo(TSI));
3165
3166 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003167 }
3168 }
3169 // fallthrough
3170 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003171 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003172 // We have a template type parameter but the template argument
3173 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003174 SourceRange SR = AL.getSourceRange();
3175 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003176 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003177
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003178 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003179 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003180 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003181
Reid Kleckner377c1592014-06-10 23:29:48 +00003182 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003183 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003184
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003185 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003186 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003187
3188 // Objective-C ARC:
3189 // If an explicitly-specified template argument type is a lifetime type
3190 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003191 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003192 ArgType->isObjCLifetimeType() &&
3193 !ArgType.getObjCLifetime()) {
3194 Qualifiers Qs;
3195 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3196 ArgType = Context.getQualifiedType(ArgType, Qs);
3197 }
3198
3199 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003200 return false;
3201}
3202
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003203/// \brief Substitute template arguments into the default template argument for
3204/// the given template type parameter.
3205///
3206/// \param SemaRef the semantic analysis object for which we are performing
3207/// the substitution.
3208///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003210/// for.
3211///
3212/// \param TemplateLoc the location of the template name that started the
3213/// template-id we are checking.
3214///
3215/// \param RAngleLoc the location of the right angle bracket ('>') that
3216/// terminates the template-id.
3217///
3218/// \param Param the template template parameter whose default we are
3219/// substituting into.
3220///
3221/// \param Converted the list of template arguments provided for template
3222/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003223/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003224static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003225SubstDefaultTemplateArgument(Sema &SemaRef,
3226 TemplateDecl *Template,
3227 SourceLocation TemplateLoc,
3228 SourceLocation RAngleLoc,
3229 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003230 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003231 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003232
3233 // If the argument type is dependent, instantiate it now based
3234 // on the previously-computed template arguments.
3235 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003236 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003237 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003238 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003239 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003240 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241
David Majnemer89189202013-08-28 23:48:32 +00003242 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3243 Converted.data(), Converted.size());
3244
3245 // Only substitute for the innermost template argument list.
3246 MultiLevelTemplateArgumentList TemplateArgLists;
3247 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3248 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3249 TemplateArgLists.addOuterTemplateArguments(None);
3250
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003251 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003252 ArgType =
3253 SemaRef.SubstType(ArgType, TemplateArgLists,
3254 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003255 }
3256
3257 return ArgType;
3258}
3259
3260/// \brief Substitute template arguments into the default template argument for
3261/// the given non-type template parameter.
3262///
3263/// \param SemaRef the semantic analysis object for which we are performing
3264/// the substitution.
3265///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003267/// for.
3268///
3269/// \param TemplateLoc the location of the template name that started the
3270/// template-id we are checking.
3271///
3272/// \param RAngleLoc the location of the right angle bracket ('>') that
3273/// terminates the template-id.
3274///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003275/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003276/// substituting into.
3277///
3278/// \param Converted the list of template arguments provided for template
3279/// parameters that precede \p Param in the template parameter list.
3280///
3281/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003282static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003283SubstDefaultTemplateArgument(Sema &SemaRef,
3284 TemplateDecl *Template,
3285 SourceLocation TemplateLoc,
3286 SourceLocation RAngleLoc,
3287 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003288 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003289 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003290 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003291 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003292 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003293 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003294
David Majnemer89189202013-08-28 23:48:32 +00003295 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3296 Converted.data(), Converted.size());
3297
3298 // Only substitute for the innermost template argument list.
3299 MultiLevelTemplateArgumentList TemplateArgLists;
3300 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3301 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3302 TemplateArgLists.addOuterTemplateArguments(None);
3303
Faisal Vali48401eb2015-11-19 19:20:17 +00003304 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3305 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003306 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003307}
3308
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003309/// \brief Substitute template arguments into the default template argument for
3310/// the given template template parameter.
3311///
3312/// \param SemaRef the semantic analysis object for which we are performing
3313/// the substitution.
3314///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003316/// for.
3317///
3318/// \param TemplateLoc the location of the template name that started the
3319/// template-id we are checking.
3320///
3321/// \param RAngleLoc the location of the right angle bracket ('>') that
3322/// terminates the template-id.
3323///
3324/// \param Param the template template parameter whose default we are
3325/// substituting into.
3326///
3327/// \param Converted the list of template arguments provided for template
3328/// parameters that precede \p Param in the template parameter list.
3329///
Douglas Gregordf846d12011-03-02 18:46:51 +00003330/// \param QualifierLoc Will be set to the nested-name-specifier (with
3331/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003332///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003333/// \returns the substituted template argument, or NULL if an error occurred.
3334static TemplateName
3335SubstDefaultTemplateArgument(Sema &SemaRef,
3336 TemplateDecl *Template,
3337 SourceLocation TemplateLoc,
3338 SourceLocation RAngleLoc,
3339 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003340 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003341 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003342 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003343 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003344 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003345 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346
David Majnemer89189202013-08-28 23:48:32 +00003347 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3348 Converted.data(), Converted.size());
3349
3350 // Only substitute for the innermost template argument list.
3351 MultiLevelTemplateArgumentList TemplateArgLists;
3352 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3353 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3354 TemplateArgLists.addOuterTemplateArguments(None);
3355
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003356 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003357 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003358 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003359 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003360 QualifierLoc =
3361 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003362 if (!QualifierLoc)
3363 return TemplateName();
3364 }
David Majnemer89189202013-08-28 23:48:32 +00003365
3366 return SemaRef.SubstTemplateName(
3367 QualifierLoc,
3368 Param->getDefaultArgument().getArgument().getAsTemplate(),
3369 Param->getDefaultArgument().getTemplateNameLoc(),
3370 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003371}
3372
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003373/// \brief If the given template parameter has a default template
3374/// argument, substitute into that default template argument and
3375/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003377Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3378 SourceLocation TemplateLoc,
3379 SourceLocation RAngleLoc,
3380 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003381 SmallVectorImpl<TemplateArgument>
3382 &Converted,
3383 bool &HasDefaultArg) {
3384 HasDefaultArg = false;
3385
3386 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003387 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003388 return TemplateArgumentLoc();
3389
Richard Smithc87b9382013-07-04 01:01:24 +00003390 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003391 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003392 TemplateLoc,
3393 RAngleLoc,
3394 TypeParm,
3395 Converted);
3396 if (DI)
3397 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3398
3399 return TemplateArgumentLoc();
3400 }
3401
3402 if (NonTypeTemplateParmDecl *NonTypeParm
3403 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003404 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003405 return TemplateArgumentLoc();
3406
Richard Smithc87b9382013-07-04 01:01:24 +00003407 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003408 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003409 TemplateLoc,
3410 RAngleLoc,
3411 NonTypeParm,
3412 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003413 if (Arg.isInvalid())
3414 return TemplateArgumentLoc();
3415
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003416 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003417 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3418 }
3419
3420 TemplateTemplateParmDecl *TempTempParm
3421 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003422 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003423 return TemplateArgumentLoc();
3424
Richard Smithc87b9382013-07-04 01:01:24 +00003425 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003426 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003427 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003429 RAngleLoc,
3430 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003431 Converted,
3432 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003433 if (TName.isNull())
3434 return TemplateArgumentLoc();
3435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003436 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003437 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003438 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3439}
3440
Douglas Gregorda0fb532009-11-11 19:31:23 +00003441/// \brief Check that the given template argument corresponds to the given
3442/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003443///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003445/// checked.
3446///
Richard Trieu15b66532015-01-24 02:48:32 +00003447/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003448///
3449/// \param Template The template in which the template argument resides.
3450///
3451/// \param TemplateLoc The location of the template name for the template
3452/// whose argument list we're matching.
3453///
3454/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3455/// the template argument list.
3456///
3457/// \param ArgumentPackIndex The index into the argument pack where this
3458/// argument will be placed. Only valid if the parameter is a parameter pack.
3459///
3460/// \param Converted The checked, converted argument will be added to the
3461/// end of this small vector.
3462///
3463/// \param CTAK Describes how we arrived at this particular template argument:
3464/// explicitly written, deduced, etc.
3465///
3466/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003467bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003468 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003469 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003470 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003471 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003472 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003473 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003474 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003475 // Check template type parameters.
3476 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003477 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478
Douglas Gregoreebed722009-11-11 19:41:09 +00003479 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003481 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003482 // with the template arguments we've seen thus far. But if the
3483 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003484 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003485 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3486 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487
Peter Collingbourne01687632010-12-10 17:08:53 +00003488 if (NTTPType->isDependentType() &&
3489 !isa<TemplateTemplateParmDecl>(Template) &&
3490 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003491 // Do substitution on the type of the non-type template parameter.
3492 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003493 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003494 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003495 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003496 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497
3498 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003499 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003500 NTTPType = SubstType(NTTPType,
3501 MultiLevelTemplateArgumentList(TemplateArgs),
3502 NTTP->getLocation(),
3503 NTTP->getDeclName());
3504 // If that worked, check the non-type template parameter type
3505 // for validity.
3506 if (!NTTPType.isNull())
3507 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3508 NTTP->getLocation());
3509 if (NTTPType.isNull())
3510 return true;
3511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512
Douglas Gregorda0fb532009-11-11 19:31:23 +00003513 switch (Arg.getArgument().getKind()) {
3514 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003515 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
Douglas Gregorda0fb532009-11-11 19:31:23 +00003517 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003518 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003519 ExprResult Res =
3520 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3521 Result, CTAK);
3522 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003523 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Richard Trieu15b66532015-01-24 02:48:32 +00003525 // If the resulting expression is new, then use it in place of the
3526 // old expression in the template argument.
3527 if (Res.get() != Arg.getArgument().getAsExpr()) {
3528 TemplateArgument TA(Res.get());
3529 Arg = TemplateArgumentLoc(TA, Res.get());
3530 }
3531
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003532 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003533 break;
3534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregorda0fb532009-11-11 19:31:23 +00003536 case TemplateArgument::Declaration:
3537 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003538 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003539 // We've already checked this template argument, so just copy
3540 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003541 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543
Douglas Gregorda0fb532009-11-11 19:31:23 +00003544 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003545 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003546 // We were given a template template argument. It may not be ill-formed;
3547 // see below.
3548 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003549 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3550 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003551 // We have a template argument such as \c T::template X, which we
3552 // parsed as a template template argument. However, since we now
3553 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003554 // template name into an expression.
3555
3556 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3557 Arg.getTemplateNameLoc());
3558
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003559 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003560 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003561 // FIXME: the template-template arg was a DependentTemplateName,
3562 // so it was provided with a template keyword. However, its source
3563 // location is not stored in the template argument structure.
3564 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003565 ExprResult E = DependentScopeDeclRefExpr::Create(
3566 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3567 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003569 // If we parsed the template argument as a pack expansion, create a
3570 // pack expansion expression.
3571 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003572 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003573 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003574 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003576
Douglas Gregorda0fb532009-11-11 19:31:23 +00003577 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003578 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003579 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003582 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003583 break;
3584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585
Douglas Gregorda0fb532009-11-11 19:31:23 +00003586 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003587 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003588 // therefore cannot be a non-type template argument.
3589 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3590 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591
Douglas Gregorda0fb532009-11-11 19:31:23 +00003592 Diag(Param->getLocation(), diag::note_template_param_here);
3593 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594
Douglas Gregorda0fb532009-11-11 19:31:23 +00003595 case TemplateArgument::Type: {
3596 // We have a non-type template parameter but the template
3597 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598
Douglas Gregorda0fb532009-11-11 19:31:23 +00003599 // C++ [temp.arg]p2:
3600 // In a template-argument, an ambiguity between a type-id and
3601 // an expression is resolved to a type-id, regardless of the
3602 // form of the corresponding template-parameter.
3603 //
3604 // We warn specifically about this case, since it can be rather
3605 // confusing for users.
3606 QualType T = Arg.getArgument().getAsType();
3607 SourceRange SR = Arg.getSourceRange();
3608 if (T->isFunctionType())
3609 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3610 else
3611 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3612 Diag(Param->getLocation(), diag::note_template_param_here);
3613 return true;
3614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Douglas Gregorda0fb532009-11-11 19:31:23 +00003616 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003617 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619
Douglas Gregorda0fb532009-11-11 19:31:23 +00003620 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003621 }
3622
3623
Douglas Gregorda0fb532009-11-11 19:31:23 +00003624 // Check template template parameters.
3625 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626
Douglas Gregorda0fb532009-11-11 19:31:23 +00003627 // Substitute into the template parameter list of the template
3628 // template parameter, since previously-supplied template arguments
3629 // may appear within the template template parameter.
3630 {
3631 // Set up a template instantiation context.
3632 LocalInstantiationScope Scope(*this);
3633 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003634 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003635 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003636 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003637 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638
3639 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003640 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003641 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003642 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003643 MultiLevelTemplateArgumentList(TemplateArgs)));
3644 if (!TempParm)
3645 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregorda0fb532009-11-11 19:31:23 +00003648 switch (Arg.getArgument().getKind()) {
3649 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003650 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651
Douglas Gregorda0fb532009-11-11 19:31:23 +00003652 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003653 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003654 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003655 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003657 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003658 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659
Douglas Gregorda0fb532009-11-11 19:31:23 +00003660 case TemplateArgument::Expression:
3661 case TemplateArgument::Type:
3662 // We have a template template parameter but the template
3663 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003664 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003665 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003666 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Douglas Gregorda0fb532009-11-11 19:31:23 +00003668 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003669 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003670 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003671 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003672 case TemplateArgument::NullPtr:
3673 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregorda0fb532009-11-11 19:31:23 +00003675 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003676 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
Douglas Gregorda0fb532009-11-11 19:31:23 +00003679 return false;
3680}
3681
Douglas Gregor8e072612012-02-03 07:34:46 +00003682/// \brief Diagnose an arity mismatch in the
3683static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3684 SourceLocation TemplateLoc,
3685 TemplateArgumentListInfo &TemplateArgs) {
3686 TemplateParameterList *Params = Template->getTemplateParameters();
3687 unsigned NumParams = Params->size();
3688 unsigned NumArgs = TemplateArgs.size();
3689
3690 SourceRange Range;
3691 if (NumArgs > NumParams)
3692 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3693 TemplateArgs.getRAngleLoc());
3694 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3695 << (NumArgs > NumParams)
3696 << (isa<ClassTemplateDecl>(Template)? 0 :
3697 isa<FunctionTemplateDecl>(Template)? 1 :
3698 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3699 << Template << Range;
3700 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3701 << Params->getSourceRange();
3702 return true;
3703}
3704
Richard Smith1fde8ec2012-09-07 02:06:42 +00003705/// \brief Check whether the template parameter is a pack expansion, and if so,
3706/// determine the number of parameters produced by that expansion. For instance:
3707///
3708/// \code
3709/// template<typename ...Ts> struct A {
3710/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3711/// };
3712/// \endcode
3713///
3714/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3715/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003716static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003717 if (NonTypeTemplateParmDecl *NTTP
3718 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3719 if (NTTP->isExpandedParameterPack())
3720 return NTTP->getNumExpansionTypes();
3721 }
3722
3723 if (TemplateTemplateParmDecl *TTP
3724 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3725 if (TTP->isExpandedParameterPack())
3726 return TTP->getNumExpansionTemplateParameters();
3727 }
3728
David Blaikie7a30dc52013-02-21 01:47:18 +00003729 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003730}
3731
Richard Smith35c1df52015-06-17 20:16:32 +00003732/// Diagnose a missing template argument.
3733template<typename TemplateParmDecl>
3734static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3735 TemplateDecl *TD,
3736 const TemplateParmDecl *D,
3737 TemplateArgumentListInfo &Args) {
3738 // Dig out the most recent declaration of the template parameter; there may be
3739 // declarations of the template that are more recent than TD.
3740 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3741 ->getTemplateParameters()
3742 ->getParam(D->getIndex()));
3743
3744 // If there's a default argument that's not visible, diagnose that we're
3745 // missing a module import.
3746 llvm::SmallVector<Module*, 8> Modules;
3747 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3748 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3749 D->getDefaultArgumentLoc(), Modules,
3750 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003751 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003752 return true;
3753 }
3754
3755 // FIXME: If there's a more recent default argument that *is* visible,
3756 // diagnose that it was declared too late.
3757
3758 return diagnoseArityMismatch(S, TD, Loc, Args);
3759}
3760
Douglas Gregord32e0282009-02-09 23:23:08 +00003761/// \brief Check that the given template argument list is well-formed
3762/// for specializing the given template.
3763bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3764 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003765 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003766 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003767 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003768 // Make a copy of the template arguments for processing. Only make the
3769 // changes at the end when successful in matching the arguments to the
3770 // template.
3771 TemplateArgumentListInfo NewArgs = TemplateArgs;
3772
Douglas Gregord32e0282009-02-09 23:23:08 +00003773 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003774
Richard Trieu15b66532015-01-24 02:48:32 +00003775 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003776
Mike Stump11289f42009-09-09 15:08:12 +00003777 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003778 // [...] The type and form of each template-argument specified in
3779 // a template-id shall match the type and form specified for the
3780 // corresponding parameter declared by the template in its
3781 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003782 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003783 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003784 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003785 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003786 for (TemplateParameterList::iterator Param = Params->begin(),
3787 ParamEnd = Params->end();
3788 Param != ParamEnd; /* increment in loop */) {
3789 // If we have an expanded parameter pack, make sure we don't have too
3790 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003791 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003792 if (*Expansions == ArgumentPack.size()) {
3793 // We're done with this parameter pack. Pack up its arguments and add
3794 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003795 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003796 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003797 ArgumentPack.clear();
3798
Richard Smith1fde8ec2012-09-07 02:06:42 +00003799 // This argument is assigned to the next parameter.
3800 ++Param;
3801 continue;
3802 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3803 // Not enough arguments for this parameter pack.
3804 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3805 << false
3806 << (isa<ClassTemplateDecl>(Template)? 0 :
3807 isa<FunctionTemplateDecl>(Template)? 1 :
3808 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3809 << Template;
3810 Diag(Template->getLocation(), diag::note_template_decl_here)
3811 << Params->getSourceRange();
3812 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003813 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815
Richard Smith1fde8ec2012-09-07 02:06:42 +00003816 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003817 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003818 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003820 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003821 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
Richard Smith96d71c32014-11-12 23:38:38 +00003823 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003824 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003825 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3826 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003827 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003828 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003829 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003830 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003831 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003832 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003833 Diag((*Param)->getLocation(), diag::note_template_param_here);
3834 return true;
3835 }
3836
Richard Smith1fde8ec2012-09-07 02:06:42 +00003837 // We're now done with this argument.
3838 ++ArgIdx;
3839
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003840 if ((*Param)->isTemplateParameterPack()) {
3841 // The template parameter was a template parameter pack, so take the
3842 // deduced argument and place it on the argument pack. Note that we
3843 // stay on the same template parameter so that we can deduce more
3844 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003845 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003846 } else {
3847 // Move to the next template parameter.
3848 ++Param;
3849 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003850
Richard Smith96d71c32014-11-12 23:38:38 +00003851 // If we just saw a pack expansion into a non-pack, then directly convert
3852 // the remaining arguments, because we don't know what parameters they'll
3853 // match up with.
3854 if (PackExpansionIntoNonPack) {
3855 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003856 // If we were part way through filling in an expanded parameter pack,
3857 // fall back to just producing individual arguments.
3858 Converted.insert(Converted.end(),
3859 ArgumentPack.begin(), ArgumentPack.end());
3860 ArgumentPack.clear();
3861 }
3862
3863 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003864 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003865 ++ArgIdx;
3866 }
3867
Richard Smith1fde8ec2012-09-07 02:06:42 +00003868 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003869 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003870
Douglas Gregor84d49a22009-11-11 21:54:23 +00003871 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873
Douglas Gregor2f157c92011-06-03 02:59:40 +00003874 // If we're checking a partial template argument list, we're done.
3875 if (PartialTemplateArgs) {
3876 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003877 Converted.push_back(
3878 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3879
Richard Smith1fde8ec2012-09-07 02:06:42 +00003880 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003881 }
3882
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003884 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003885 if ((*Param)->isTemplateParameterPack()) {
3886 assert(!getExpandedPackSize(*Param) &&
3887 "Should have dealt with this already");
3888
3889 // A non-expanded parameter pack before the end of the parameter list
3890 // only occurs for an ill-formed template parameter list, unless we've
3891 // got a partial argument list for a function template, so just bail out.
3892 if (Param + 1 != ParamEnd)
3893 return true;
3894
Benjamin Kramercce63472015-08-05 09:40:22 +00003895 Converted.push_back(
3896 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003897 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003898
3899 ++Param;
3900 continue;
3901 }
3902
Douglas Gregor8e072612012-02-03 07:34:46 +00003903 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003904 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Douglas Gregor84d49a22009-11-11 21:54:23 +00003906 // Retrieve the default template argument from the template
3907 // parameter. For each kind of template parameter, we substitute the
3908 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003910 // the default argument.
3911 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003912 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003913 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3914 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003917 Template,
3918 TemplateLoc,
3919 RAngleLoc,
3920 TTP,
3921 Converted);
3922 if (!ArgType)
3923 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924
Douglas Gregor84d49a22009-11-11 21:54:23 +00003925 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3926 ArgType);
3927 } else if (NonTypeTemplateParmDecl *NTTP
3928 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003929 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003930 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3931 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003932
John McCalldadc5752010-08-24 06:29:42 +00003933 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934 TemplateLoc,
3935 RAngleLoc,
3936 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003937 Converted);
3938 if (E.isInvalid())
3939 return true;
3940
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003941 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003942 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3943 } else {
3944 TemplateTemplateParmDecl *TempParm
3945 = cast<TemplateTemplateParmDecl>(*Param);
3946
Richard Smith95d83952015-06-10 20:36:34 +00003947 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003948 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3949 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003950
Douglas Gregordf846d12011-03-02 18:46:51 +00003951 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003952 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953 TemplateLoc,
3954 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003955 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003956 Converted,
3957 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003958 if (Name.isNull())
3959 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003960
Douglas Gregor9d802122011-03-02 17:09:35 +00003961 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3962 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003964
Douglas Gregor84d49a22009-11-11 21:54:23 +00003965 // Introduce an instantiation record that describes where we are using
3966 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003967 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3968 SourceRange(TemplateLoc, RAngleLoc));
3969 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003970 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971
Douglas Gregor84d49a22009-11-11 21:54:23 +00003972 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003973 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003974 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003975 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976
Richard Trieu15b66532015-01-24 02:48:32 +00003977 // Core issue 150 (assumed resolution): if this is a template template
3978 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003979 // template definition.
3980 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003981 NewArgs.addArgument(Arg);
3982
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003983 // Move to the next template parameter and argument.
3984 ++Param;
3985 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003986 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003987
Richard Smith07f79912014-06-06 16:00:50 +00003988 // If we're performing a partial argument substitution, allow any trailing
3989 // pack expansions; they might be empty. This can happen even if
3990 // PartialTemplateArgs is false (the list of arguments is complete but
3991 // still dependent).
3992 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3993 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003994 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3995 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003996 }
3997
Douglas Gregor8e072612012-02-03 07:34:46 +00003998 // If we have any leftover arguments, then there were too many arguments.
3999 // Complain and fail.
4000 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004001 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4002
4003 // No problems found with the new argument list, propagate changes back
4004 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004005 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006
Richard Smith1fde8ec2012-09-07 02:06:42 +00004007 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004008}
4009
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004010namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011 class UnnamedLocalNoLinkageFinder
4012 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004013 {
4014 Sema &S;
4015 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004017 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004019 public:
4020 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4021
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022 bool Visit(QualType T) {
4023 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004026#define TYPE(Class, Parent) \
4027 bool Visit##Class##Type(const Class##Type *);
4028#define ABSTRACT_TYPE(Class, Parent) \
4029 bool Visit##Class##Type(const Class##Type *) { return false; }
4030#define NON_CANONICAL_TYPE(Class, Parent) \
4031 bool Visit##Class##Type(const Class##Type *) { return false; }
4032#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004034 bool VisitTagDecl(const TagDecl *Tag);
4035 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4036 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004037} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004038
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004040 return false;
4041}
4042
4043bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4044 return Visit(T->getElementType());
4045}
4046
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004048 return Visit(T->getPointeeType());
4049}
4050
4051bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004053 return Visit(T->getPointeeType());
4054}
4055
4056bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004058 return Visit(T->getPointeeType());
4059}
4060
4061bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004063 return Visit(T->getPointeeType());
4064}
4065
4066bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004068 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4069}
4070
4071bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004073 return Visit(T->getElementType());
4074}
4075
4076bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004078 return Visit(T->getElementType());
4079}
4080
4081bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004083 return Visit(T->getElementType());
4084}
4085
4086bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004088 return Visit(T->getElementType());
4089}
4090
4091bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004093 return Visit(T->getElementType());
4094}
4095
4096bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4097 return Visit(T->getElementType());
4098}
4099
4100bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4101 return Visit(T->getElementType());
4102}
4103
4104bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4105 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004106 for (const auto &A : T->param_types()) {
4107 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004108 return true;
4109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004110
Alp Toker314cc812014-01-25 16:55:45 +00004111 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004112}
4113
4114bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4115 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004116 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004117}
4118
4119bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4120 const UnresolvedUsingType*) {
4121 return false;
4122}
4123
4124bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4125 return false;
4126}
4127
4128bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4129 return Visit(T->getUnderlyingType());
4130}
4131
4132bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4133 return false;
4134}
4135
Alexis Hunte852b102011-05-24 22:41:36 +00004136bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4137 const UnaryTransformType*) {
4138 return false;
4139}
4140
Richard Smith30482bc2011-02-20 03:19:35 +00004141bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4142 return Visit(T->getDeducedType());
4143}
4144
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004145bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4146 return VisitTagDecl(T->getDecl());
4147}
4148
4149bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4150 return VisitTagDecl(T->getDecl());
4151}
4152
4153bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4154 const TemplateTypeParmType*) {
4155 return false;
4156}
4157
Douglas Gregorada4b792011-01-14 02:55:32 +00004158bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4159 const SubstTemplateTypeParmPackType *) {
4160 return false;
4161}
4162
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004163bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4164 const TemplateSpecializationType*) {
4165 return false;
4166}
4167
4168bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4169 const InjectedClassNameType* T) {
4170 return VisitTagDecl(T->getDecl());
4171}
4172
4173bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4174 const DependentNameType* T) {
4175 return VisitNestedNameSpecifier(T->getQualifier());
4176}
4177
4178bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4179 const DependentTemplateSpecializationType* T) {
4180 return VisitNestedNameSpecifier(T->getQualifier());
4181}
4182
Douglas Gregord2fa7662010-12-20 02:24:11 +00004183bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4184 const PackExpansionType* T) {
4185 return Visit(T->getPattern());
4186}
4187
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004188bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4189 return false;
4190}
4191
4192bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4193 const ObjCInterfaceType *) {
4194 return false;
4195}
4196
4197bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4198 const ObjCObjectPointerType *) {
4199 return false;
4200}
4201
Eli Friedman0dfb8892011-10-06 23:00:33 +00004202bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4203 return Visit(T->getValueType());
4204}
4205
Xiuli Pan9c14e282016-01-09 12:53:17 +00004206bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4207 return false;
4208}
4209
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004210bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4211 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004212 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004213 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004214 diag::warn_cxx98_compat_template_arg_local_type :
4215 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004216 << S.Context.getTypeDeclType(Tag) << SR;
4217 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218 }
4219
John McCall5ea95772013-03-09 00:54:27 +00004220 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004221 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004222 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004223 diag::warn_cxx98_compat_template_arg_unnamed_type :
4224 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004225 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4226 return true;
4227 }
4228
4229 return false;
4230}
4231
4232bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4233 NestedNameSpecifier *NNS) {
4234 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4235 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004237 switch (NNS->getKind()) {
4238 case NestedNameSpecifier::Identifier:
4239 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004240 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004241 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004242 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004243 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004245 case NestedNameSpecifier::TypeSpec:
4246 case NestedNameSpecifier::TypeSpecWithTemplate:
4247 return Visit(QualType(NNS->getAsType(), 0));
4248 }
David Blaikie8a40f702012-01-17 06:56:22 +00004249 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004250}
4251
Douglas Gregord32e0282009-02-09 23:23:08 +00004252/// \brief Check a template argument against its corresponding
4253/// template type parameter.
4254///
4255/// This routine implements the semantics of C++ [temp.arg.type]. It
4256/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004257bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004258 TypeSourceInfo *ArgInfo) {
4259 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004260 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004261 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004262
4263 if (Arg->isVariablyModifiedType()) {
4264 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004265 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004266 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004267 }
4268
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004269 // C++03 [temp.arg.type]p2:
4270 // A local type, a type with no linkage, an unnamed type or a type
4271 // compounded from any of these types shall not be used as a
4272 // template-argument for a template type-parameter.
4273 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004274 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004275 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004276 bool NeedsCheck;
4277 if (LangOpts.CPlusPlus11)
4278 NeedsCheck =
4279 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4280 SR.getBegin()) ||
4281 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4282 SR.getBegin());
4283 else
4284 NeedsCheck = Arg->hasUnnamedOrLocalType();
4285
4286 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004287 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4288 (void)Finder.Visit(Context.getCanonicalType(Arg));
4289 }
4290
Douglas Gregord32e0282009-02-09 23:23:08 +00004291 return false;
4292}
4293
Douglas Gregor20fdef32012-04-10 17:08:25 +00004294enum NullPointerValueKind {
4295 NPV_NotNullPointer,
4296 NPV_NullPointer,
4297 NPV_Error
4298};
4299
4300/// \brief Determine whether the given template argument is a null pointer
4301/// value of the appropriate type.
4302static NullPointerValueKind
4303isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4304 QualType ParamType, Expr *Arg) {
4305 if (Arg->isValueDependent() || Arg->isTypeDependent())
4306 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004307
Richard Smithdb0ac552015-12-18 22:40:25 +00004308 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004309 llvm_unreachable(
4310 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004311
David Majnemer5c734ad2014-08-14 00:49:23 +00004312 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004313 return NPV_NotNullPointer;
4314
4315 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004316 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4317 if (ArgRV.isInvalid())
4318 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004319 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004320
Douglas Gregor20fdef32012-04-10 17:08:25 +00004321 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004322 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004323 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004324 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004325 EvalResult.HasSideEffects) {
4326 SourceLocation DiagLoc = Arg->getExprLoc();
4327
4328 // If our only note is the usual "invalid subexpression" note, just point
4329 // the caret at its location rather than producing an essentially
4330 // redundant note.
4331 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4332 diag::note_invalid_subexpr_in_const_expr) {
4333 DiagLoc = Notes[0].first;
4334 Notes.clear();
4335 }
4336
4337 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4338 << Arg->getType() << Arg->getSourceRange();
4339 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4340 S.Diag(Notes[I].first, Notes[I].second);
4341
4342 S.Diag(Param->getLocation(), diag::note_template_param_here);
4343 return NPV_Error;
4344 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004345
4346 // C++11 [temp.arg.nontype]p1:
4347 // - an address constant expression of type std::nullptr_t
4348 if (Arg->getType()->isNullPtrType())
4349 return NPV_NullPointer;
4350
4351 // - a constant expression that evaluates to a null pointer value (4.10); or
4352 // - a constant expression that evaluates to a null member pointer value
4353 // (4.11); or
4354 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4355 (EvalResult.Val.isMemberPointer() &&
4356 !EvalResult.Val.getMemberPointerDecl())) {
4357 // If our expression has an appropriate type, we've succeeded.
4358 bool ObjCLifetimeConversion;
4359 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4360 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4361 ObjCLifetimeConversion))
4362 return NPV_NullPointer;
4363
4364 // The types didn't match, but we know we got a null pointer; complain,
4365 // then recover as if the types were correct.
4366 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4367 << Arg->getType() << ParamType << Arg->getSourceRange();
4368 S.Diag(Param->getLocation(), diag::note_template_param_here);
4369 return NPV_NullPointer;
4370 }
4371
4372 // If we don't have a null pointer value, but we do have a NULL pointer
4373 // constant, suggest a cast to the appropriate type.
4374 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4375 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4376 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004377 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4378 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4379 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004380 S.Diag(Param->getLocation(), diag::note_template_param_here);
4381 return NPV_NullPointer;
4382 }
4383
4384 // FIXME: If we ever want to support general, address-constant expressions
4385 // as non-type template arguments, we should return the ExprResult here to
4386 // be interpreted by the caller.
4387 return NPV_NotNullPointer;
4388}
4389
David Majnemer61c39a12013-08-23 05:39:39 +00004390/// \brief Checks whether the given template argument is compatible with its
4391/// template parameter.
4392static bool CheckTemplateArgumentIsCompatibleWithParameter(
4393 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4394 Expr *Arg, QualType ArgType) {
4395 bool ObjCLifetimeConversion;
4396 if (ParamType->isPointerType() &&
4397 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4398 S.IsQualificationConversion(ArgType, ParamType, false,
4399 ObjCLifetimeConversion)) {
4400 // For pointer-to-object types, qualification conversions are
4401 // permitted.
4402 } else {
4403 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4404 if (!ParamRef->getPointeeType()->isFunctionType()) {
4405 // C++ [temp.arg.nontype]p5b3:
4406 // For a non-type template-parameter of type reference to
4407 // object, no conversions apply. The type referred to by the
4408 // reference may be more cv-qualified than the (otherwise
4409 // identical) type of the template- argument. The
4410 // template-parameter is bound directly to the
4411 // template-argument, which shall be an lvalue.
4412
4413 // FIXME: Other qualifiers?
4414 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4415 unsigned ArgQuals = ArgType.getCVRQualifiers();
4416
4417 if ((ParamQuals | ArgQuals) != ParamQuals) {
4418 S.Diag(Arg->getLocStart(),
4419 diag::err_template_arg_ref_bind_ignores_quals)
4420 << ParamType << Arg->getType() << Arg->getSourceRange();
4421 S.Diag(Param->getLocation(), diag::note_template_param_here);
4422 return true;
4423 }
4424 }
4425 }
4426
4427 // At this point, the template argument refers to an object or
4428 // function with external linkage. We now need to check whether the
4429 // argument and parameter types are compatible.
4430 if (!S.Context.hasSameUnqualifiedType(ArgType,
4431 ParamType.getNonReferenceType())) {
4432 // We can't perform this conversion or binding.
4433 if (ParamType->isReferenceType())
4434 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4435 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4436 else
4437 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4438 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4439 S.Diag(Param->getLocation(), diag::note_template_param_here);
4440 return true;
4441 }
4442 }
4443
4444 return false;
4445}
4446
Douglas Gregorccb07762009-02-11 19:52:55 +00004447/// \brief Checks whether the given template argument is the address
4448/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004450CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4451 NonTypeTemplateParmDecl *Param,
4452 QualType ParamType,
4453 Expr *ArgIn,
4454 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004455 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004456 Expr *Arg = ArgIn;
4457 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004458
Douglas Gregorb242683d2010-04-01 18:32:35 +00004459 bool AddressTaken = false;
4460 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004461 if (S.getLangOpts().MicrosoftExt) {
4462 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4463 // dereference and address-of operators.
4464 Arg = Arg->IgnoreParenCasts();
4465
4466 bool ExtWarnMSTemplateArg = false;
4467 UnaryOperatorKind FirstOpKind;
4468 SourceLocation FirstOpLoc;
4469 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4470 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4471 if (UnOpKind == UO_Deref)
4472 ExtWarnMSTemplateArg = true;
4473 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4474 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4475 if (!AddrOpLoc.isValid()) {
4476 FirstOpKind = UnOpKind;
4477 FirstOpLoc = UnOp->getOperatorLoc();
4478 }
4479 } else
4480 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004481 }
David Majnemer61c39a12013-08-23 05:39:39 +00004482 if (FirstOpLoc.isValid()) {
4483 if (ExtWarnMSTemplateArg)
4484 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4485 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004486
David Majnemer61c39a12013-08-23 05:39:39 +00004487 if (FirstOpKind == UO_AddrOf)
4488 AddressTaken = true;
4489 else if (Arg->getType()->isPointerType()) {
4490 // We cannot let pointers get dereferenced here, that is obviously not a
4491 // constant expression.
4492 assert(FirstOpKind == UO_Deref);
4493 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4494 << Arg->getSourceRange();
4495 }
4496 }
4497 } else {
4498 // See through any implicit casts we added to fix the type.
4499 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004500
David Majnemer61c39a12013-08-23 05:39:39 +00004501 // C++ [temp.arg.nontype]p1:
4502 //
4503 // A template-argument for a non-type, non-template
4504 // template-parameter shall be one of: [...]
4505 //
4506 // -- the address of an object or function with external
4507 // linkage, including function templates and function
4508 // template-ids but excluding non-static class members,
4509 // expressed as & id-expression where the & is optional if
4510 // the name refers to a function or array, or if the
4511 // corresponding template-parameter is a reference; or
4512
4513 // In C++98/03 mode, give an extension warning on any extra parentheses.
4514 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4515 bool ExtraParens = false;
4516 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4517 if (!Invalid && !ExtraParens) {
4518 S.Diag(Arg->getLocStart(),
4519 S.getLangOpts().CPlusPlus11
4520 ? diag::warn_cxx98_compat_template_arg_extra_parens
4521 : diag::ext_template_arg_extra_parens)
4522 << Arg->getSourceRange();
4523 ExtraParens = true;
4524 }
4525
4526 Arg = Parens->getSubExpr();
4527 }
4528
4529 while (SubstNonTypeTemplateParmExpr *subst =
4530 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4531 Arg = subst->getReplacement()->IgnoreImpCasts();
4532
4533 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4534 if (UnOp->getOpcode() == UO_AddrOf) {
4535 Arg = UnOp->getSubExpr();
4536 AddressTaken = true;
4537 AddrOpLoc = UnOp->getOperatorLoc();
4538 }
4539 }
4540
4541 while (SubstNonTypeTemplateParmExpr *subst =
4542 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4543 Arg = subst->getReplacement()->IgnoreImpCasts();
4544 }
John McCall7c454bb2011-07-15 05:09:51 +00004545
David Majnemer07910d62014-06-26 07:48:46 +00004546 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4547 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4548
4549 // If our parameter has pointer type, check for a null template value.
4550 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4551 NullPointerValueKind NPV;
4552 // dllimport'd entities aren't constant but are available inside of template
4553 // arguments.
4554 if (Entity && Entity->hasAttr<DLLImportAttr>())
4555 NPV = NPV_NotNullPointer;
4556 else
4557 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4558 switch (NPV) {
4559 case NPV_NullPointer:
4560 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004561 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4562 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004563 return false;
4564
4565 case NPV_Error:
4566 return true;
4567
4568 case NPV_NotNullPointer:
4569 break;
4570 }
4571 }
4572
Chandler Carruth724a8a12010-01-31 10:01:20 +00004573 // Stop checking the precise nature of the argument if it is value dependent,
4574 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004575 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004576 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004577 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004578 }
David Majnemer61c39a12013-08-23 05:39:39 +00004579
4580 if (isa<CXXUuidofExpr>(Arg)) {
4581 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4582 ArgIn, Arg, ArgType))
4583 return true;
4584
4585 Converted = TemplateArgument(ArgIn);
4586 return false;
4587 }
4588
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004589 if (!DRE) {
4590 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4591 << Arg->getSourceRange();
4592 S.Diag(Param->getLocation(), diag::note_template_param_here);
4593 return true;
4594 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004595
Douglas Gregorccb07762009-02-11 19:52:55 +00004596 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004597 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004598 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004599 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004600 S.Diag(Param->getLocation(), diag::note_template_param_here);
4601 return true;
4602 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004603
4604 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004605 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004606 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004607 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004608 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004609 S.Diag(Param->getLocation(), diag::note_template_param_here);
4610 return true;
4611 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004612 }
Mike Stump11289f42009-09-09 15:08:12 +00004613
Richard Smith9380e0e2012-04-04 21:11:30 +00004614 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4615 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004616
Richard Smith9380e0e2012-04-04 21:11:30 +00004617 // A non-type template argument must refer to an object or function.
4618 if (!Func && !Var) {
4619 // We found something, but we don't know specifically what it is.
4620 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4621 << Arg->getSourceRange();
4622 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4623 return true;
4624 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004625
Richard Smith9380e0e2012-04-04 21:11:30 +00004626 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004627 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004628 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004629 diag::warn_cxx98_compat_template_arg_object_internal :
4630 diag::ext_template_arg_object_internal)
4631 << !Func << Entity << Arg->getSourceRange();
4632 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4633 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004634 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004635 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4636 << !Func << Entity << Arg->getSourceRange();
4637 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4638 << !Func;
4639 return true;
4640 }
4641
4642 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004643 // If the template parameter has pointer type, the function decays.
4644 if (ParamType->isPointerType() && !AddressTaken)
4645 ArgType = S.Context.getPointerType(Func->getType());
4646 else if (AddressTaken && ParamType->isReferenceType()) {
4647 // If we originally had an address-of operator, but the
4648 // parameter has reference type, complain and (if things look
4649 // like they will work) drop the address-of operator.
4650 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4651 ParamType.getNonReferenceType())) {
4652 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4653 << ParamType;
4654 S.Diag(Param->getLocation(), diag::note_template_param_here);
4655 return true;
4656 }
4657
4658 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4659 << ParamType
4660 << FixItHint::CreateRemoval(AddrOpLoc);
4661 S.Diag(Param->getLocation(), diag::note_template_param_here);
4662
4663 ArgType = Func->getType();
4664 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004665 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004666 // A value of reference type is not an object.
4667 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004668 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004669 diag::err_template_arg_reference_var)
4670 << Var->getType() << Arg->getSourceRange();
4671 S.Diag(Param->getLocation(), diag::note_template_param_here);
4672 return true;
4673 }
4674
Richard Smith9380e0e2012-04-04 21:11:30 +00004675 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004676 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004677 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4678 << Arg->getSourceRange();
4679 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4680 return true;
4681 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004682
4683 // If the template parameter has pointer type, we must have taken
4684 // the address of this object.
4685 if (ParamType->isReferenceType()) {
4686 if (AddressTaken) {
4687 // If we originally had an address-of operator, but the
4688 // parameter has reference type, complain and (if things look
4689 // like they will work) drop the address-of operator.
4690 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4691 ParamType.getNonReferenceType())) {
4692 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4693 << ParamType;
4694 S.Diag(Param->getLocation(), diag::note_template_param_here);
4695 return true;
4696 }
4697
4698 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4699 << ParamType
4700 << FixItHint::CreateRemoval(AddrOpLoc);
4701 S.Diag(Param->getLocation(), diag::note_template_param_here);
4702
4703 ArgType = Var->getType();
4704 }
4705 } else if (!AddressTaken && ParamType->isPointerType()) {
4706 if (Var->getType()->isArrayType()) {
4707 // Array-to-pointer decay.
4708 ArgType = S.Context.getArrayDecayedType(Var->getType());
4709 } else {
4710 // If the template parameter has pointer type but the address of
4711 // this object was not taken, complain and (possibly) recover by
4712 // taking the address of the entity.
4713 ArgType = S.Context.getPointerType(Var->getType());
4714 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4715 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4716 << ParamType;
4717 S.Diag(Param->getLocation(), diag::note_template_param_here);
4718 return true;
4719 }
4720
4721 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4722 << ParamType
4723 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4724
4725 S.Diag(Param->getLocation(), diag::note_template_param_here);
4726 }
4727 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004728 }
Mike Stump11289f42009-09-09 15:08:12 +00004729
David Majnemer61c39a12013-08-23 05:39:39 +00004730 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4731 Arg, ArgType))
4732 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004733
4734 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004735 Converted =
4736 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004737 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004738 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004739}
4740
4741/// \brief Checks whether the given template argument is a pointer to
4742/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004743static bool CheckTemplateArgumentPointerToMember(Sema &S,
4744 NonTypeTemplateParmDecl *Param,
4745 QualType ParamType,
4746 Expr *&ResultArg,
4747 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004748 bool Invalid = false;
4749
Douglas Gregor20fdef32012-04-10 17:08:25 +00004750 // Check for a null pointer value.
4751 Expr *Arg = ResultArg;
4752 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4753 case NPV_Error:
4754 return true;
4755 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004756 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004757 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4758 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004759 return false;
4760 case NPV_NotNullPointer:
4761 break;
4762 }
4763
4764 bool ObjCLifetimeConversion;
4765 if (S.IsQualificationConversion(Arg->getType(),
4766 ParamType.getNonReferenceType(),
4767 false, ObjCLifetimeConversion)) {
4768 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004769 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004770 ResultArg = Arg;
4771 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4772 ParamType.getNonReferenceType())) {
4773 // We can't perform this conversion.
4774 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4775 << Arg->getType() << ParamType << Arg->getSourceRange();
4776 S.Diag(Param->getLocation(), diag::note_template_param_here);
4777 return true;
4778 }
4779
Douglas Gregorccb07762009-02-11 19:52:55 +00004780 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004781 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004782 Arg = Cast->getSubExpr();
4783
4784 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004785 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004786 // A template-argument for a non-type, non-template
4787 // template-parameter shall be one of: [...]
4788 //
4789 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004790 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004791
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004792 // In C++98/03 mode, give an extension warning on any extra parentheses.
4793 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4794 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004795 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004796 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004797 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004798 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004799 diag::warn_cxx98_compat_template_arg_extra_parens :
4800 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004801 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004802 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004803 }
4804
4805 Arg = Parens->getSubExpr();
4806 }
4807
John McCall7c454bb2011-07-15 05:09:51 +00004808 while (SubstNonTypeTemplateParmExpr *subst =
4809 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4810 Arg = subst->getReplacement()->IgnoreImpCasts();
4811
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004812 // A pointer-to-member constant written &Class::member.
4813 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004814 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004815 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4816 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004817 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004819 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004820 // A constant of pointer-to-member type.
4821 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4822 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4823 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004824 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004825 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004826 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004827 } else {
4828 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004829 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004830 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004831 return Invalid;
4832 }
4833 }
4834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835
Craig Topperc3ec1492014-05-26 06:22:03 +00004836 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838
Douglas Gregorccb07762009-02-11 19:52:55 +00004839 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004840 return S.Diag(Arg->getLocStart(),
4841 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004842 << Arg->getSourceRange();
4843
David Majnemer3ac84e62013-10-22 21:56:38 +00004844 if (isa<FieldDecl>(DRE->getDecl()) ||
4845 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4846 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004847 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004848 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004849 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4850 "Only non-static member pointers can make it here");
4851
4852 // Okay: this is the address of a non-static member, and therefore
4853 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004854 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004855 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004856 } else {
4857 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004858 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004859 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004860 return Invalid;
4861 }
4862
4863 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004864 S.Diag(Arg->getLocStart(),
4865 diag::err_template_arg_not_pointer_to_member_form)
4866 << Arg->getSourceRange();
4867 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004868 return true;
4869}
4870
Douglas Gregord32e0282009-02-09 23:23:08 +00004871/// \brief Check a template argument against its corresponding
4872/// non-type template parameter.
4873///
Douglas Gregor463421d2009-03-03 04:44:36 +00004874/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004875/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004876/// returns the converted template argument. \p ParamType is the
4877/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004878ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004879 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004880 TemplateArgument &Converted,
4881 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004882 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004883
Douglas Gregor86560402009-02-10 23:36:10 +00004884 // If either the parameter has a dependent type or the argument is
4885 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004886 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004887 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004888 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004889 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004890 }
Douglas Gregor86560402009-02-10 23:36:10 +00004891
Richard Smithd663fdd2014-12-17 20:42:37 +00004892 // We should have already dropped all cv-qualifiers by now.
4893 assert(!ParamType.hasQualifiers() &&
4894 "non-type template parameter type cannot be qualified");
4895
4896 if (CTAK == CTAK_Deduced &&
4897 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4898 // C++ [temp.deduct.type]p17:
4899 // If, in the declaration of a function template with a non-type
4900 // template-parameter, the non-type template-parameter is used
4901 // in an expression in the function parameter-list and, if the
4902 // corresponding template-argument is deduced, the
4903 // template-argument type shall match the type of the
4904 // template-parameter exactly, except that a template-argument
4905 // deduced from an array bound may be of any integral type.
4906 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4907 << Arg->getType().getUnqualifiedType()
4908 << ParamType.getUnqualifiedType();
4909 Diag(Param->getLocation(), diag::note_template_param_here);
4910 return ExprError();
4911 }
4912
Richard Smith410cc892014-11-26 03:26:53 +00004913 if (getLangOpts().CPlusPlus1z) {
4914 // FIXME: We can do some limited checking for a value-dependent but not
4915 // type-dependent argument.
4916 if (Arg->isValueDependent()) {
4917 Converted = TemplateArgument(Arg);
4918 return Arg;
4919 }
4920
4921 // C++1z [temp.arg.nontype]p1:
4922 // A template-argument for a non-type template parameter shall be
4923 // a converted constant expression of the type of the template-parameter.
4924 APValue Value;
4925 ExprResult ArgResult = CheckConvertedConstantExpression(
4926 Arg, ParamType, Value, CCEK_TemplateArg);
4927 if (ArgResult.isInvalid())
4928 return ExprError();
4929
Richard Smithd663fdd2014-12-17 20:42:37 +00004930 QualType CanonParamType = Context.getCanonicalType(ParamType);
4931
Richard Smith410cc892014-11-26 03:26:53 +00004932 // Convert the APValue to a TemplateArgument.
4933 switch (Value.getKind()) {
4934 case APValue::Uninitialized:
4935 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004936 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004937 break;
4938 case APValue::Int:
4939 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004940 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004941 break;
4942 case APValue::MemberPointer: {
4943 assert(ParamType->isMemberPointerType());
4944
4945 // FIXME: We need TemplateArgument representation and mangling for these.
4946 if (!Value.getMemberPointerPath().empty()) {
4947 Diag(Arg->getLocStart(),
4948 diag::err_template_arg_member_ptr_base_derived_not_supported)
4949 << Value.getMemberPointerDecl() << ParamType
4950 << Arg->getSourceRange();
4951 return ExprError();
4952 }
4953
4954 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004955 Converted = VD ? TemplateArgument(VD, CanonParamType)
4956 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004957 break;
4958 }
4959 case APValue::LValue: {
4960 // For a non-type template-parameter of pointer or reference type,
4961 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004962 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4963 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004964 // -- a temporary object
4965 // -- a string literal
4966 // -- the result of a typeid expression, or
4967 // -- a predefind __func__ variable
4968 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4969 if (isa<CXXUuidofExpr>(E)) {
4970 Converted = TemplateArgument(const_cast<Expr*>(E));
4971 break;
4972 }
4973 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4974 << Arg->getSourceRange();
4975 return ExprError();
4976 }
4977 auto *VD = const_cast<ValueDecl *>(
4978 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4979 // -- a subobject
4980 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4981 VD && VD->getType()->isArrayType() &&
4982 Value.getLValuePath()[0].ArrayIndex == 0 &&
4983 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4984 // Per defect report (no number yet):
4985 // ... other than a pointer to the first element of a complete array
4986 // object.
4987 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4988 Value.isLValueOnePastTheEnd()) {
4989 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4990 << Value.getAsString(Context, ParamType);
4991 return ExprError();
4992 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004993 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004994 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004995 assert((!VD || !ParamType->isNullPtrType()) &&
4996 "non-null value of type nullptr_t?");
4997 Converted = VD ? TemplateArgument(VD, CanonParamType)
4998 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004999 break;
5000 }
5001 case APValue::AddrLabelDiff:
5002 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5003 case APValue::Float:
5004 case APValue::ComplexInt:
5005 case APValue::ComplexFloat:
5006 case APValue::Vector:
5007 case APValue::Array:
5008 case APValue::Struct:
5009 case APValue::Union:
5010 llvm_unreachable("invalid kind for template argument");
5011 }
5012
5013 return ArgResult.get();
5014 }
5015
Douglas Gregor86560402009-02-10 23:36:10 +00005016 // C++ [temp.arg.nontype]p5:
5017 // The following conversions are performed on each expression used
5018 // as a non-type template-argument. If a non-type
5019 // template-argument cannot be converted to the type of the
5020 // corresponding template-parameter then the program is
5021 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005022 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005023 // C++11:
5024 // -- for a non-type template-parameter of integral or
5025 // enumeration type, conversions permitted in a converted
5026 // constant expression are applied.
5027 //
5028 // C++98:
5029 // -- for a non-type template-parameter of integral or
5030 // enumeration type, integral promotions (4.5) and integral
5031 // conversions (4.7) are applied.
5032
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005033 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005034 // We can't check arbitrary value-dependent arguments.
5035 // FIXME: If there's no viable conversion to the template parameter type,
5036 // we should be able to diagnose that prior to instantiation.
5037 if (Arg->isValueDependent()) {
5038 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005039 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005040 }
5041
5042 // C++ [temp.arg.nontype]p1:
5043 // A template-argument for a non-type, non-template template-parameter
5044 // shall be one of:
5045 //
5046 // -- for a non-type template-parameter of integral or enumeration
5047 // type, a converted constant expression of the type of the
5048 // template-parameter; or
5049 llvm::APSInt Value;
5050 ExprResult ArgResult =
5051 CheckConvertedConstantExpression(Arg, ParamType, Value,
5052 CCEK_TemplateArg);
5053 if (ArgResult.isInvalid())
5054 return ExprError();
5055
5056 // Widen the argument value to sizeof(parameter type). This is almost
5057 // always a no-op, except when the parameter type is bool. In
5058 // that case, this may extend the argument from 1 bit to 8 bits.
5059 QualType IntegerType = ParamType;
5060 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5061 IntegerType = Enum->getDecl()->getIntegerType();
5062 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5063
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005064 Converted = TemplateArgument(Context, Value,
5065 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005066 return ArgResult;
5067 }
5068
Richard Smith08b12f12011-10-27 22:11:44 +00005069 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5070 if (ArgResult.isInvalid())
5071 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005072 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005073
5074 QualType ArgType = Arg->getType();
5075
Douglas Gregor86560402009-02-10 23:36:10 +00005076 // C++ [temp.arg.nontype]p1:
5077 // A template-argument for a non-type, non-template
5078 // template-parameter shall be one of:
5079 //
5080 // -- an integral constant-expression of integral or enumeration
5081 // type; or
5082 // -- the name of a non-type template-parameter; or
5083 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005084 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005085 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005086 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005087 diag::err_template_arg_not_integral_or_enumeral)
5088 << ArgType << Arg->getSourceRange();
5089 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005090 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005091 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005092 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5093 QualType T;
5094
5095 public:
5096 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005097
5098 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5099 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005100 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5101 }
5102 } Diagnoser(ArgType);
5103
5104 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005105 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005106 if (!Arg)
5107 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005108 }
5109
Richard Smithd663fdd2014-12-17 20:42:37 +00005110 // From here on out, all we care about is the unqualified form
5111 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005112 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005113
5114 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005115 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005116 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005117 } else if (ParamType->isBooleanType()) {
5118 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005119 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005120 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5121 !ParamType->isEnumeralType()) {
5122 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005123 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005124 } else {
5125 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005126 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005127 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005128 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005129 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005130 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005131 }
5132
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005133 // Add the value of this argument to the list of converted
5134 // arguments. We use the bitwidth and signedness of the template
5135 // parameter.
5136 if (Arg->isValueDependent()) {
5137 // The argument is value-dependent. Create a new
5138 // TemplateArgument with the converted expression.
5139 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005140 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005141 }
5142
Douglas Gregor52aba872009-03-14 00:20:21 +00005143 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005144 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005145 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005146
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005147 if (ParamType->isBooleanType()) {
5148 // Value must be zero or one.
5149 Value = Value != 0;
5150 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5151 if (Value.getBitWidth() != AllowedBits)
5152 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005153 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005154 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005155 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005156
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005158 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005159 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005160 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005161 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005162 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005163
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005164 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005165 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005166 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005167 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005168 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5169 << Arg->getSourceRange();
5170 Diag(Param->getLocation(), diag::note_template_param_here);
5171 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005172
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005173 // Complain if we overflowed the template parameter's type.
5174 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005175 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005176 RequiredBits = OldValue.getActiveBits();
5177 else if (OldValue.isUnsigned())
5178 RequiredBits = OldValue.getActiveBits() + 1;
5179 else
5180 RequiredBits = OldValue.getMinSignedBits();
5181 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005182 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005183 diag::warn_template_arg_too_large)
5184 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5185 << Arg->getSourceRange();
5186 Diag(Param->getLocation(), diag::note_template_param_here);
5187 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005188 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005189
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005190 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005191 ParamType->isEnumeralType()
5192 ? Context.getCanonicalType(ParamType)
5193 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005194 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005195 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005196
Richard Smith08b12f12011-10-27 22:11:44 +00005197 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005198 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5199
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005200 // Handle pointer-to-function, reference-to-function, and
5201 // pointer-to-member-function all in (roughly) the same way.
5202 if (// -- For a non-type template-parameter of type pointer to
5203 // function, only the function-to-pointer conversion (4.3) is
5204 // applied. If the template-argument represents a set of
5205 // overloaded functions (or a pointer to such), the matching
5206 // function is selected from the set (13.4).
5207 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005208 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005209 // -- For a non-type template-parameter of type reference to
5210 // function, no conversions apply. If the template-argument
5211 // represents a set of overloaded functions, the matching
5212 // function is selected from the set (13.4).
5213 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005214 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005215 // -- For a non-type template-parameter of type pointer to
5216 // member function, no conversions apply. If the
5217 // template-argument represents a set of overloaded member
5218 // functions, the matching member function is selected from
5219 // the set (13.4).
5220 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005221 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005222 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005223
Douglas Gregor064fdb22010-04-14 23:11:21 +00005224 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005225 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005226 true,
5227 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005228 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005229 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005230
5231 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5232 ArgType = Arg->getType();
5233 } else
John Wiegley01296292011-04-08 18:41:53 +00005234 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005236
John Wiegley01296292011-04-08 18:41:53 +00005237 if (!ParamType->isMemberPointerType()) {
5238 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5239 ParamType,
5240 Arg, Converted))
5241 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005242 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005243 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005244
Douglas Gregor20fdef32012-04-10 17:08:25 +00005245 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5246 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005247 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005248 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005249 }
5250
Chris Lattner696197c2009-02-20 21:37:53 +00005251 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005252 // -- for a non-type template-parameter of type pointer to
5253 // object, qualification conversions (4.4) and the
5254 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005255 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005256 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005257 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005258
John Wiegley01296292011-04-08 18:41:53 +00005259 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5260 ParamType,
5261 Arg, Converted))
5262 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005263 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005264 }
Mike Stump11289f42009-09-09 15:08:12 +00005265
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005266 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005267 // -- For a non-type template-parameter of type reference to
5268 // object, no conversions apply. The type referred to by the
5269 // reference may be more cv-qualified than the (otherwise
5270 // identical) type of the template-argument. The
5271 // template-parameter is bound directly to the
5272 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005273 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005274 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005275
Douglas Gregor064fdb22010-04-14 23:11:21 +00005276 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005277 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5278 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005279 true,
5280 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005281 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005282 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005283
5284 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5285 ArgType = Arg->getType();
5286 } else
John Wiegley01296292011-04-08 18:41:53 +00005287 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005289
John Wiegley01296292011-04-08 18:41:53 +00005290 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5291 ParamType,
5292 Arg, Converted))
5293 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005294 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005295 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005296
Douglas Gregor20fdef32012-04-10 17:08:25 +00005297 // Deal with parameters of type std::nullptr_t.
5298 if (ParamType->isNullPtrType()) {
5299 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5300 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005301 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005302 }
5303
5304 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5305 case NPV_NotNullPointer:
5306 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5307 << Arg->getType() << ParamType;
5308 Diag(Param->getLocation(), diag::note_template_param_here);
5309 return ExprError();
5310
5311 case NPV_Error:
5312 return ExprError();
5313
5314 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005315 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005316 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5317 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005318 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005319 }
5320 }
5321
Douglas Gregor0e558532009-02-11 16:16:59 +00005322 // -- For a non-type template-parameter of type pointer to data
5323 // member, qualification conversions (4.4) are applied.
5324 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5325
Douglas Gregor20fdef32012-04-10 17:08:25 +00005326 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5327 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005328 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005329 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005330}
5331
5332/// \brief Check a template argument against its corresponding
5333/// template template parameter.
5334///
5335/// This routine implements the semantics of C++ [temp.arg.template].
5336/// It returns true if an error occurred, and false otherwise.
5337bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005338 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005339 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005340 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005341 TemplateDecl *Template = Name.getAsTemplateDecl();
5342 if (!Template) {
5343 // Any dependent template name is fine.
5344 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5345 return false;
5346 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005347
Richard Smith3f1b5d02011-05-05 21:57:07 +00005348 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005349 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005350 // the name of a class template or an alias template, expressed as an
5351 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005352 // primary class templates are considered when matching the
5353 // template template argument with the corresponding parameter;
5354 // partial specializations are not considered even if their
5355 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005356 //
5357 // Note that we also allow template template parameters here, which
5358 // will happen when we are dealing with, e.g., class template
5359 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005360 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005361 !isa<TemplateTemplateParmDecl>(Template) &&
5362 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005363 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005364 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005365 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005366 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005367 << Template;
5368 }
5369
Richard Smith1fde8ec2012-09-07 02:06:42 +00005370 TemplateParameterList *Params = Param->getTemplateParameters();
5371 if (Param->isExpandedParameterPack())
5372 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5373
Douglas Gregor85e0f662009-02-10 00:24:35 +00005374 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005375 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005376 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005377 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005378 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005379}
5380
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005381/// \brief Given a non-type template argument that refers to a
5382/// declaration and the type of its corresponding non-type template
5383/// parameter, produce an expression that properly refers to that
5384/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005386Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5387 QualType ParamType,
5388 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005389 // C++ [temp.param]p8:
5390 //
5391 // A non-type template-parameter of type "array of T" or
5392 // "function returning T" is adjusted to be of type "pointer to
5393 // T" or "pointer to function returning T", respectively.
5394 if (ParamType->isArrayType())
5395 ParamType = Context.getArrayDecayedType(ParamType);
5396 else if (ParamType->isFunctionType())
5397 ParamType = Context.getPointerType(ParamType);
5398
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005399 // For a NULL non-type template argument, return nullptr casted to the
5400 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005401 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005402 return ImpCastExprToType(
5403 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5404 ParamType,
5405 ParamType->getAs<MemberPointerType>()
5406 ? CK_NullToMemberPointer
5407 : CK_NullToPointer);
5408 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005409 assert(Arg.getKind() == TemplateArgument::Declaration &&
5410 "Only declaration template arguments permitted here");
5411
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005412 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5413
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005414 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005415 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5416 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005417 // If the value is a class member, we might have a pointer-to-member.
5418 // Determine whether the non-type template template parameter is of
5419 // pointer-to-member type. If so, we need to build an appropriate
5420 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5421 // would refer to the member itself.
5422 if (ParamType->isMemberPointerType()) {
5423 QualType ClassType
5424 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5425 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005426 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005427 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005428 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005429 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005430
5431 // The actual value-ness of this is unimportant, but for
5432 // internal consistency's sake, references to instance methods
5433 // are r-values.
5434 ExprValueKind VK = VK_LValue;
5435 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5436 VK = VK_RValue;
5437
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005439 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005440 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005441 Loc,
5442 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005443 if (RefExpr.isInvalid())
5444 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445
John McCalle3027922010-08-25 11:45:40 +00005446 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005448 // We might need to perform a trailing qualification conversion, since
5449 // the element type on the parameter could be more qualified than the
5450 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005451 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005452 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005453 ParamType.getUnqualifiedType(), false,
5454 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005455 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005456
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005457 assert(!RefExpr.isInvalid() &&
5458 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005459 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005460 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005461 }
5462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005464 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005465
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005466 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005467 // When the non-type template parameter is a pointer, take the
5468 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005469 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005470 if (RefExpr.isInvalid())
5471 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005472
5473 if (T->isFunctionType() || T->isArrayType()) {
5474 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005475 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005476 if (RefExpr.isInvalid())
5477 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005478
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005479 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
Douglas Gregorb242683d2010-04-01 18:32:35 +00005482 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005483 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005484 }
5485
John McCall7decc9e2010-11-18 06:31:45 +00005486 ExprValueKind VK = VK_RValue;
5487
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005488 // If the non-type template parameter has reference type, qualify the
5489 // resulting declaration reference with the extra qualifiers on the
5490 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005491 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5492 VK = VK_LValue;
5493 T = Context.getQualifiedType(T,
5494 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005495 } else if (isa<FunctionDecl>(VD)) {
5496 // References to functions are always lvalues.
5497 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005499
John McCall7decc9e2010-11-18 06:31:45 +00005500 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005501}
5502
5503/// \brief Construct a new expression that refers to the given
5504/// integral template argument with the given source-location
5505/// information.
5506///
5507/// This routine takes care of the mapping from an integral template
5508/// argument (which may have any integral type) to the appropriate
5509/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005511Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5512 SourceLocation Loc) {
5513 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005514 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005515 QualType OrigT = Arg.getIntegralType();
5516
5517 // If this is an enum type that we're instantiating, we need to use an integer
5518 // type the same size as the enumerator. We don't want to build an
5519 // IntegerLiteral with enum type. The integer type of an enum type can be of
5520 // any integral type with C++11 enum classes, make sure we create the right
5521 // type of literal for it.
5522 QualType T = OrigT;
5523 if (const EnumType *ET = OrigT->getAs<EnumType>())
5524 T = ET->getDecl()->getIntegerType();
5525
5526 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005527 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005528 // This does not need to handle u8 character literals because those are
5529 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005530 CharacterLiteral::CharacterKind Kind;
5531 if (T->isWideCharType())
5532 Kind = CharacterLiteral::Wide;
5533 else if (T->isChar16Type())
5534 Kind = CharacterLiteral::UTF16;
5535 else if (T->isChar32Type())
5536 Kind = CharacterLiteral::UTF32;
5537 else
5538 Kind = CharacterLiteral::Ascii;
5539
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005540 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5541 Kind, T, Loc);
5542 } else if (T->isBooleanType()) {
5543 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5544 T, Loc);
5545 } else if (T->isNullPtrType()) {
5546 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5547 } else {
5548 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005549 }
5550
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005551 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005552 // FIXME: This is a hack. We need a better way to handle substituted
5553 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005554 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5555 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005556 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005557 Loc, Loc);
5558 }
5559
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005560 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005561}
5562
Douglas Gregor641040a2011-01-12 23:45:44 +00005563/// \brief Match two template parameters within template parameter lists.
5564static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5565 bool Complain,
5566 Sema::TemplateParameterListEqualKind Kind,
5567 SourceLocation TemplateArgLoc) {
5568 // Check the actual kind (type, non-type, template).
5569 if (Old->getKind() != New->getKind()) {
5570 if (Complain) {
5571 unsigned NextDiag = diag::err_template_param_different_kind;
5572 if (TemplateArgLoc.isValid()) {
5573 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5574 NextDiag = diag::note_template_param_different_kind;
5575 }
5576 S.Diag(New->getLocation(), NextDiag)
5577 << (Kind != Sema::TPL_TemplateMatch);
5578 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5579 << (Kind != Sema::TPL_TemplateMatch);
5580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
Douglas Gregor641040a2011-01-12 23:45:44 +00005582 return false;
5583 }
5584
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005585 // Check that both are parameter packs are neither are parameter packs.
5586 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005587 // template template parameter, the template template parameter can have
5588 // a parameter pack where the template template argument does not.
5589 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5590 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5591 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005592 if (Complain) {
5593 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5594 if (TemplateArgLoc.isValid()) {
5595 S.Diag(TemplateArgLoc,
5596 diag::err_template_arg_template_params_mismatch);
5597 NextDiag = diag::note_template_parameter_pack_non_pack;
5598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005599
Douglas Gregor641040a2011-01-12 23:45:44 +00005600 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5601 : isa<NonTypeTemplateParmDecl>(New)? 1
5602 : 2;
5603 S.Diag(New->getLocation(), NextDiag)
5604 << ParamKind << New->isParameterPack();
5605 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5606 << ParamKind << Old->isParameterPack();
5607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Douglas Gregor641040a2011-01-12 23:45:44 +00005609 return false;
5610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005611
Douglas Gregor641040a2011-01-12 23:45:44 +00005612 // For non-type template parameters, check the type of the parameter.
5613 if (NonTypeTemplateParmDecl *OldNTTP
5614 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5615 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616
Douglas Gregor641040a2011-01-12 23:45:44 +00005617 // If we are matching a template template argument to a template
5618 // template parameter and one of the non-type template parameter types
5619 // is dependent, then we must wait until template instantiation time
5620 // to actually compare the arguments.
5621 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5622 (OldNTTP->getType()->isDependentType() ||
5623 NewNTTP->getType()->isDependentType()))
5624 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625
Douglas Gregor641040a2011-01-12 23:45:44 +00005626 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5627 if (Complain) {
5628 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5629 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005630 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005631 diag::err_template_arg_template_params_mismatch);
5632 NextDiag = diag::note_template_nontype_parm_different_type;
5633 }
5634 S.Diag(NewNTTP->getLocation(), NextDiag)
5635 << NewNTTP->getType()
5636 << (Kind != Sema::TPL_TemplateMatch);
5637 S.Diag(OldNTTP->getLocation(),
5638 diag::note_template_nontype_parm_prev_declaration)
5639 << OldNTTP->getType();
5640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregor641040a2011-01-12 23:45:44 +00005642 return false;
5643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005644
Douglas Gregor641040a2011-01-12 23:45:44 +00005645 return true;
5646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005647
Douglas Gregor641040a2011-01-12 23:45:44 +00005648 // For template template parameters, check the template parameter types.
5649 // The template parameter lists of template template
5650 // parameters must agree.
5651 if (TemplateTemplateParmDecl *OldTTP
5652 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005653 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005654 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5655 OldTTP->getTemplateParameters(),
5656 Complain,
5657 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005659 : Kind),
5660 TemplateArgLoc);
5661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005662
Douglas Gregor641040a2011-01-12 23:45:44 +00005663 return true;
5664}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005665
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005666/// \brief Diagnose a known arity mismatch when comparing template argument
5667/// lists.
5668static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005670 TemplateParameterList *New,
5671 TemplateParameterList *Old,
5672 Sema::TemplateParameterListEqualKind Kind,
5673 SourceLocation TemplateArgLoc) {
5674 unsigned NextDiag = diag::err_template_param_list_different_arity;
5675 if (TemplateArgLoc.isValid()) {
5676 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5677 NextDiag = diag::note_template_param_list_different_arity;
5678 }
5679 S.Diag(New->getTemplateLoc(), NextDiag)
5680 << (New->size() > Old->size())
5681 << (Kind != Sema::TPL_TemplateMatch)
5682 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5683 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5684 << (Kind != Sema::TPL_TemplateMatch)
5685 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5686}
5687
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005688/// \brief Determine whether the given template parameter lists are
5689/// equivalent.
5690///
Mike Stump11289f42009-09-09 15:08:12 +00005691/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005692/// source code as part of a new template declaration.
5693///
5694/// \param Old The old template parameter list, typically found via
5695/// name lookup of the template declared with this template parameter
5696/// list.
5697///
5698/// \param Complain If true, this routine will produce a diagnostic if
5699/// the template parameter lists are not equivalent.
5700///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005701/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005702///
5703/// \param TemplateArgLoc If this source location is valid, then we
5704/// are actually checking the template parameter list of a template
5705/// argument (New) against the template parameter list of its
5706/// corresponding template template parameter (Old). We produce
5707/// slightly different diagnostics in this scenario.
5708///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005709/// \returns True if the template parameter lists are equal, false
5710/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005711bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005712Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5713 TemplateParameterList *Old,
5714 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005715 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005716 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005717 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5718 if (Complain)
5719 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5720 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005721
5722 return false;
5723 }
5724
Douglas Gregor641040a2011-01-12 23:45:44 +00005725 // C++0x [temp.arg.template]p3:
5726 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005727 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005728 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005729 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005730 // template-parameter-list of P. [...]
5731 TemplateParameterList::iterator NewParm = New->begin();
5732 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005733 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005734 OldParmEnd = Old->end();
5735 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005736 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5737 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005738 if (NewParm == NewParmEnd) {
5739 if (Complain)
5740 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5741 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005742
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005743 return false;
5744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005746 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5747 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748 return false;
5749
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005750 ++NewParm;
5751 continue;
5752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005754 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005755 // [...] When P's template- parameter-list contains a template parameter
5756 // pack (14.5.3), the template parameter pack will match zero or more
5757 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005758 // template-parameter-list of A with the same type and form as the
5759 // template parameter pack in P (ignoring whether those template
5760 // parameters are template parameter packs).
5761 for (; NewParm != NewParmEnd; ++NewParm) {
5762 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5763 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005765 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005768 // Make sure we exhausted all of the arguments.
5769 if (NewParm != NewParmEnd) {
5770 if (Complain)
5771 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5772 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005774 return false;
5775 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005776
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005777 return true;
5778}
5779
5780/// \brief Check whether a template can be declared within this scope.
5781///
5782/// If the template declaration is valid in this scope, returns
5783/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005784bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005785Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005786 if (!S)
5787 return false;
5788
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005789 // Find the nearest enclosing declaration scope.
5790 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5791 (S->getFlags() & Scope::TemplateParamScope) != 0)
5792 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005793
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005794 // C++ [temp]p4:
5795 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005796 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005797 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005798 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005799 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005800
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005801 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005802 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005803
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005804 // C++ [temp]p2:
5805 // A template-declaration can appear only as a namespace scope or
5806 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005807 if (Ctx) {
5808 if (Ctx->isFileContext())
5809 return false;
5810 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5811 // C++ [temp.mem]p2:
5812 // A local class shall not have member templates.
5813 if (RD->isLocalClass())
5814 return Diag(TemplateParams->getTemplateLoc(),
5815 diag::err_template_inside_local_class)
5816 << TemplateParams->getSourceRange();
5817 else
5818 return false;
5819 }
5820 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005821
Mike Stump11289f42009-09-09 15:08:12 +00005822 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005823 diag::err_template_outside_namespace_or_class_scope)
5824 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005825}
Douglas Gregor67a65642009-02-17 23:15:12 +00005826
Douglas Gregor54888652009-10-07 00:13:32 +00005827/// \brief Determine what kind of template specialization the given declaration
5828/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005829static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005830 if (!D)
5831 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005832
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005833 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5834 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005835 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5836 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005837 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5838 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005839
Douglas Gregor54888652009-10-07 00:13:32 +00005840 return TSK_Undeclared;
5841}
5842
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005844/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005845///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005846/// This routine determines whether a template specialization can be declared
5847/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005848///
5849/// \param S the semantic analysis object for which this check is being
5850/// performed.
5851///
5852/// \param Specialized the entity being specialized or instantiated, which
5853/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005854/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005855/// member class).
5856///
5857/// \param PrevDecl the previous declaration of this entity, if any.
5858///
5859/// \param Loc the location of the explicit specialization or instantiation of
5860/// this entity.
5861///
5862/// \param IsPartialSpecialization whether this is a partial specialization of
5863/// a class template.
5864///
Douglas Gregor54888652009-10-07 00:13:32 +00005865/// \returns true if there was an error that we cannot recover from, false
5866/// otherwise.
5867static bool CheckTemplateSpecializationScope(Sema &S,
5868 NamedDecl *Specialized,
5869 NamedDecl *PrevDecl,
5870 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005871 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005872 // Keep these "kind" numbers in sync with the %select statements in the
5873 // various diagnostics emitted by this routine.
5874 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005875 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005876 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005877 else if (isa<VarTemplateDecl>(Specialized))
5878 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005879 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005880 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005881 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005882 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005883 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005884 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005885 else if (isa<RecordDecl>(Specialized))
5886 EntityKind = 7;
5887 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5888 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005889 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005890 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005891 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005892 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005893 return true;
5894 }
5895
Douglas Gregorf47b9112009-02-25 22:02:03 +00005896 // C++ [temp.expl.spec]p2:
5897 // An explicit specialization shall be declared in the namespace
5898 // of which the template is a member, or, for member templates, in
5899 // the namespace of which the enclosing class or enclosing class
5900 // template is a member. An explicit specialization of a member
5901 // function, member class or static data member of a class
5902 // template shall be declared in the namespace of which the class
5903 // template is a member. Such a declaration may also be a
5904 // definition. If the declaration is not a definition, the
5905 // specialization may be defined later in the name- space in which
5906 // the explicit specialization was declared, or in a namespace
5907 // that encloses the one in which the explicit specialization was
5908 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005909 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005910 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005911 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005912 return true;
5913 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005914
Douglas Gregor40fb7442009-10-07 17:30:37 +00005915 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005916 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005917 // Do not warn for class scope explicit specialization during
5918 // instantiation, warning was already emitted during pattern
5919 // semantic analysis.
5920 if (!S.ActiveTemplateInstantiations.size())
5921 S.Diag(Loc, diag::ext_function_specialization_in_class)
5922 << Specialized;
5923 } else {
5924 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5925 << Specialized;
5926 return true;
5927 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005930 if (S.CurContext->isRecord() &&
5931 !S.CurContext->Equals(Specialized->getDeclContext())) {
5932 // Make sure that we're specializing in the right record context.
5933 // Otherwise, things can go horribly wrong.
5934 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5935 << Specialized;
5936 return true;
5937 }
5938
Douglas Gregore4b05162009-10-07 17:21:34 +00005939 // C++ [temp.class.spec]p6:
5940 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005941 // in any namespace scope in which its definition may be defined (14.5.1
5942 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005943 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005944 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005945 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005946
5947 // Make sure that this redeclaration (or definition) occurs in an enclosing
5948 // namespace.
5949 // Note that HandleDeclarator() performs this check for explicit
5950 // specializations of function templates, static data members, and member
5951 // functions, so we skip the check here for those kinds of entities.
5952 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5953 // Should we refactor that check, so that it occurs later?
5954 if (!DC->Encloses(SpecializedContext) &&
5955 !(isa<FunctionTemplateDecl>(Specialized) ||
5956 isa<FunctionDecl>(Specialized) ||
5957 isa<VarTemplateDecl>(Specialized) ||
5958 isa<VarDecl>(Specialized))) {
5959 if (isa<TranslationUnitDecl>(SpecializedContext))
5960 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5961 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005962 else if (isa<NamespaceDecl>(SpecializedContext)) {
5963 int Diag = diag::err_template_spec_redecl_out_of_scope;
5964 if (S.getLangOpts().MicrosoftExt)
5965 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5966 S.Diag(Loc, Diag) << EntityKind << Specialized
5967 << cast<NamedDecl>(SpecializedContext);
5968 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005969 llvm_unreachable("unexpected namespace context for specialization");
5970
5971 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5972 } else if ((!PrevDecl ||
5973 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5974 getTemplateSpecializationKind(PrevDecl) ==
5975 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005976 // C++ [temp.exp.spec]p2:
5977 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005978 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005979 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005980 // An explicit specialization of a member function, member class or
5981 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005982 // namespace of which the class template is a member.
5983 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005984 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005986 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005987 // C++11 [temp.explicit]p3:
5988 // An explicit instantiation shall appear in an enclosing namespace of its
5989 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005990 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005991 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005992 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005993 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005994 "DC encloses TU but isn't in enclosing namespace set");
5995 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005996 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005997 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5998 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005999 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006000 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006001 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006002 Diag = diag::ext_template_spec_decl_out_of_scope;
6003 else
6004 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6005 S.Diag(Loc, Diag)
6006 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006008
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006009 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006010 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006012
Douglas Gregorf47b9112009-02-25 22:02:03 +00006013 return false;
6014}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006015
Richard Smith6056d5e2014-02-09 00:54:43 +00006016static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6017 if (!E->isInstantiationDependent())
6018 return SourceLocation();
6019 DependencyChecker Checker(Depth);
6020 Checker.TraverseStmt(E);
6021 if (Checker.Match && Checker.MatchLoc.isInvalid())
6022 return E->getSourceRange();
6023 return Checker.MatchLoc;
6024}
6025
6026static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6027 if (!TL.getType()->isDependentType())
6028 return SourceLocation();
6029 DependencyChecker Checker(Depth);
6030 Checker.TraverseTypeLoc(TL);
6031 if (Checker.Match && Checker.MatchLoc.isInvalid())
6032 return TL.getSourceRange();
6033 return Checker.MatchLoc;
6034}
6035
Larisse Voufo39a1e502013-08-06 01:03:05 +00006036/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006037/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006038static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006039 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6040 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006041 for (unsigned I = 0; I != NumArgs; ++I) {
6042 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006043 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006044 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6045 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006046 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006047
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006048 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006050
Eli Friedmanb826a002012-09-26 02:36:12 +00006051 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006052 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006053
6054 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006055
Douglas Gregor98318c22011-01-03 21:37:45 +00006056 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006057 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6058 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006059
6060 // Strip off any implicit casts we added as part of type checking.
6061 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6062 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006063
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006064 // C++ [temp.class.spec]p8:
6065 // A non-type argument is non-specialized if it is the name of a
6066 // non-type parameter. All other non-type arguments are
6067 // specialized.
6068 //
6069 // Below, we check the two conditions that only apply to
6070 // specialized non-type arguments, so skip any non-specialized
6071 // arguments.
6072 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006073 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006074 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006075
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006076 // C++ [temp.class.spec]p9:
6077 // Within the argument list of a class template partial
6078 // specialization, the following restrictions apply:
6079 // -- A partially specialized non-type argument expression
6080 // shall not involve a template parameter of the partial
6081 // specialization except when the argument expression is a
6082 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006083 SourceRange ParamUseRange =
6084 findTemplateParameter(Param->getDepth(), ArgExpr);
6085 if (ParamUseRange.isValid()) {
6086 if (IsDefaultArgument) {
6087 S.Diag(TemplateNameLoc,
6088 diag::err_dependent_non_type_arg_in_partial_spec);
6089 S.Diag(ParamUseRange.getBegin(),
6090 diag::note_dependent_non_type_default_arg_in_partial_spec)
6091 << ParamUseRange;
6092 } else {
6093 S.Diag(ParamUseRange.getBegin(),
6094 diag::err_dependent_non_type_arg_in_partial_spec)
6095 << ParamUseRange;
6096 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006097 return true;
6098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006099
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006100 // -- The type of a template parameter corresponding to a
6101 // specialized non-type argument shall not be dependent on a
6102 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006103 //
6104 // FIXME: We need to delay this check until instantiation in some cases:
6105 //
6106 // template<template<typename> class X> struct A {
6107 // template<typename T, X<T> N> struct B;
6108 // template<typename T> struct B<T, 0>;
6109 // };
6110 // template<typename> using X = int;
6111 // A<X>::B<int, 0> b;
6112 ParamUseRange = findTemplateParameter(
6113 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6114 if (ParamUseRange.isValid()) {
6115 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6116 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6117 << Param->getType() << ParamUseRange;
6118 S.Diag(Param->getLocation(), diag::note_template_param_here)
6119 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006120 return true;
6121 }
6122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006123
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006124 return false;
6125}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006126
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006127/// \brief Check the non-type template arguments of a class template
6128/// partial specialization according to C++ [temp.class.spec]p9.
6129///
Richard Smith6056d5e2014-02-09 00:54:43 +00006130/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006131/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006132/// template.
6133/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006134/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006135/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006136///
Richard Smith6056d5e2014-02-09 00:54:43 +00006137/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006138static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006139 Sema &S, SourceLocation TemplateNameLoc,
6140 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006141 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006142 const TemplateArgument *ArgList = TemplateArgs.data();
6143
6144 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6145 NonTypeTemplateParmDecl *Param
6146 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6147 if (!Param)
6148 continue;
6149
Richard Smith6056d5e2014-02-09 00:54:43 +00006150 if (CheckNonTypeTemplatePartialSpecializationArgs(
6151 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006152 return true;
6153 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006154
6155 return false;
6156}
6157
John McCall48871652010-08-21 09:40:31 +00006158DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006159Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6160 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006161 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006162 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006163 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006164 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006165 MultiTemplateParamsArg
6166 TemplateParameterLists,
6167 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006168 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006169
Richard Smith4b55a9c2014-04-17 03:29:33 +00006170 CXXScopeSpec &SS = TemplateId.SS;
6171
Abramo Bagnara60804e12011-03-18 15:16:37 +00006172 // NOTE: KWLoc is the location of the tag keyword. This will instead
6173 // store the location of the outermost template keyword in the declaration.
6174 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006175 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6176 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6177 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6178 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006179
Douglas Gregor67a65642009-02-17 23:15:12 +00006180 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006181 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006182 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006183 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6184
6185 if (!ClassTemplate) {
6186 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006187 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006188 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6189 return true;
6190 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006191
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006192 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006193 bool isPartialSpecialization = false;
6194
Douglas Gregorf47b9112009-02-25 22:02:03 +00006195 // Check the validity of the template headers that introduce this
6196 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006197 // FIXME: We probably shouldn't complain about these headers for
6198 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006199 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006200 TemplateParameterList *TemplateParams =
6201 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006202 KWLoc, TemplateNameLoc, SS, &TemplateId,
6203 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6204 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006205 if (Invalid)
6206 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006207
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006208 if (TemplateParams && TemplateParams->size() > 0) {
6209 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006210
Douglas Gregorec9518b2010-12-21 08:14:57 +00006211 if (TUK == TUK_Friend) {
6212 Diag(KWLoc, diag::err_partial_specialization_friend)
6213 << SourceRange(LAngleLoc, RAngleLoc);
6214 return true;
6215 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006216
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006217 // C++ [temp.class.spec]p10:
6218 // The template parameter list of a specialization shall not
6219 // contain default template argument values.
6220 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6221 Decl *Param = TemplateParams->getParam(I);
6222 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6223 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006224 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006225 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006226 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006227 }
6228 } else if (NonTypeTemplateParmDecl *NTTP
6229 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6230 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006231 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006232 diag::err_default_arg_in_partial_spec)
6233 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006234 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006235 }
6236 } else {
6237 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006238 if (TTP->hasDefaultArgument()) {
6239 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006240 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006241 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006242 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006243 }
6244 }
6245 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006246 } else if (TemplateParams) {
6247 if (TUK == TUK_Friend)
6248 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006249 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006250 SourceRange(TemplateParams->getTemplateLoc(),
6251 TemplateParams->getRAngleLoc()))
6252 << SourceRange(LAngleLoc, RAngleLoc);
6253 else
6254 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006255 } else {
6256 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006257 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006258
Douglas Gregor67a65642009-02-17 23:15:12 +00006259 // Check that the specialization uses the same tag kind as the
6260 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006261 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6262 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006263 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006264 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006265 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006266 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006267 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006268 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006269 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006270 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006271 diag::note_previous_use);
6272 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6273 }
6274
Douglas Gregorc40290e2009-03-09 23:48:35 +00006275 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006276 TemplateArgumentListInfo TemplateArgs =
6277 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006278
Douglas Gregor14406932011-01-03 20:35:03 +00006279 // Check for unexpanded parameter packs in any of the template arguments.
6280 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006281 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006282 UPPC_PartialSpecialization))
6283 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006284
Douglas Gregor67a65642009-02-17 23:15:12 +00006285 // Check that the template argument list is well-formed for this
6286 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006287 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006288 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6289 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006290 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006291
Douglas Gregor2373c592009-05-31 09:31:02 +00006292 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006293 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006294 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006295 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006296 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6297 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006298 return true;
6299
Douglas Gregor678d76c2011-07-01 01:22:09 +00006300 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006301 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006302 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006303 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006304 TemplateArgs.size(),
6305 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006306 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6307 << ClassTemplate->getDeclName();
6308 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006309 }
6310 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006311
Craig Topperc3ec1492014-05-26 06:22:03 +00006312 void *InsertPos = nullptr;
6313 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006314
6315 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006316 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006317 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006318 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006319 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006320
Craig Topperc3ec1492014-05-26 06:22:03 +00006321 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006322
Douglas Gregorf47b9112009-02-25 22:02:03 +00006323 // Check whether we can declare a class template specialization in
6324 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006325 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006326 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6327 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006328 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006329 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006330
Douglas Gregor15301382009-07-30 17:40:51 +00006331 // The canonical type
6332 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006333 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006334 // Build the canonical type that describes the converted template
6335 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006336 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6337 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006338 Converted.data(),
6339 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006340
6341 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006342 ClassTemplate->getInjectedClassNameSpecialization())) {
6343 // C++ [temp.class.spec]p9b3:
6344 //
6345 // -- The argument list of the specialization shall not be identical
6346 // to the implicit argument list of the primary template.
6347 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006348 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006349 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006350 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6351 ClassTemplate->getIdentifier(),
6352 TemplateNameLoc,
6353 Attr,
6354 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006355 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006356 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006357 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006358 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006359 }
Douglas Gregor15301382009-07-30 17:40:51 +00006360
Douglas Gregor2373c592009-05-31 09:31:02 +00006361 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006362 ClassTemplatePartialSpecializationDecl *PrevPartial
6363 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006364 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006365 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006366 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006367 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006368 TemplateParams,
6369 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006370 Converted.data(),
6371 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006372 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006373 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006374 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006375 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006376 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006377 Partial->setTemplateParameterListsInfo(
6378 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006379 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006380
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006381 if (!PrevPartial)
6382 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006383 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006384
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006385 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006386 // template specialization, make a note of that.
6387 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6388 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006389
Douglas Gregor91772d12009-06-13 00:26:55 +00006390 // Check that all of the template parameters of the class template
6391 // partial specialization are deducible from the template
6392 // arguments. If not, this class template partial specialization
6393 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006394 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006395 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006396 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006397 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006398
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006399 if (!DeducibleParams.all()) {
6400 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006401 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006402 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006403 << SourceRange(TemplateNameLoc, RAngleLoc);
6404 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6405 if (!DeducibleParams[I]) {
6406 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6407 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006408 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006409 diag::note_partial_spec_unused_parameter)
6410 << Param->getDeclName();
6411 else
Mike Stump11289f42009-09-09 15:08:12 +00006412 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006413 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006414 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006415 }
6416 }
6417 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006418 } else {
6419 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006420 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006421 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006422 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006423 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006424 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006425 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006426 Converted.data(),
6427 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006428 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006429 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006430 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006431 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006432 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006433 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006434
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006435 if (!PrevDecl)
6436 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006437
David Majnemer678f50b2015-11-18 19:49:19 +00006438 if (CurContext->isDependentContext()) {
6439 // -fms-extensions permits specialization of nested classes without
6440 // fully specializing the outer class(es).
6441 assert(getLangOpts().MicrosoftExt &&
6442 "Only possible with -fms-extensions!");
6443 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6444 CanonType = Context.getTemplateSpecializationType(
6445 CanonTemplate, Converted.data(), Converted.size());
6446 } else {
6447 CanonType = Context.getTypeDeclType(Specialization);
6448 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006449 }
6450
Douglas Gregor06db9f52009-10-12 20:18:28 +00006451 // C++ [temp.expl.spec]p6:
6452 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006454 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006455 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006456 // use occurs; no diagnostic is required.
6457 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006458 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006459 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006460 // Is there any previous explicit specialization declaration?
6461 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6462 Okay = true;
6463 break;
6464 }
6465 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006466
Douglas Gregorc854c662010-02-26 06:03:23 +00006467 if (!Okay) {
6468 SourceRange Range(TemplateNameLoc, RAngleLoc);
6469 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6470 << Context.getTypeDeclType(Specialization) << Range;
6471
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006473 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006474 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006475 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006476 return true;
6477 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479
Douglas Gregor2208a292009-09-26 20:57:03 +00006480 // If this is not a friend, note that this is an explicit specialization.
6481 if (TUK != TUK_Friend)
6482 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006483
6484 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006485 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006486 RecordDecl *Def = Specialization->getDefinition();
6487 NamedDecl *Hidden = nullptr;
6488 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6489 SkipBody->ShouldSkip = true;
6490 makeMergedDefinitionVisible(Hidden, KWLoc);
6491 // From here on out, treat this as just a redeclaration.
6492 TUK = TUK_Declaration;
6493 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006494 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006495 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006496 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006497 Diag(Def->getLocation(), diag::note_previous_definition);
6498 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006499 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006500 }
6501 }
6502
John McCall659a3372010-12-18 03:30:47 +00006503 if (Attr)
6504 ProcessDeclAttributeList(S, Specialization, Attr);
6505
Richard Smith034b94a2012-08-17 03:20:55 +00006506 // Add alignment attributes if necessary; these attributes are checked when
6507 // the ASTContext lays out the structure.
6508 if (TUK == TUK_Definition) {
6509 AddAlignmentAttributesForRecord(Specialization);
6510 AddMsStructLayoutForRecord(Specialization);
6511 }
6512
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006513 if (ModulePrivateLoc.isValid())
6514 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6515 << (isPartialSpecialization? 1 : 0)
6516 << FixItHint::CreateRemoval(ModulePrivateLoc);
6517
Douglas Gregord56a91e2009-02-26 22:19:44 +00006518 // Build the fully-sugared type for this class template
6519 // specialization as the user wrote in the specialization
6520 // itself. This means that we'll pretty-print the type retrieved
6521 // from the specialization's declaration the way that the user
6522 // actually wrote the specialization, rather than formatting the
6523 // name based on the "canonical" representation used to store the
6524 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006525 TypeSourceInfo *WrittenTy
6526 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6527 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006528 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006529 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006530 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006531 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006532
Douglas Gregor1e249f82009-02-25 22:18:32 +00006533 // C++ [temp.expl.spec]p9:
6534 // A template explicit specialization is in the scope of the
6535 // namespace in which the template was defined.
6536 //
6537 // We actually implement this paragraph where we set the semantic
6538 // context (in the creation of the ClassTemplateSpecializationDecl),
6539 // but we also maintain the lexical context where the actual
6540 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006541 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006542
Douglas Gregor67a65642009-02-17 23:15:12 +00006543 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006544 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006545 Specialization->startDefinition();
6546
Douglas Gregor2208a292009-09-26 20:57:03 +00006547 if (TUK == TUK_Friend) {
6548 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6549 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006550 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006551 /*FIXME:*/KWLoc);
6552 Friend->setAccess(AS_public);
6553 CurContext->addDecl(Friend);
6554 } else {
6555 // Add the specialization into its lexical context, so that it can
6556 // be seen when iterating through the list of declarations in that
6557 // context. However, specializations are not found by name lookup.
6558 CurContext->addDecl(Specialization);
6559 }
John McCall48871652010-08-21 09:40:31 +00006560 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006561}
Douglas Gregor333489b2009-03-27 23:10:48 +00006562
John McCall48871652010-08-21 09:40:31 +00006563Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006564 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006565 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006566 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006567 ActOnDocumentableDecl(NewDecl);
6568 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006569}
6570
John McCall4f7ced62010-02-11 01:33:53 +00006571/// \brief Strips various properties off an implicit instantiation
6572/// that has just been explicitly specialized.
6573static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006574 D->dropAttr<DLLImportAttr>();
6575 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006576
Nico Webere4974382014-12-19 23:52:45 +00006577 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006578 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006579}
6580
Nico Webera8f80b32012-01-09 19:52:25 +00006581/// \brief Compute the diagnostic location for an explicit instantiation
6582// declaration or definition.
6583static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006584 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006585 // Explicit instantiations following a specialization have no effect and
6586 // hence no PointOfInstantiation. In that case, walk decl backwards
6587 // until a valid name loc is found.
6588 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006589 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6590 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006591 PrevDiagLoc = Prev->getLocation();
6592 }
6593 assert(PrevDiagLoc.isValid() &&
6594 "Explicit instantiation without point of instantiation?");
6595 return PrevDiagLoc;
6596}
6597
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006598/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006599/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006600/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006601/// new specialization/instantiation will have any effect.
6602///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006603/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006604/// instantiation.
6605///
6606/// \param NewTSK the kind of the new explicit specialization or instantiation.
6607///
6608/// \param PrevDecl the previous declaration of the entity.
6609///
6610/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6611///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006613/// declaration was instantiated (either implicitly or explicitly).
6614///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006615/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006616/// specialization or instantiation has no effect and should be ignored.
6617///
6618/// \returns true if there was an error that should prevent the introduction of
6619/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006620bool
6621Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6622 TemplateSpecializationKind NewTSK,
6623 NamedDecl *PrevDecl,
6624 TemplateSpecializationKind PrevTSK,
6625 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006626 bool &HasNoEffect) {
6627 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006628
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006629 switch (NewTSK) {
6630 case TSK_Undeclared:
6631 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006632 assert(
6633 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6634 "previous declaration must be implicit!");
6635 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006637 case TSK_ExplicitSpecialization:
6638 switch (PrevTSK) {
6639 case TSK_Undeclared:
6640 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006641 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006642 // explicitly specialized or has merely been mentioned without any
6643 // instantiation.
6644 return false;
6645
6646 case TSK_ImplicitInstantiation:
6647 if (PrevPointOfInstantiation.isInvalid()) {
6648 // The declaration itself has not actually been instantiated, so it is
6649 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006650 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006651 return false;
6652 }
6653 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006654
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006655 case TSK_ExplicitInstantiationDeclaration:
6656 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657 assert((PrevTSK == TSK_ImplicitInstantiation ||
6658 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006659 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006661 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006662 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006663 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006665 // implicit instantiation to take place, in every translation unit in
6666 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006667 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006668 // Is there any previous explicit specialization declaration?
6669 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6670 return false;
6671 }
6672
Douglas Gregor1d957a32009-10-27 18:42:08 +00006673 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006674 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006675 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006676 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006678 return true;
6679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006681 case TSK_ExplicitInstantiationDeclaration:
6682 switch (PrevTSK) {
6683 case TSK_ExplicitInstantiationDeclaration:
6684 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006685 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006686 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006687
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006688 case TSK_Undeclared:
6689 case TSK_ImplicitInstantiation:
6690 // We're explicitly instantiating something that may have already been
6691 // implicitly instantiated; that's fine.
6692 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006693
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006694 case TSK_ExplicitSpecialization:
6695 // C++0x [temp.explicit]p4:
6696 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006698 // specialization for that template, the explicit instantiation has no
6699 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006700 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006701 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006703 case TSK_ExplicitInstantiationDefinition:
6704 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006705 // If an entity is the subject of both an explicit instantiation
6706 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006707 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006708 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006709 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006710
6711 // Explicit instantiations following a specialization have no effect and
6712 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6713 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006714 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6715 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006716 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006717 return false;
6718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006719
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006720 case TSK_ExplicitInstantiationDefinition:
6721 switch (PrevTSK) {
6722 case TSK_Undeclared:
6723 case TSK_ImplicitInstantiation:
6724 // We're explicitly instantiating something that may have already been
6725 // implicitly instantiated; that's fine.
6726 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006727
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006728 case TSK_ExplicitSpecialization:
6729 // C++ DR 259, C++0x [temp.explicit]p4:
6730 // For a given set of template parameters, if an explicit
6731 // instantiation of a template appears after a declaration of
6732 // an explicit specialization for that template, the explicit
6733 // instantiation has no effect.
6734 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006735 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006736 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006737 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006738 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006739 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6740 diag::ext_explicit_instantiation_after_specialization)
6741 << PrevDecl;
6742 Diag(PrevDecl->getLocation(),
6743 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006744 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006745 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006746
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006747 case TSK_ExplicitInstantiationDeclaration:
6748 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006749 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006750
6751 // C++0x [temp.explicit]p4:
6752 // For a given set of template parameters, if an explicit instantiation
6753 // of a template appears after a declaration of an explicit
6754 // specialization for that template, the explicit instantiation has no
6755 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006756 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006757 // Is there any previous explicit specialization declaration?
6758 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6759 HasNoEffect = true;
6760 break;
6761 }
6762 }
6763
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006764 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006766 case TSK_ExplicitInstantiationDefinition:
6767 // C++0x [temp.spec]p5:
6768 // For a given template and a given set of template-arguments,
6769 // - an explicit instantiation definition shall appear at most once
6770 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006771
6772 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6773 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006774 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006775 : diag::err_explicit_instantiation_duplicate)
6776 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006777 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006778 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006779 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006780 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006781 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006783
David Blaikie83d382b2011-09-23 05:06:16 +00006784 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006785}
6786
John McCallb9c78482010-04-08 09:05:18 +00006787/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006788/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006789///
James Dennettf14a6e52012-06-15 22:23:43 +00006790/// The only possible way to get a dependent function template specialization
6791/// is with a friend declaration, like so:
6792///
6793/// \code
6794/// template \<class T> void foo(T);
6795/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006796/// friend void foo<>(T);
6797/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006798/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006799///
6800/// There really isn't any useful analysis we can do here, so we
6801/// just store the information.
6802bool
6803Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6804 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6805 LookupResult &Previous) {
6806 // Remove anything from Previous that isn't a function template in
6807 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006808 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006809 LookupResult::Filter F = Previous.makeFilter();
6810 while (F.hasNext()) {
6811 NamedDecl *D = F.next()->getUnderlyingDecl();
6812 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006813 !FDLookupContext->InEnclosingNamespaceSetOf(
6814 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006815 F.erase();
6816 }
6817 F.done();
6818
6819 // Should this be diagnosed here?
6820 if (Previous.empty()) return true;
6821
6822 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6823 ExplicitTemplateArgs);
6824 return false;
6825}
6826
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006827/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006828/// specialization.
6829///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006830/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006831/// explicit function template specialization. On successful completion,
6832/// the function declaration \p FD will become a function template
6833/// specialization.
6834///
6835/// \param FD the function declaration, which will be updated to become a
6836/// function template specialization.
6837///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006838/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6839/// if any. Note that this may be valid info even when 0 arguments are
6840/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6841/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006842///
Francois Pichet3a44e432011-07-08 06:21:47 +00006843/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006844/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006845bool Sema::CheckFunctionTemplateSpecialization(
6846 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6847 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006848 // The set of function template specializations that could match this
6849 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006850 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006851 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6852 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006853
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006854 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6855 ConvertedTemplateArgs;
6856
Sebastian Redl50c68252010-08-31 00:36:30 +00006857 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006858 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6859 I != E; ++I) {
6860 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6861 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006863 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006864 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6865 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006866 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006867
Richard Smith574f4f62013-01-14 05:37:29 +00006868 // When matching a constexpr member function template specialization
6869 // against the primary template, we don't yet know whether the
6870 // specialization has an implicit 'const' (because we don't know whether
6871 // it will be a static member function until we know which template it
6872 // specializes), so adjust it now assuming it specializes this template.
6873 QualType FT = FD->getType();
6874 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006875 CXXMethodDecl *OldMD =
6876 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006877 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006878 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006879 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6880 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006881 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006882 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006883 }
6884 }
6885
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006886 TemplateArgumentListInfo Args;
6887 if (ExplicitTemplateArgs)
6888 Args = *ExplicitTemplateArgs;
6889
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006890 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891 // A trailing template-argument can be left unspecified in the
6892 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006893 // provided it can be deduced from the function argument type.
6894 // Perform template argument deduction to determine whether we may be
6895 // specializing this template.
6896 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006897 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006898 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006899 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6900 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00006901 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
6902 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006903 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006904 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00006905 FailedCandidates.addCandidate().set(
6906 I.getPair(), FunTmpl->getTemplatedDecl(),
6907 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006908 (void)TDK;
6909 continue;
6910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006912 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006913 if (ExplicitTemplateArgs)
6914 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006915 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006916 }
6917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
Douglas Gregor5de279c2009-09-26 03:41:46 +00006919 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006920 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006921 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006922 FD->getLocation(),
6923 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6924 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006925 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006926 PDiag(diag::note_function_template_spec_matched));
6927
John McCall58cc69d2010-01-27 01:50:18 +00006928 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006929 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006930
6931 // Ignore access information; it doesn't figure into redeclaration checking.
6932 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006933
Nathan Wilson83839122016-04-09 02:55:27 +00006934 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6935 // an explicit specialization (14.8.3) [...] of a concept definition.
6936 if (Specialization->getPrimaryTemplate()->isConcept()) {
6937 Diag(FD->getLocation(), diag::err_concept_specialized)
6938 << 0 /*function*/ << 1 /*explicitly specialized*/;
6939 Diag(Specialization->getLocation(), diag::note_previous_declaration);
6940 return true;
6941 }
6942
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006943 FunctionTemplateSpecializationInfo *SpecInfo
6944 = Specialization->getTemplateSpecializationInfo();
6945 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006946
6947 // Note: do not overwrite location info if previous template
6948 // specialization kind was explicit.
6949 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006950 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006951 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006952 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6953 // function can differ from the template declaration with respect to
6954 // the constexpr specifier.
6955 Specialization->setConstexpr(FD->isConstexpr());
6956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006958 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006959 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006960
6961 // If this is a friend declaration, then we're not really declaring
6962 // an explicit specialization.
6963 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006964
Douglas Gregor54888652009-10-07 00:13:32 +00006965 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006966 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006968 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006970 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006971 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006972
6973 // C++ [temp.expl.spec]p6:
6974 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006976 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006977 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006978 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006979 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006980 if (!isFriend &&
6981 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006982 TSK_ExplicitSpecialization,
6983 Specialization,
6984 SpecInfo->getTemplateSpecializationKind(),
6985 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006986 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006987 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006988
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006989 // Mark the prior declaration as an explicit specialization, so that later
6990 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006991 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00006992 // Since explicit specializations do not inherit '=delete' from their
6993 // primary function template - check if the 'specialization' that was
6994 // implicitly generated (during template argument deduction for partial
6995 // ordering) from the most specialized of all the function templates that
6996 // 'FD' could have been specializing, has a 'deleted' definition. If so,
6997 // first check that it was implicitly generated during template argument
6998 // deduction by making sure it wasn't referenced, and then reset the deleted
6999 // flag to not-deleted, so that we can inherit that information from 'FD'.
7000 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7001 !Specialization->getCanonicalDecl()->isReferenced()) {
7002 assert(
7003 Specialization->getCanonicalDecl() == Specialization &&
7004 "This must be the only existing declaration of this specialization");
7005 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007006 }
John McCall816d75b2010-03-24 07:46:06 +00007007 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007008 MarkUnusedFileScopedDecl(Specialization);
7009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007011 // Turn the given function declaration into a function template
7012 // specialization, with the template arguments from the previous
7013 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007014 // Take copies of (semantic and syntactic) template argument lists.
7015 const TemplateArgumentList* TemplArgs = new (Context)
7016 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007017 FD->setFunctionTemplateSpecialization(
7018 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7019 SpecInfo->getTemplateSpecializationKind(),
7020 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007021
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007022 // The "previous declaration" for this function template specialization is
7023 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007024 Previous.clear();
7025 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007026 return false;
7027}
7028
Douglas Gregor86d142a2009-10-08 07:24:58 +00007029/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007030/// specialization.
7031///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007032/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007033/// explicit member function specialization. On successful completion,
7034/// the function declaration \p FD will become a member function
7035/// specialization.
7036///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007037/// \param Member the member declaration, which will be updated to become a
7038/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007039///
John McCall1f82f242009-11-18 22:49:29 +00007040/// \param Previous the set of declarations, one of which may be specialized
7041/// by this function specialization; the set will be modified to contain the
7042/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043bool
John McCall1f82f242009-11-18 22:49:29 +00007044Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007045 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007046
Douglas Gregor86d142a2009-10-08 07:24:58 +00007047 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007048 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007049 NamedDecl *Instantiation = nullptr;
7050 NamedDecl *InstantiatedFrom = nullptr;
7051 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007052
John McCall1f82f242009-11-18 22:49:29 +00007053 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007054 // Nowhere to look anyway.
7055 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007056 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7057 I != E; ++I) {
7058 NamedDecl *D = (*I)->getUnderlyingDecl();
7059 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007060 QualType Adjusted = Function->getType();
7061 if (!hasExplicitCallingConv(Adjusted))
7062 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7063 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007064 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007065 Instantiation = Method;
7066 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007067 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007068 break;
7069 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007070 }
7071 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007072 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007073 VarDecl *PrevVar;
7074 if (Previous.isSingleResult() &&
7075 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007076 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007077 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007078 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007079 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007080 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007081 }
7082 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007083 CXXRecordDecl *PrevRecord;
7084 if (Previous.isSingleResult() &&
7085 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007086 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007087 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007088 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007089 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007090 }
Richard Smith7d137e32012-03-23 03:33:32 +00007091 } else if (isa<EnumDecl>(Member)) {
7092 EnumDecl *PrevEnum;
7093 if (Previous.isSingleResult() &&
7094 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007095 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007096 Instantiation = PrevEnum;
7097 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7098 MSInfo = PrevEnum->getMemberSpecializationInfo();
7099 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007101
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007102 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007103 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007104 // specializations are always out-of-line, the caller will complain about
7105 // this mismatch later.
7106 return false;
7107 }
John McCalle820e5e2010-04-13 20:37:33 +00007108
7109 // If this is a friend, just bail out here before we start turning
7110 // things into explicit specializations.
7111 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7112 // Preserve instantiation information.
7113 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7114 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7115 cast<CXXMethodDecl>(InstantiatedFrom),
7116 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7117 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7118 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7119 cast<CXXRecordDecl>(InstantiatedFrom),
7120 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7121 }
7122
7123 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007124 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007125 return false;
7126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007127
Douglas Gregor86d142a2009-10-08 07:24:58 +00007128 // Make sure that this is a specialization of a member.
7129 if (!InstantiatedFrom) {
7130 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7131 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007132 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7133 return true;
7134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007135
Douglas Gregor06db9f52009-10-12 20:18:28 +00007136 // C++ [temp.expl.spec]p6:
7137 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007138 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007139 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007141 // use occurs; no diagnostic is required.
7142 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007143
Abramo Bagnara8075c852010-06-12 07:44:57 +00007144 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007145 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7146 TSK_ExplicitSpecialization,
7147 Instantiation,
7148 MSInfo->getTemplateSpecializationKind(),
7149 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007150 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007151 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007152
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007153 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007154 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007155 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007156 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007157 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007158 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007159
Douglas Gregor86d142a2009-10-08 07:24:58 +00007160 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007161 // the original declaration to note that it is an explicit specialization
7162 // (if it was previously an implicit instantiation). This latter step
7163 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007164 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007165 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7166 if (InstantiationFunction->getTemplateSpecializationKind() ==
7167 TSK_ImplicitInstantiation) {
7168 InstantiationFunction->setTemplateSpecializationKind(
7169 TSK_ExplicitSpecialization);
7170 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007171 // Explicit specializations of member functions of class templates do not
7172 // inherit '=delete' from the member function they are specializing.
7173 if (InstantiationFunction->isDeleted()) {
7174 assert(InstantiationFunction->getCanonicalDecl() ==
7175 InstantiationFunction);
7176 InstantiationFunction->setDeletedAsWritten(false);
7177 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007179
Douglas Gregor86d142a2009-10-08 07:24:58 +00007180 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7181 cast<CXXMethodDecl>(InstantiatedFrom),
7182 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007183 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007184 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007185 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7186 if (InstantiationVar->getTemplateSpecializationKind() ==
7187 TSK_ImplicitInstantiation) {
7188 InstantiationVar->setTemplateSpecializationKind(
7189 TSK_ExplicitSpecialization);
7190 InstantiationVar->setLocation(Member->getLocation());
7191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007192
Larisse Voufo39a1e502013-08-06 01:03:05 +00007193 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7194 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007195 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007196 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007197 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7198 if (InstantiationClass->getTemplateSpecializationKind() ==
7199 TSK_ImplicitInstantiation) {
7200 InstantiationClass->setTemplateSpecializationKind(
7201 TSK_ExplicitSpecialization);
7202 InstantiationClass->setLocation(Member->getLocation());
7203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007204
Douglas Gregor86d142a2009-10-08 07:24:58 +00007205 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007206 cast<CXXRecordDecl>(InstantiatedFrom),
7207 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007208 } else {
7209 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7210 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7211 if (InstantiationEnum->getTemplateSpecializationKind() ==
7212 TSK_ImplicitInstantiation) {
7213 InstantiationEnum->setTemplateSpecializationKind(
7214 TSK_ExplicitSpecialization);
7215 InstantiationEnum->setLocation(Member->getLocation());
7216 }
7217
7218 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7219 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007221
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007222 // Save the caller the trouble of having to figure out which declaration
7223 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007224 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007225 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007226 return false;
7227}
7228
Douglas Gregore47f5a72009-10-14 23:41:34 +00007229/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007230///
7231/// \returns true if a serious error occurs, false otherwise.
7232static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007233 SourceLocation InstLoc,
7234 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007235 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7236 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007237
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007238 if (CurContext->isRecord()) {
7239 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7240 << D;
7241 return true;
7242 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007243
Richard Smith050d2612011-10-18 02:28:33 +00007244 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007245 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007246 // template. If the name declared in the explicit instantiation is an
7247 // unqualified name, the explicit instantiation shall appear in the
7248 // namespace where its template is declared or, if that namespace is inline
7249 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007250 //
7251 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007252 if (WasQualifiedName) {
7253 if (CurContext->Encloses(OrigContext))
7254 return false;
7255 } else {
7256 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7257 return false;
7258 }
7259
7260 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7261 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007262 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007263 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007264 diag::err_explicit_instantiation_out_of_scope :
7265 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007266 << D << NS;
7267 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007268 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007269 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007270 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7271 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7272 << D << NS;
7273 } else
7274 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007275 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007276 diag::err_explicit_instantiation_must_be_global :
7277 diag::warn_explicit_instantiation_must_be_global_0x)
7278 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007279 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007280 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007281}
7282
7283/// \brief Determine whether the given scope specifier has a template-id in it.
7284static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7285 if (!SS.isSet())
7286 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007287
Richard Smith050d2612011-10-18 02:28:33 +00007288 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007289 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007290 // or a static data member of a class template specialization, the name of
7291 // the class template specialization in the qualified-id for the member
7292 // name shall be a simple-template-id.
7293 //
7294 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007295 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7296 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007297 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007298 if (isa<TemplateSpecializationType>(T))
7299 return true;
7300
7301 return false;
7302}
7303
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007304// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007305DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007306Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007307 SourceLocation ExternLoc,
7308 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007309 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007310 SourceLocation KWLoc,
7311 const CXXScopeSpec &SS,
7312 TemplateTy TemplateD,
7313 SourceLocation TemplateNameLoc,
7314 SourceLocation LAngleLoc,
7315 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007316 SourceLocation RAngleLoc,
7317 AttributeList *Attr) {
7318 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007319 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007320 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007321 // Check that the specialization uses the same tag kind as the
7322 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007323 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7324 assert(Kind != TTK_Enum &&
7325 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007326
Richard Trieu265c3442016-04-05 21:13:54 +00007327 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7328
7329 if (!ClassTemplate) {
7330 unsigned ErrorKind = 0;
7331 if (isa<TypeAliasTemplateDecl>(TD)) {
7332 ErrorKind = 4;
7333 } else if (isa<TemplateTemplateParmDecl>(TD)) {
7334 ErrorKind = 5;
7335 }
7336
7337 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7338 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007339 return true;
7340 }
7341
Douglas Gregord9034f02009-05-14 16:41:31 +00007342 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007343 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007344 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007345 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007346 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007347 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007348 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007349 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007350 diag::note_previous_use);
7351 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7352 }
7353
Douglas Gregore47f5a72009-10-14 23:41:34 +00007354 // C++0x [temp.explicit]p2:
7355 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007356 // definition and an explicit instantiation declaration. An explicit
7357 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007358 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7359 ? TSK_ExplicitInstantiationDefinition
7360 : TSK_ExplicitInstantiationDeclaration;
7361
7362 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7363 // Check for dllexport class template instantiation declarations.
7364 for (AttributeList *A = Attr; A; A = A->getNext()) {
7365 if (A->getKind() == AttributeList::AT_DLLExport) {
7366 Diag(ExternLoc,
7367 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7368 Diag(A->getLoc(), diag::note_attribute);
7369 break;
7370 }
7371 }
7372
7373 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7374 Diag(ExternLoc,
7375 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7376 Diag(A->getLocation(), diag::note_attribute);
7377 }
7378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007379
Hans Wennborga86a83b2016-05-26 19:42:56 +00007380 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7381 // instantiation declarations for most purposes.
7382 bool DLLImportExplicitInstantiationDef = false;
7383 if (TSK == TSK_ExplicitInstantiationDefinition &&
7384 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7385 // Check for dllimport class template instantiation definitions.
7386 bool DLLImport =
7387 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7388 for (AttributeList *A = Attr; A; A = A->getNext()) {
7389 if (A->getKind() == AttributeList::AT_DLLImport)
7390 DLLImport = true;
7391 if (A->getKind() == AttributeList::AT_DLLExport) {
7392 // dllexport trumps dllimport here.
7393 DLLImport = false;
7394 break;
7395 }
7396 }
7397 if (DLLImport) {
7398 TSK = TSK_ExplicitInstantiationDeclaration;
7399 DLLImportExplicitInstantiationDef = true;
7400 }
7401 }
7402
Douglas Gregora1f49972009-05-13 00:25:59 +00007403 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007404 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007405 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007406
7407 // Check that the template argument list is well-formed for this
7408 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007409 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007410 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7411 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007412 return true;
7413
Douglas Gregora1f49972009-05-13 00:25:59 +00007414 // Find the class template specialization declaration that
7415 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007416 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007417 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007418 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007419
Abramo Bagnara8075c852010-06-12 07:44:57 +00007420 TemplateSpecializationKind PrevDecl_TSK
7421 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7422
Douglas Gregor54888652009-10-07 00:13:32 +00007423 // C++0x [temp.explicit]p2:
7424 // [...] An explicit instantiation shall appear in an enclosing
7425 // namespace of its template. [...]
7426 //
7427 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007428 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7429 SS.isSet()))
7430 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007431
Craig Topperc3ec1492014-05-26 06:22:03 +00007432 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007433
Abramo Bagnara8075c852010-06-12 07:44:57 +00007434 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007435 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007436 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007437 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007438 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007439 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007440 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007441
Abramo Bagnara8075c852010-06-12 07:44:57 +00007442 // Even though HasNoEffect == true means that this explicit instantiation
7443 // has no effect on semantics, we go on to put its syntax in the AST.
7444
7445 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7446 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007447 // Since the only prior class template specialization with these
7448 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007449 // declaration node as our own, updating the source location
7450 // for the template name to reflect our new declaration.
7451 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007452 Specialization = PrevDecl;
7453 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007454 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007455 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007456
7457 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7458 DLLImportExplicitInstantiationDef) {
7459 // The new specialization might add a dllimport attribute.
7460 HasNoEffect = false;
7461 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007462 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007463
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007464 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007465 // Create a new class template specialization declaration node for
7466 // this explicit specialization.
7467 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007468 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007469 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007470 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007471 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007472 Converted.data(),
7473 Converted.size(),
7474 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007475 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007476
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007477 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007478 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007479 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007480 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007481 }
7482
7483 // Build the fully-sugared type for this explicit instantiation as
7484 // the user wrote in the explicit instantiation itself. This means
7485 // that we'll pretty-print the type retrieved from the
7486 // specialization's declaration the way that the user actually wrote
7487 // the explicit instantiation, rather than formatting the name based
7488 // on the "canonical" representation used to store the template
7489 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007490 TypeSourceInfo *WrittenTy
7491 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7492 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007493 Context.getTypeDeclType(Specialization));
7494 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007495
Abramo Bagnara8075c852010-06-12 07:44:57 +00007496 // Set source locations for keywords.
7497 Specialization->setExternLoc(ExternLoc);
7498 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007499 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007500
Rafael Espindola0b062072012-01-03 06:04:21 +00007501 if (Attr)
7502 ProcessDeclAttributeList(S, Specialization, Attr);
7503
Abramo Bagnara8075c852010-06-12 07:44:57 +00007504 // Add the explicit instantiation into its lexical context. However,
7505 // since explicit instantiations are never found by name lookup, we
7506 // just put it into the declaration context directly.
7507 Specialization->setLexicalDeclContext(CurContext);
7508 CurContext->addDecl(Specialization);
7509
7510 // Syntax is now OK, so return if it has no other effect on semantics.
7511 if (HasNoEffect) {
7512 // Set the template specialization kind.
7513 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007514 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007515 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007516
7517 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007518 // A definition of a class template or class member template
7519 // shall be in scope at the point of the explicit instantiation of
7520 // the class template or class member template.
7521 //
7522 // This check comes when we actually try to perform the
7523 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007524 ClassTemplateSpecializationDecl *Def
7525 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007526 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007527 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007528 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007529 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007530 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007531 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7532 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007533
Douglas Gregor1d957a32009-10-27 18:42:08 +00007534 // Instantiate the members of this class template specialization.
7535 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007536 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007537 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007538 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007539 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7540 // TSK_ExplicitInstantiationDefinition
7541 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007542 (TSK == TSK_ExplicitInstantiationDefinition ||
7543 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007544 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007545 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007546
Hans Wennborgc0875502015-06-09 00:39:05 +00007547 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7548 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7549 // In the MS ABI, an explicit instantiation definition can add a dll
7550 // attribute to a template with a previous instantiation declaration.
7551 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007552 auto *A = cast<InheritableAttr>(
7553 getDLLAttr(Specialization)->clone(getASTContext()));
7554 A->setInherited(true);
7555 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007556
7557 // We reject explicit instantiations in class scope, so there should
7558 // never be any delayed exported classes to worry about.
7559 assert(DelayedDllExportClasses.empty() &&
7560 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007561 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007562 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007563
7564 // Propagate attribute to base class templates.
7565 for (auto &B : Def->bases()) {
7566 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7567 B.getType()->getAsCXXRecordDecl()))
7568 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7569 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007570 }
7571 }
7572
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007573 // Set the template specialization kind. Make sure it is set before
7574 // instantiating the members which will trigger ASTConsumer callbacks.
7575 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007576 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007577 } else {
7578
7579 // Set the template specialization kind.
7580 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007581 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007582
John McCall48871652010-08-21 09:40:31 +00007583 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007584}
7585
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007586// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007587DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007588Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007589 SourceLocation ExternLoc,
7590 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007591 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007592 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007593 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007594 IdentifierInfo *Name,
7595 SourceLocation NameLoc,
7596 AttributeList *Attr) {
7597
Douglas Gregord6ab8742009-05-28 23:31:59 +00007598 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007599 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007600 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007601 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007602 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007603 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007604 SourceLocation(), false, TypeResult(),
7605 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007606 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7607
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007608 if (!TagD)
7609 return true;
7610
John McCall48871652010-08-21 09:40:31 +00007611 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007612 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007613
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007614 if (Tag->isInvalidDecl())
7615 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007616
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007617 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7618 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7619 if (!Pattern) {
7620 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7621 << Context.getTypeDeclType(Record);
7622 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7623 return true;
7624 }
7625
Douglas Gregore47f5a72009-10-14 23:41:34 +00007626 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007627 // If the explicit instantiation is for a class or member class, the
7628 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007629 // simple-template-id.
7630 //
7631 // C++98 has the same restriction, just worded differently.
7632 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007633 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007634 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007635
Douglas Gregore47f5a72009-10-14 23:41:34 +00007636 // C++0x [temp.explicit]p2:
7637 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007638 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007639 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007640 TemplateSpecializationKind TSK
7641 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7642 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007643
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007644 // C++0x [temp.explicit]p2:
7645 // [...] An explicit instantiation shall appear in an enclosing
7646 // namespace of its template. [...]
7647 //
7648 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007649 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007650
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007651 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007652 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007653 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007654 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007655 PrevDecl = Record;
7656 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007657 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007658 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007659 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007660 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007661 PrevDecl,
7662 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007663 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007664 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007665 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007666 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007667 return TagD;
7668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007669
Douglas Gregor12e49d32009-10-15 22:53:21 +00007670 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007671 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007672 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007673 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007674 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007675 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007677 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007678 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007679 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7680 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007681 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7682 << Pattern;
7683 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007684 } else {
7685 if (InstantiateClass(NameLoc, Record, Def,
7686 getTemplateInstantiationArgs(Record),
7687 TSK))
7688 return true;
7689
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007690 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007691 if (!RecordDef)
7692 return true;
7693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007694 }
7695
Douglas Gregor1d957a32009-10-27 18:42:08 +00007696 // Instantiate all of the members of the class.
7697 InstantiateClassMembers(NameLoc, RecordDef,
7698 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007699
Douglas Gregor88d292c2010-05-13 16:44:06 +00007700 if (TSK == TSK_ExplicitInstantiationDefinition)
7701 MarkVTableUsed(NameLoc, RecordDef, true);
7702
Mike Stump87c57ac2009-05-16 07:39:55 +00007703 // FIXME: We don't have any representation for explicit instantiations of
7704 // member classes. Such a representation is not needed for compilation, but it
7705 // should be available for clients that want to see all of the declarations in
7706 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007707 return TagD;
7708}
7709
John McCallfaf5fb42010-08-26 23:41:50 +00007710DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7711 SourceLocation ExternLoc,
7712 SourceLocation TemplateLoc,
7713 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007714 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007715 // TODO: check if/when DNInfo should replace Name.
7716 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7717 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007718 if (!Name) {
7719 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007720 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007721 diag::err_explicit_instantiation_requires_name)
7722 << D.getDeclSpec().getSourceRange()
7723 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007724
Douglas Gregor450f00842009-09-25 18:43:00 +00007725 return true;
7726 }
7727
7728 // The scope passed in may not be a decl scope. Zip up the scope tree until
7729 // we find one that is.
7730 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7731 (S->getFlags() & Scope::TemplateParamScope) != 0)
7732 S = S->getParent();
7733
7734 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007735 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7736 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007737 if (R.isNull())
7738 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007739
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007740 // C++ [dcl.stc]p1:
7741 // A storage-class-specifier shall not be specified in [...] an explicit
7742 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007743 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007744 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7745 << Name;
7746 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007747 } else if (D.getDeclSpec().getStorageClassSpec()
7748 != DeclSpec::SCS_unspecified) {
7749 // Complain about then remove the storage class specifier.
7750 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7751 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7752
7753 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007754 }
7755
Douglas Gregor3c74d412009-10-14 20:14:33 +00007756 // C++0x [temp.explicit]p1:
7757 // [...] An explicit instantiation of a function template shall not use the
7758 // inline or constexpr specifiers.
7759 // Presumably, this also applies to member functions of class templates as
7760 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007761 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007762 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007763 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007764 diag::err_explicit_instantiation_inline :
7765 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007766 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007767 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007768 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7769 // not already specified.
7770 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7771 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007772
Nathan Wilsonde498452016-02-08 05:34:00 +00007773 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7774 // applied only to the definition of a function template or variable template,
7775 // declared in namespace scope.
7776 if (D.getDeclSpec().isConceptSpecified()) {
7777 Diag(D.getDeclSpec().getConceptSpecLoc(),
7778 diag::err_concept_specified_specialization) << 0;
7779 return true;
7780 }
7781
Douglas Gregore47f5a72009-10-14 23:41:34 +00007782 // C++0x [temp.explicit]p2:
7783 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007784 // definition and an explicit instantiation declaration. An explicit
7785 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007786 TemplateSpecializationKind TSK
7787 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7788 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007789
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007790 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007791 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007792
7793 if (!R->isFunctionType()) {
7794 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007795 // A [...] static data member of a class template can be explicitly
7796 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007797 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007798 // C++1y [temp.explicit]p1:
7799 // A [...] variable [...] template specialization can be explicitly
7800 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007801 if (Previous.isAmbiguous())
7802 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803
John McCall67c00872009-12-02 08:25:40 +00007804 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007805 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007806
Larisse Voufo39a1e502013-08-06 01:03:05 +00007807 if (!PrevTemplate) {
7808 if (!Prev || !Prev->isStaticDataMember()) {
7809 // We expect to see a data data member here.
7810 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7811 << Name;
7812 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7813 P != PEnd; ++P)
7814 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7815 return true;
7816 }
7817
7818 if (!Prev->getInstantiatedFromStaticDataMember()) {
7819 // FIXME: Check for explicit specialization?
7820 Diag(D.getIdentifierLoc(),
7821 diag::err_explicit_instantiation_data_member_not_instantiated)
7822 << Prev;
7823 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7824 // FIXME: Can we provide a note showing where this was declared?
7825 return true;
7826 }
7827 } else {
7828 // Explicitly instantiate a variable template.
7829
7830 // C++1y [dcl.spec.auto]p6:
7831 // ... A program that uses auto or decltype(auto) in a context not
7832 // explicitly allowed in this section is ill-formed.
7833 //
7834 // This includes auto-typed variable template instantiations.
7835 if (R->isUndeducedType()) {
7836 Diag(T->getTypeLoc().getLocStart(),
7837 diag::err_auto_not_allowed_var_inst);
7838 return true;
7839 }
7840
Richard Smithef985ac2013-09-18 02:10:12 +00007841 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7842 // C++1y [temp.explicit]p3:
7843 // If the explicit instantiation is for a variable, the unqualified-id
7844 // in the declaration shall be a template-id.
7845 Diag(D.getIdentifierLoc(),
7846 diag::err_explicit_instantiation_without_template_id)
7847 << PrevTemplate;
7848 Diag(PrevTemplate->getLocation(),
7849 diag::note_explicit_instantiation_here);
7850 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007851 }
7852
Nathan Wilson83839122016-04-09 02:55:27 +00007853 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7854 // explicit instantiation (14.8.2) [...] of a concept definition.
7855 if (PrevTemplate->isConcept()) {
7856 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7857 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7858 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7859 return true;
7860 }
7861
Richard Smithef985ac2013-09-18 02:10:12 +00007862 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007863 TemplateArgumentListInfo TemplateArgs =
7864 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007865
Larisse Voufo39a1e502013-08-06 01:03:05 +00007866 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7867 D.getIdentifierLoc(), TemplateArgs);
7868 if (Res.isInvalid())
7869 return true;
7870
7871 // Ignore access control bits, we don't need them for redeclaration
7872 // checking.
7873 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007875
Douglas Gregore47f5a72009-10-14 23:41:34 +00007876 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007877 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007878 // or a static data member of a class template specialization, the name of
7879 // the class template specialization in the qualified-id for the member
7880 // name shall be a simple-template-id.
7881 //
7882 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007883 //
Richard Smith5977d872013-09-18 21:55:14 +00007884 // This does not apply to variable template specializations, where the
7885 // template-id is in the unqualified-id instead.
7886 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007887 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007888 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007889 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007890
Douglas Gregore47f5a72009-10-14 23:41:34 +00007891 // Check the scope of this explicit instantiation.
7892 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007893
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007894 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007895 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7896 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007897 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007898 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007899 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007900 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007901
Larisse Voufo39a1e502013-08-06 01:03:05 +00007902 if (!HasNoEffect) {
7903 // Instantiate static data member or variable template.
7904
7905 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7906 if (PrevTemplate) {
7907 // Merge attributes.
7908 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7909 ProcessDeclAttributeList(S, Prev, Attr);
7910 }
7911 if (TSK == TSK_ExplicitInstantiationDefinition)
7912 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7913 }
7914
7915 // Check the new variable specialization against the parsed input.
7916 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7917 Diag(T->getTypeLoc().getLocStart(),
7918 diag::err_invalid_var_template_spec_type)
7919 << 0 << PrevTemplate << R << Prev->getType();
7920 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7921 << 2 << PrevTemplate->getDeclName();
7922 return true;
7923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007924
Douglas Gregor450f00842009-09-25 18:43:00 +00007925 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007926 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007928
7929 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007930 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007931 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007932 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007933 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007934 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007935 HasExplicitTemplateArgs = true;
7936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007937
Douglas Gregor450f00842009-09-25 18:43:00 +00007938 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007939 // A [...] function [...] can be explicitly instantiated from its template.
7940 // A member function [...] of a class template can be explicitly
7941 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007942 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007943 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007944 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007945 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7946 P != PEnd; ++P) {
7947 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007948 if (!HasExplicitTemplateArgs) {
7949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007950 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7951 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007952 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007953
John McCall58cc69d2010-01-27 01:50:18 +00007954 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007955 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7956 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007957 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007958 }
7959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960
Douglas Gregor450f00842009-09-25 18:43:00 +00007961 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7962 if (!FunTmpl)
7963 continue;
7964
Larisse Voufo98b20f12013-07-19 23:00:19 +00007965 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007966 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007967 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007968 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007969 (HasExplicitTemplateArgs ? &TemplateArgs
7970 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007971 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007972 // Keep track of almost-matches.
7973 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00007974 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007975 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007976 (void)TDK;
7977 continue;
7978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007979
John McCall58cc69d2010-01-27 01:50:18 +00007980 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982
Douglas Gregor450f00842009-09-25 18:43:00 +00007983 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007984 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007985 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007986 D.getIdentifierLoc(),
7987 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7988 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7989 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007990
John McCall58cc69d2010-01-27 01:50:18 +00007991 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007992 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007993
7994 // Ignore access control bits, we don't need them for redeclaration checking.
7995 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007996
Alexey Bataev73983912014-11-06 10:10:50 +00007997 // C++11 [except.spec]p4
7998 // In an explicit instantiation an exception-specification may be specified,
7999 // but is not required.
8000 // If an exception-specification is specified in an explicit instantiation
8001 // directive, it shall be compatible with the exception-specifications of
8002 // other declarations of that function.
8003 if (auto *FPT = R->getAs<FunctionProtoType>())
8004 if (FPT->hasExceptionSpec()) {
8005 unsigned DiagID =
8006 diag::err_mismatched_exception_spec_explicit_instantiation;
8007 if (getLangOpts().MicrosoftExt)
8008 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8009 bool Result = CheckEquivalentExceptionSpec(
8010 PDiag(DiagID) << Specialization->getType(),
8011 PDiag(diag::note_explicit_instantiation_here),
8012 Specialization->getType()->getAs<FunctionProtoType>(),
8013 Specialization->getLocation(), FPT, D.getLocStart());
8014 // In Microsoft mode, mismatching exception specifications just cause a
8015 // warning.
8016 if (!getLangOpts().MicrosoftExt && Result)
8017 return true;
8018 }
8019
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008020 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008021 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008022 diag::err_explicit_instantiation_member_function_not_instantiated)
8023 << Specialization
8024 << (Specialization->getTemplateSpecializationKind() ==
8025 TSK_ExplicitSpecialization);
8026 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8027 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008028 }
8029
Douglas Gregorec9fd132012-01-14 16:38:05 +00008030 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008031 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8032 PrevDecl = Specialization;
8033
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008034 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008035 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008036 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037 PrevDecl,
8038 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008039 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008040 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008041 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008042
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008043 // FIXME: We may still want to build some representation of this
8044 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008045 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008046 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008047 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008048
8049 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008050 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8051 if (Attr)
8052 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008053
Richard Smitheb36ddf2014-04-24 22:45:46 +00008054 if (Specialization->isDefined()) {
8055 // Let the ASTConsumer know that this function has been explicitly
8056 // instantiated now, and its linkage might have changed.
8057 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8058 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008059 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008060
Douglas Gregore47f5a72009-10-14 23:41:34 +00008061 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008062 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008063 // or a static data member of a class template specialization, the name of
8064 // the class template specialization in the qualified-id for the member
8065 // name shall be a simple-template-id.
8066 //
8067 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008068 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008069 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008070 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008071 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008072 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008073 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008074 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008075
Nathan Wilson83839122016-04-09 02:55:27 +00008076 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8077 // explicit instantiation (14.8.2) [...] of a concept definition.
8078 if (FunTmpl && FunTmpl->isConcept() &&
8079 !D.getDeclSpec().isConceptSpecified()) {
8080 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8081 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8082 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8083 return true;
8084 }
8085
Douglas Gregore47f5a72009-10-14 23:41:34 +00008086 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008087 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008088 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008089 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008090 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008091
Douglas Gregor450f00842009-09-25 18:43:00 +00008092 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008093 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008094}
8095
John McCallfaf5fb42010-08-26 23:41:50 +00008096TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008097Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8098 const CXXScopeSpec &SS, IdentifierInfo *Name,
8099 SourceLocation TagLoc, SourceLocation NameLoc) {
8100 // This has to hold, because SS is expected to be defined.
8101 assert(Name && "Expected a name in a dependent tag");
8102
Aaron Ballman4a979672014-01-03 13:56:08 +00008103 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008104 if (!NNS)
8105 return true;
8106
Abramo Bagnara6150c882010-05-11 21:36:43 +00008107 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008108
Douglas Gregorba41d012010-04-24 16:38:41 +00008109 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8110 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008111 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008112 return true;
8113 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008114
Douglas Gregore7c20652011-03-02 00:47:37 +00008115 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008116 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008117 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8118
8119 // Create type-source location information for this type.
8120 TypeLocBuilder TLB;
8121 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008122 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008123 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8124 TL.setNameLoc(NameLoc);
8125 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008126}
8127
John McCallfaf5fb42010-08-26 23:41:50 +00008128TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008129Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8130 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008131 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008132 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008133 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008134
Richard Smith0bf8a4922011-10-18 20:49:44 +00008135 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8136 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008137 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008138 diag::warn_cxx98_compat_typename_outside_of_template :
8139 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008140 << FixItHint::CreateRemoval(TypenameLoc);
8141
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008142 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008143 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8144 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008145 if (T.isNull())
8146 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008147
8148 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8149 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008150 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008151 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008152 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008153 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008154 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008155 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008156 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008157 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008158 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008160
John McCallba7bf592010-08-24 05:47:05 +00008161 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008162}
8163
John McCallfaf5fb42010-08-26 23:41:50 +00008164TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008165Sema::ActOnTypenameType(Scope *S,
8166 SourceLocation TypenameLoc,
8167 const CXXScopeSpec &SS,
8168 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008169 TemplateTy TemplateIn,
8170 SourceLocation TemplateNameLoc,
8171 SourceLocation LAngleLoc,
8172 ASTTemplateArgsPtr TemplateArgsIn,
8173 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008174 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8175 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008176 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008177 diag::warn_cxx98_compat_typename_outside_of_template :
8178 diag::ext_typename_outside_of_template)
8179 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008180
8181 // Translate the parser's template argument list in our AST format.
8182 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8183 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8184
8185 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008186 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8187 // Construct a dependent template specialization type.
8188 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008189 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008190 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8191 DTN->getQualifier(),
8192 DTN->getIdentifier(),
8193 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008194
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008195 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008196 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008197 DependentTemplateSpecializationTypeLoc SpecTL
8198 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008199 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8200 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008201 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008202 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008203 SpecTL.setLAngleLoc(LAngleLoc);
8204 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008205 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8206 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008207 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008208 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008209
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008210 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8211 if (T.isNull())
8212 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008213
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008214 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008215 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008216 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008217 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008218 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8219 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008220 SpecTL.setLAngleLoc(LAngleLoc);
8221 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008222 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8223 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8224
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008225 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8226 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008227 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008228 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8229
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008230 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8231 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008232}
8233
Douglas Gregorb09518c2011-02-27 22:46:49 +00008234
Richard Smith6f8d2c62012-05-09 05:17:00 +00008235/// Determine whether this failed name lookup should be treated as being
8236/// disabled by a usage of std::enable_if.
8237static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8238 SourceRange &CondRange) {
8239 // We must be looking for a ::type...
8240 if (!II.isStr("type"))
8241 return false;
8242
8243 // ... within an explicitly-written template specialization...
8244 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8245 return false;
8246 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008247 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8248 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8249 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008250 return false;
8251 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008252 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008253
8254 // ... which names a complete class template declaration...
8255 const TemplateDecl *EnableIfDecl =
8256 EnableIfTST->getTemplateName().getAsTemplateDecl();
8257 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8258 return false;
8259
8260 // ... called "enable_if".
8261 const IdentifierInfo *EnableIfII =
8262 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8263 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8264 return false;
8265
8266 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008267 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008268 return true;
8269}
8270
Douglas Gregor333489b2009-03-27 23:10:48 +00008271/// \brief Build the type that describes a C++ typename specifier,
8272/// e.g., "typename T::type".
8273QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008274Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8275 SourceLocation KeywordLoc,
8276 NestedNameSpecifierLoc QualifierLoc,
8277 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008278 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008279 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008280 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008281
John McCall0b66eb32010-05-01 00:40:08 +00008282 DeclContext *Ctx = computeDeclContext(SS);
8283 if (!Ctx) {
8284 // If the nested-name-specifier is dependent and couldn't be
8285 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008286 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8287 return Context.getDependentNameType(Keyword,
8288 QualifierLoc.getNestedNameSpecifier(),
8289 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008290 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008291
John McCall0b66eb32010-05-01 00:40:08 +00008292 // If the nested-name-specifier refers to the current instantiation,
8293 // the "typename" keyword itself is superfluous. In C++03, the
8294 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8295 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008296 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008297
John McCall0b66eb32010-05-01 00:40:08 +00008298 if (RequireCompleteDeclContext(SS, Ctx))
8299 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008300
8301 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008302 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008303 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008304 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008305 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008306 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008307 case LookupResult::NotFound: {
8308 // If we're looking up 'type' within a template named 'enable_if', produce
8309 // a more specific diagnostic.
8310 SourceRange CondRange;
8311 if (isEnableIf(QualifierLoc, II, CondRange)) {
8312 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8313 << Ctx << CondRange;
8314 return QualType();
8315 }
8316
Douglas Gregore40876a2009-10-13 21:16:44 +00008317 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008318 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008319 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008320
8321 case LookupResult::FoundUnresolvedValue: {
8322 // We found a using declaration that is a value. Most likely, the using
8323 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008324 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008325 IILoc);
8326 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8327 << Name << Ctx << FullRange;
8328 if (UnresolvedUsingValueDecl *Using
8329 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008330 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008331 Diag(Loc, diag::note_using_value_decl_missing_typename)
8332 << FixItHint::CreateInsertion(Loc, "typename ");
8333 }
8334 }
8335 // Fall through to create a dependent typename type, from which we can recover
8336 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008337
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008338 case LookupResult::NotFoundInCurrentInstantiation:
8339 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008340 return Context.getDependentNameType(Keyword,
8341 QualifierLoc.getNestedNameSpecifier(),
8342 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008343
8344 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008345 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008346 // We found a type. Build an ElaboratedType, since the
8347 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008348 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008349 return Context.getElaboratedType(ETK_Typename,
8350 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008351 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008352 }
8353
8354 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008355 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008356 break;
8357
8358 case LookupResult::FoundOverloaded:
8359 DiagID = diag::err_typename_nested_not_type;
8360 Referenced = *Result.begin();
8361 break;
8362
John McCall6538c932009-10-10 05:48:19 +00008363 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008364 return QualType();
8365 }
8366
8367 // If we get here, it's because name lookup did not find a
8368 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008369 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008370 IILoc);
8371 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008372 if (Referenced)
8373 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8374 << Name;
8375 return QualType();
8376}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008377
8378namespace {
8379 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008380 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008381 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008382 SourceLocation Loc;
8383 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008384
Douglas Gregor15acfb92009-08-06 16:20:37 +00008385 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008386 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008387
Mike Stump11289f42009-09-09 15:08:12 +00008388 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008389 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008390 DeclarationName Entity)
8391 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008392 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008393
8394 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008395 /// transformed.
8396 ///
8397 /// For the purposes of type reconstruction, a type has already been
8398 /// transformed if it is NULL or if it is not dependent.
8399 bool AlreadyTransformed(QualType T) {
8400 return T.isNull() || !T->isDependentType();
8401 }
Mike Stump11289f42009-09-09 15:08:12 +00008402
8403 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008404 /// rebuilt.
8405 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008406
Douglas Gregor15acfb92009-08-06 16:20:37 +00008407 /// \brief Returns the name of the entity whose type is being rebuilt.
8408 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008409
Douglas Gregoref6ab412009-10-27 06:26:26 +00008410 /// \brief Sets the "base" location and entity when that
8411 /// information is known based on another transformation.
8412 void setBase(SourceLocation Loc, DeclarationName Entity) {
8413 this->Loc = Loc;
8414 this->Entity = Entity;
8415 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008416
8417 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8418 // Lambdas never need to be transformed.
8419 return E;
8420 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008421 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008422} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008423
Douglas Gregor15acfb92009-08-06 16:20:37 +00008424/// \brief Rebuilds a type within the context of the current instantiation.
8425///
Mike Stump11289f42009-09-09 15:08:12 +00008426/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008427/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008428/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008429/// partial specialization thereof). This routine will rebuild that type now
8430/// that we have entered the declarator's scope, which may produce different
8431/// canonical types, e.g.,
8432///
8433/// \code
8434/// template<typename T>
8435/// struct X {
8436/// typedef T* pointer;
8437/// pointer data();
8438/// };
8439///
8440/// template<typename T>
8441/// typename X<T>::pointer X<T>::data() { ... }
8442/// \endcode
8443///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008444/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008445/// since we do not know that we can look into X<T> when we parsed the type.
8446/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008447/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008448/// as the canonical type of T*, allowing the return types of the out-of-line
8449/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008450TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8451 SourceLocation Loc,
8452 DeclarationName Name) {
8453 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008454 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008455
Douglas Gregor15acfb92009-08-06 16:20:37 +00008456 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8457 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008458}
Douglas Gregorbe999392009-09-15 16:23:51 +00008459
John McCalldadc5752010-08-24 06:29:42 +00008460ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008461 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8462 DeclarationName());
8463 return Rebuilder.TransformExpr(E);
8464}
8465
John McCall99b2fe52010-04-29 23:50:39 +00008466bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008467 if (SS.isInvalid())
8468 return true;
John McCall2408e322010-04-27 00:57:59 +00008469
Douglas Gregor10176412011-02-25 16:07:42 +00008470 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008471 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8472 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008473 NestedNameSpecifierLoc Rebuilt
8474 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8475 if (!Rebuilt)
8476 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008477
Douglas Gregor10176412011-02-25 16:07:42 +00008478 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008479 return false;
John McCall2408e322010-04-27 00:57:59 +00008480}
8481
Douglas Gregor041b0842011-10-14 15:31:12 +00008482/// \brief Rebuild the template parameters now that we know we're in a current
8483/// instantiation.
8484bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8485 TemplateParameterList *Params) {
8486 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8487 Decl *Param = Params->getParam(I);
8488
8489 // There is nothing to rebuild in a type parameter.
8490 if (isa<TemplateTypeParmDecl>(Param))
8491 continue;
8492
8493 // Rebuild the template parameter list of a template template parameter.
8494 if (TemplateTemplateParmDecl *TTP
8495 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8496 if (RebuildTemplateParamsInCurrentInstantiation(
8497 TTP->getTemplateParameters()))
8498 return true;
8499
8500 continue;
8501 }
8502
8503 // Rebuild the type of a non-type template parameter.
8504 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8505 TypeSourceInfo *NewTSI
8506 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8507 NTTP->getLocation(),
8508 NTTP->getDeclName());
8509 if (!NewTSI)
8510 return true;
8511
8512 if (NewTSI != NTTP->getTypeSourceInfo()) {
8513 NTTP->setTypeSourceInfo(NewTSI);
8514 NTTP->setType(NewTSI->getType());
8515 }
8516 }
8517
8518 return false;
8519}
8520
Douglas Gregorbe999392009-09-15 16:23:51 +00008521/// \brief Produces a formatted string that describes the binding of
8522/// template parameters to template arguments.
8523std::string
8524Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8525 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008526 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008527}
8528
8529std::string
8530Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8531 const TemplateArgument *Args,
8532 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008533 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008534 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008535
Douglas Gregore62e6a02009-11-11 19:13:48 +00008536 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008537 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008538
Douglas Gregorbe999392009-09-15 16:23:51 +00008539 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008540 if (I >= NumArgs)
8541 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008542
Douglas Gregorbe999392009-09-15 16:23:51 +00008543 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008544 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008545 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008546 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008547
Douglas Gregorbe999392009-09-15 16:23:51 +00008548 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008549 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008550 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008551 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008553
Douglas Gregor0192c232010-12-20 16:52:59 +00008554 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008555 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008556 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008557
8558 Out << ']';
8559 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008560}
Francois Pichet1c229c02011-04-22 22:18:13 +00008561
Richard Smithe40f2ba2013-08-07 21:41:30 +00008562void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8563 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008564 if (!FD)
8565 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008566
8567 LateParsedTemplate *LPT = new LateParsedTemplate;
8568
8569 // Take tokens to avoid allocations
8570 LPT->Toks.swap(Toks);
8571 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008572 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008573
8574 FD->setLateTemplateParsed(true);
8575}
8576
8577void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8578 if (!FD)
8579 return;
8580 FD->setLateTemplateParsed(false);
8581}
Francois Pichet1c229c02011-04-22 22:18:13 +00008582
8583bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8584 DeclContext *DC = CurContext;
8585
8586 while (DC) {
8587 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8588 const FunctionDecl *FD = RD->isLocalClass();
8589 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8590 } else if (DC->isTranslationUnit() || DC->isNamespace())
8591 return false;
8592
8593 DC = DC->getParent();
8594 }
8595 return false;
8596}
Richard Smith6739a102016-05-05 00:56:12 +00008597
8598/// \brief Walk the path from which a declaration was instantiated, and check
8599/// that every explicit specialization along that path is visible. This enforces
8600/// C++ [temp.expl.spec]/6:
8601///
8602/// If a template, a member template or a member of a class template is
8603/// explicitly specialized then that specialization shall be declared before
8604/// the first use of that specialization that would cause an implicit
8605/// instantiation to take place, in every translation unit in which such a
8606/// use occurs; no diagnostic is required.
8607///
8608/// and also C++ [temp.class.spec]/1:
8609///
8610/// A partial specialization shall be declared before the first use of a
8611/// class template specialization that would make use of the partial
8612/// specialization as the result of an implicit or explicit instantiation
8613/// in every translation unit in which such a use occurs; no diagnostic is
8614/// required.
8615class ExplicitSpecializationVisibilityChecker {
8616 Sema &S;
8617 SourceLocation Loc;
8618 llvm::SmallVector<Module *, 8> Modules;
8619
8620public:
8621 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8622 : S(S), Loc(Loc) {}
8623
8624 void check(NamedDecl *ND) {
8625 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8626 return checkImpl(FD);
8627 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8628 return checkImpl(RD);
8629 if (auto *VD = dyn_cast<VarDecl>(ND))
8630 return checkImpl(VD);
8631 if (auto *ED = dyn_cast<EnumDecl>(ND))
8632 return checkImpl(ED);
8633 }
8634
8635private:
8636 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8637 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8638 : Sema::MissingImportKind::ExplicitSpecialization;
8639 const bool Recover = true;
8640
8641 // If we got a custom set of modules (because only a subset of the
8642 // declarations are interesting), use them, otherwise let
8643 // diagnoseMissingImport intelligently pick some.
8644 if (Modules.empty())
8645 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8646 else
8647 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8648 }
8649
8650 // Check a specific declaration. There are three problematic cases:
8651 //
8652 // 1) The declaration is an explicit specialization of a template
8653 // specialization.
8654 // 2) The declaration is an explicit specialization of a member of an
8655 // templated class.
8656 // 3) The declaration is an instantiation of a template, and that template
8657 // is an explicit specialization of a member of a templated class.
8658 //
8659 // We don't need to go any deeper than that, as the instantiation of the
8660 // surrounding class / etc is not triggered by whatever triggered this
8661 // instantiation, and thus should be checked elsewhere.
8662 template<typename SpecDecl>
8663 void checkImpl(SpecDecl *Spec) {
8664 bool IsHiddenExplicitSpecialization = false;
8665 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8666 IsHiddenExplicitSpecialization =
8667 Spec->getMemberSpecializationInfo()
8668 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8669 : !S.hasVisibleDeclaration(Spec);
8670 } else {
8671 checkInstantiated(Spec);
8672 }
8673
8674 if (IsHiddenExplicitSpecialization)
8675 diagnose(Spec->getMostRecentDecl(), false);
8676 }
8677
8678 void checkInstantiated(FunctionDecl *FD) {
8679 if (auto *TD = FD->getPrimaryTemplate())
8680 checkTemplate(TD);
8681 }
8682
8683 void checkInstantiated(CXXRecordDecl *RD) {
8684 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8685 if (!SD)
8686 return;
8687
8688 auto From = SD->getSpecializedTemplateOrPartial();
8689 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8690 checkTemplate(TD);
8691 else if (auto *TD =
8692 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8693 if (!S.hasVisibleDeclaration(TD))
8694 diagnose(TD, true);
8695 checkTemplate(TD);
8696 }
8697 }
8698
8699 void checkInstantiated(VarDecl *RD) {
8700 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8701 if (!SD)
8702 return;
8703
8704 auto From = SD->getSpecializedTemplateOrPartial();
8705 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8706 checkTemplate(TD);
8707 else if (auto *TD =
8708 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8709 if (!S.hasVisibleDeclaration(TD))
8710 diagnose(TD, true);
8711 checkTemplate(TD);
8712 }
8713 }
8714
8715 void checkInstantiated(EnumDecl *FD) {}
8716
8717 template<typename TemplDecl>
8718 void checkTemplate(TemplDecl *TD) {
8719 if (TD->isMemberSpecialization()) {
8720 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8721 diagnose(TD->getMostRecentDecl(), false);
8722 }
8723 }
8724};
8725
8726void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8727 if (!getLangOpts().Modules)
8728 return;
8729
8730 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8731}
8732
8733/// \brief Check whether a template partial specialization that we've discovered
8734/// is hidden, and produce suitable diagnostics if so.
8735void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8736 NamedDecl *Spec) {
8737 llvm::SmallVector<Module *, 8> Modules;
8738 if (!hasVisibleDeclaration(Spec, &Modules))
8739 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8740 MissingImportKind::PartialSpecialization,
8741 /*Recover*/true);
8742}