blob: 3b85b98abdd369c21c3684babd40ba3b0f114c6d [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
John McCallcd4b4772009-12-02 03:53:29 +0000417 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000418 isa<CXXMethodDecl>(DC) &&
419 cast<CXXMethodDecl>(DC)->isInstance()) {
420 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000421
John McCalle66edc12009-11-24 19:00:30 +0000422 // Since the 'this' expression is synthesized, we don't need to
423 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000424 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000425
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000426 return CXXDependentScopeMemberExpr::Create(
427 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
428 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
429 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000430 }
431
Abramo Bagnara7945c982012-01-27 09:46:47 +0000432 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000433}
434
John McCalldadc5752010-08-24 06:29:42 +0000435ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000436Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000437 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000438 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000439 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return DependentScopeDeclRefExpr::Create(
441 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
442 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000443}
444
Douglas Gregor5101c242008-12-05 18:15:24 +0000445/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
446/// that the template parameter 'PrevDecl' is being shadowed by a new
447/// declaration at location Loc. Returns true to indicate that this is
448/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000449void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000450 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000451
452 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000453 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000454 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000455
456 // C++ [temp.local]p4:
457 // A template-parameter shall not be redeclared within its
458 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000459 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000460 << cast<NamedDecl>(PrevDecl)->getDeclName();
461 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000462}
463
Douglas Gregor463421d2009-03-03 04:44:36 +0000464/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000465/// the parameter D to reference the templated declaration and return a pointer
466/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000467TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
468 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
469 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000470 return Temp;
471 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000472 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000473}
474
Douglas Gregoreb29d182011-01-05 17:40:24 +0000475ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
476 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000478 "Only template template arguments can be pack expansions here");
479 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
480 "Template template argument pack expansion without packs");
481 ParsedTemplateArgument Result(*this);
482 Result.EllipsisLoc = EllipsisLoc;
483 return Result;
484}
485
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000486static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
487 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000489 switch (Arg.getKind()) {
490 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000491 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000492 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000494 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000495 return TemplateArgumentLoc(TemplateArgument(T), DI);
496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000498 case ParsedTemplateArgument::NonType: {
499 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
500 return TemplateArgumentLoc(TemplateArgument(E), E);
501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000503 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000504 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000505 TemplateArgument TArg;
506 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000507 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000508 else
509 TArg = Template;
510 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000511 Arg.getScopeSpec().getWithLocInContext(
512 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000513 Arg.getLocation(),
514 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000515 }
516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000517
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000518 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000519}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000520
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000521/// \brief Translates template arguments as provided by the parser
522/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000523void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
524 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000525 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000526 TemplateArgs.addArgument(translateTemplateArgument(*this,
527 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000528}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Richard Smithb80d5402013-06-25 22:21:36 +0000530static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
531 SourceLocation Loc,
532 IdentifierInfo *Name) {
533 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
534 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
535 if (PrevDecl && PrevDecl->isTemplateParameter())
536 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
537}
538
Douglas Gregor5101c242008-12-05 18:15:24 +0000539/// ActOnTypeParameter - Called when a C++ template type parameter
540/// (e.g., "typename T") has been parsed. Typename specifies whether
541/// the keyword "typename" was used to declare the type parameter
542/// (otherwise, "class" was used), and KeyLoc is the location of the
543/// "class" or "typename" keyword. ParamName is the name of the
544/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000545/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000546/// If the type parameter has a default argument, it will be added
547/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000548Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000549 SourceLocation EllipsisLoc,
550 SourceLocation KeyLoc,
551 IdentifierInfo *ParamName,
552 SourceLocation ParamNameLoc,
553 unsigned Depth, unsigned Position,
554 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000555 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000556 assert(S->isTemplateParamScope() &&
557 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000558
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000559 SourceLocation Loc = ParamNameLoc;
560 if (!ParamName)
561 Loc = KeyLoc;
562
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000563 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000564 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000565 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000566 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000567 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000568 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000569
570 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000571 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
572
Douglas Gregor5101c242008-12-05 18:15:24 +0000573 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000574 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000575 IdResolver.AddDecl(Param);
576 }
577
Douglas Gregorf5500772011-01-05 15:48:55 +0000578 // C++0x [temp.param]p9:
579 // A default template-argument may be specified for any kind of
580 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000581 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000582 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000583 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000584 }
585
Douglas Gregordc13ded2010-07-01 00:00:45 +0000586 // Handle the default argument, if provided.
587 if (DefaultArg) {
588 TypeSourceInfo *DefaultTInfo;
589 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregordc13ded2010-07-01 00:00:45 +0000591 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000593 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000595 UPPC_DefaultArgument))
596 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597
Douglas Gregordc13ded2010-07-01 00:00:45 +0000598 // Check the template argument itself.
599 if (CheckTemplateArgument(Param, DefaultTInfo)) {
600 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000601 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603
Richard Smith1469b912015-06-10 00:29:03 +0000604 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
John McCall48871652010-08-21 09:40:31 +0000607 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000608}
609
Douglas Gregor463421d2009-03-03 04:44:36 +0000610/// \brief Check that the type of a non-type template parameter is
611/// well-formed.
612///
613/// \returns the (possibly-promoted) parameter type if valid;
614/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000615QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000616Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000617 // We don't allow variably-modified types as the type of non-type template
618 // parameters.
619 if (T->isVariablyModifiedType()) {
620 Diag(Loc, diag::err_variably_modified_nontype_template_param)
621 << T;
622 return QualType();
623 }
624
Douglas Gregor463421d2009-03-03 04:44:36 +0000625 // C++ [temp.param]p4:
626 //
627 // A non-type template-parameter shall have one of the following
628 // (optionally cv-qualified) types:
629 //
630 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000631 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000632 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000633 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000634 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000635 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000636 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000637 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000638 // -- std::nullptr_t.
639 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000640 // If T is a dependent type, we can't do the check now, so we
641 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000642 T->isDependentType()) {
643 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
644 // are ignored when determining its type.
645 return T.getUnqualifiedType();
646 }
647
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 // C++ [temp.param]p8:
649 //
650 // A non-type template-parameter of type "array of T" or
651 // "function returning T" is adjusted to be of type "pointer to
652 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000653 else if (T->isArrayType() || T->isFunctionType())
654 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655
Douglas Gregor463421d2009-03-03 04:44:36 +0000656 Diag(Loc, diag::err_template_nontype_parm_bad_type)
657 << T;
658
659 return QualType();
660}
661
John McCall48871652010-08-21 09:40:31 +0000662Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
663 unsigned Depth,
664 unsigned Position,
665 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000666 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000667 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
668 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000669
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000670 assert(S->isTemplateParamScope() &&
671 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000672 bool Invalid = false;
673
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000674 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
675 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000676 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000677 Invalid = true;
678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679
Richard Smithb80d5402013-06-25 22:21:36 +0000680 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000681 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000682 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000683 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000684 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000685 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000687 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000688 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000689
Douglas Gregor5101c242008-12-05 18:15:24 +0000690 if (Invalid)
691 Param->setInvalidDecl();
692
Richard Smithb80d5402013-06-25 22:21:36 +0000693 if (ParamName) {
694 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
695 ParamName);
696
Douglas Gregor5101c242008-12-05 18:15:24 +0000697 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000698 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000699 IdResolver.AddDecl(Param);
700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701
Douglas Gregorf5500772011-01-05 15:48:55 +0000702 // C++0x [temp.param]p9:
703 // A default template-argument may be specified for any kind of
704 // template-parameter that is not a template parameter pack.
705 if (Default && IsParameterPack) {
706 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000707 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000708 }
709
Douglas Gregordc13ded2010-07-01 00:00:45 +0000710 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000711 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000712 // Check for unexpanded parameter packs.
713 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
714 return Param;
715
Douglas Gregordc13ded2010-07-01 00:00:45 +0000716 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000717 ExprResult DefaultRes =
718 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000719 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000720 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000721 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000722 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000723 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724
Richard Smith1469b912015-06-10 00:29:03 +0000725 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
John McCall48871652010-08-21 09:40:31 +0000728 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000729}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000730
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000731/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000732/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000733/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000734Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
735 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000736 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000737 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000738 IdentifierInfo *Name,
739 SourceLocation NameLoc,
740 unsigned Depth,
741 unsigned Position,
742 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000743 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000744 assert(S->isTemplateParamScope() &&
745 "Template template parameter not in template parameter scope!");
746
747 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000748 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000749 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000750 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000751 NameLoc.isInvalid()? TmpLoc : NameLoc,
752 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000753 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000754 Param->setAccess(AS_public);
755
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000756 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000757 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000758 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000759 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
760
John McCall48871652010-08-21 09:40:31 +0000761 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000762 IdResolver.AddDecl(Param);
763 }
764
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000765 if (Params->size() == 0) {
766 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
767 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
768 Param->setInvalidDecl();
769 }
770
Douglas Gregorf5500772011-01-05 15:48:55 +0000771 // C++0x [temp.param]p9:
772 // A default template-argument may be specified for any kind of
773 // template-parameter that is not a template parameter pack.
774 if (IsParameterPack && !Default.isInvalid()) {
775 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
776 Default = ParsedTemplateArgument();
777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778
Douglas Gregordc13ded2010-07-01 00:00:45 +0000779 if (!Default.isInvalid()) {
780 // Check only that we have a template template argument. We don't want to
781 // try to check well-formedness now, because our template template parameter
782 // might have dependent types in its template parameters, which we wouldn't
783 // be able to match now.
784 //
785 // If none of the template template parameter's template arguments mention
786 // other template parameters, we could actually perform more checking here.
787 // However, it isn't worth doing.
788 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
789 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
790 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
791 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000792 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000795 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000797 DefaultArg.getArgument().getAsTemplate(),
798 UPPC_DefaultArgument))
799 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
Richard Smith1469b912015-06-10 00:29:03 +0000801 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803
John McCall48871652010-08-21 09:40:31 +0000804 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000805}
806
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000807/// ActOnTemplateParameterList - Builds a TemplateParameterList that
808/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000809TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000810Sema::ActOnTemplateParameterList(unsigned Depth,
811 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000812 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000813 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000814 ArrayRef<Decl *> Params,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000815 SourceLocation RAngleLoc) {
816 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000817 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000818
David Majnemer902f8c62015-12-27 07:16:27 +0000819 return TemplateParameterList::Create(
820 Context, TemplateLoc, LAngleLoc,
821 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
822 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000823}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000824
John McCall3e11ebe2010-03-15 10:12:16 +0000825static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
826 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000828}
829
John McCallfaf5fb42010-08-26 23:41:50 +0000830DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000831Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000832 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 IdentifierInfo *Name, SourceLocation NameLoc,
834 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000835 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000837 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000838 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000839 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000840 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000841 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000842 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000843 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000844 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000845
846 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000847 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000848 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849
Abramo Bagnara6150c882010-05-11 21:36:43 +0000850 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
851 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852
853 // There is no such thing as an unnamed class template.
854 if (!Name) {
855 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857 }
858
Richard Smith6483d222012-04-21 01:27:54 +0000859 // Find any previous declaration with this name. For a friend with no
860 // scope explicitly specified, we only look for tag declarations (per
861 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000862 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000863 LookupResult Previous(*this, Name, NameLoc,
864 (SS.isEmpty() && TUK == TUK_Friend)
865 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000866 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000867 if (SS.isNotEmpty() && !SS.isInvalid()) {
868 SemanticContext = computeDeclContext(SS, true);
869 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000870 // FIXME: Horrible, horrible hack! We can't currently represent this
871 // in the AST, and historically we have just ignored such friend
872 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000873 Diag(NameLoc, TUK == TUK_Friend
874 ? diag::warn_template_qualified_friend_ignored
875 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000876 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000877 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000878 }
Mike Stump11289f42009-09-09 15:08:12 +0000879
John McCall0b66eb32010-05-01 00:40:08 +0000880 if (RequireCompleteDeclContext(SS, SemanticContext))
881 return true;
882
Douglas Gregor041b0842011-10-14 15:31:12 +0000883 // If we're adding a template to a dependent context, we may need to
884 // rebuilding some of the types used within the template parameter list,
885 // now that we know what the current instantiation is.
886 if (SemanticContext->isDependentContext()) {
887 ContextRAII SavedContext(*this, SemanticContext);
888 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
889 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000890 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
891 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000892
John McCall27b18f82009-11-17 02:14:36 +0000893 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000894 } else {
895 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000896
897 // C++14 [class.mem]p14:
898 // If T is the name of a class, then each of the following shall have a
899 // name different from T:
900 // -- every member template of class T
901 if (TUK != TUK_Friend &&
902 DiagnoseClassNameShadow(SemanticContext,
903 DeclarationNameInfo(Name, NameLoc)))
904 return true;
905
John McCall27b18f82009-11-17 02:14:36 +0000906 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000907 }
Mike Stump11289f42009-09-09 15:08:12 +0000908
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000909 if (Previous.isAmbiguous())
910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000911
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000913 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000914 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000915
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000916 // If there is a previous declaration with the same name, check
917 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000918 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000919 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000920
921 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000922 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000923 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000925 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
926 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000928 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
929 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
930 PrevClassTemplate
931 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
932 ->getSpecializedTemplate();
933 }
934 }
935
John McCalld43784f2009-12-18 11:25:59 +0000936 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000937 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938 // [...] When looking for a prior declaration of a class or a function
939 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000940 // function is neither a qualified name nor a template-id, scopes outside
941 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000942 if (!SS.isSet()) {
943 DeclContext *OutermostContext = CurContext;
944 while (!OutermostContext->isFileContext())
945 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000946
Richard Smith61e582f2012-04-20 07:12:26 +0000947 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000948 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
949 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
950 SemanticContext = PrevDecl->getDeclContext();
951 } else {
952 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000953 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000954 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000955 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000956 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000957
958 // Check that the chosen semantic context doesn't already contain a
959 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000960 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000961 DeclContext *LookupContext = SemanticContext;
962 while (LookupContext->isTransparentContext())
963 LookupContext = LookupContext->getLookupParent();
964 LookupQualifiedName(Previous, LookupContext);
965
966 if (Previous.isAmbiguous())
967 return true;
968
969 if (Previous.begin() != Previous.end())
970 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000971 }
John McCall90d3bb92009-12-17 23:21:11 +0000972 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000973 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000974 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
975 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000976 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000977
Richard Smithfc805ca2015-07-06 04:43:58 +0000978 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
979 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
980 if (SS.isEmpty() &&
981 !(PrevClassTemplate &&
982 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
983 SemanticContext->getRedeclContext()))) {
984 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
985 Diag(Shadow->getTargetDecl()->getLocation(),
986 diag::note_using_decl_target);
987 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
988 // Recover by ignoring the old declaration.
989 PrevDecl = PrevClassTemplate = nullptr;
990 }
991 }
992
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000993 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000994 // Ensure that the template parameter lists are compatible. Skip this check
995 // for a friend in a dependent context: the template parameter list itself
996 // could be dependent.
997 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
998 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000999 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001000 /*Complain=*/true,
1001 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001002 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001003
1004 // C++ [temp.class]p4:
1005 // In a redeclaration, partial specialization, explicit
1006 // specialization or explicit instantiation of a class template,
1007 // the class-key shall agree in kind with the original class
1008 // template declaration (7.1.5.3).
1009 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001010 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001011 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001012 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001013 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001014 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001015 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001016 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 }
1018
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001019 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001020 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001021 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001022 // If we have a prior definition that is not visible, treat this as
1023 // simply making that previous definition visible.
1024 NamedDecl *Hidden = nullptr;
1025 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001026 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001027 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1028 assert(Tmpl && "original definition of a class template is not a "
1029 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001030 makeMergedDefinitionVisible(Hidden, KWLoc);
1031 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001032 return Def;
1033 }
1034
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001035 Diag(NameLoc, diag::err_redefinition) << Name;
1036 Diag(Def->getLocation(), diag::note_previous_definition);
1037 // FIXME: Would it make sense to try to "forget" the previous
1038 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001039 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001041 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001042 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1043 // Maybe we will complain about the shadowed template parameter.
1044 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1045 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001046 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001047 } else if (PrevDecl) {
1048 // C++ [temp]p5:
1049 // A class template shall not have the same name as any other
1050 // template, class, function, object, enumeration, enumerator,
1051 // namespace, or type in the same scope (3.3), except as specified
1052 // in (14.5.4).
1053 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1054 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001055 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001056 }
1057
Douglas Gregordba32632009-02-10 19:49:53 +00001058 // Check the template parameter list of this declaration, possibly
1059 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001060 // template declaration. Skip this check for a friend in a dependent
1061 // context, because the template parameter list might be dependent.
1062 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001063 CheckTemplateParameterList(
1064 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001065 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1066 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001067 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1068 SemanticContext->isDependentContext())
1069 ? TPC_ClassTemplateMember
1070 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1071 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001072 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001074 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001075 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001076 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001077 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1078 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001079 : diag::err_member_decl_does_not_match)
1080 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001081 Invalid = true;
1082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083 }
1084
Mike Stump11289f42009-09-09 15:08:12 +00001085 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001086 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001087 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001088 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001089 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001090 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001091 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001092 NewClass->setTemplateParameterListsInfo(
1093 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1094 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001095
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001096 // Add alignment attributes if necessary; these attributes are checked when
1097 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001098 if (TUK == TUK_Definition) {
1099 AddAlignmentAttributesForRecord(NewClass);
1100 AddMsStructLayoutForRecord(NewClass);
1101 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001102
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103 ClassTemplateDecl *NewTemplate
1104 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1105 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001106 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001107 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001108
Douglas Gregor21823bf2011-12-20 18:11:52 +00001109 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001110 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001111
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001112 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001113 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001114 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001115 assert(T->isDependentType() && "Class template type is not dependent?");
1116 (void)T;
1117
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001118 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001119 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001121 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1122 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123
Anders Carlsson137108d2009-03-26 01:24:28 +00001124 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001125 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001126 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001127
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001128 // Set the lexical context of these templates
1129 NewClass->setLexicalDeclContext(CurContext);
1130 NewTemplate->setLexicalDeclContext(CurContext);
1131
John McCall9bb74a52009-07-31 02:45:11 +00001132 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001133 NewClass->startDefinition();
1134
1135 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001136 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001137
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001138 if (PrevClassTemplate)
1139 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1140
Rafael Espindola385c0422012-07-13 18:04:45 +00001141 AddPushedVisibilityAttribute(NewClass);
1142
Richard Smith234ff472014-08-23 00:49:01 +00001143 if (TUK != TUK_Friend) {
1144 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1145 Scope *Outer = S;
1146 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1147 Outer = Outer->getParent();
1148 PushOnScopeChains(NewTemplate, Outer);
1149 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001150 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001151 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001152 NewClass->setAccess(PrevClassTemplate->getAccess());
1153 }
John McCall27b5c252009-09-14 21:59:20 +00001154
Richard Smith64017682013-07-17 23:53:16 +00001155 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
John McCall27b5c252009-09-14 21:59:20 +00001157 // Friend templates are visible in fairly strange ways.
1158 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001159 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001160 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001161 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1162 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001166 FriendDecl *Friend = FriendDecl::Create(
1167 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001168 Friend->setAccess(AS_public);
1169 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001170 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001171
Douglas Gregordba32632009-02-10 19:49:53 +00001172 if (Invalid) {
1173 NewTemplate->setInvalidDecl();
1174 NewClass->setInvalidDecl();
1175 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001176
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001177 ActOnDocumentableDecl(NewTemplate);
1178
John McCall48871652010-08-21 09:40:31 +00001179 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001180}
1181
Douglas Gregored5731f2009-11-25 17:50:39 +00001182/// \brief Diagnose the presence of a default template argument on a
1183/// template parameter, which is ill-formed in certain contexts.
1184///
1185/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001187 Sema::TemplateParamListContext TPC,
1188 SourceLocation ParamLoc,
1189 SourceRange DefArgRange) {
1190 switch (TPC) {
1191 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001192 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001193 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001194 return false;
1195
1196 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001197 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001198 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001199 // A default template-argument shall not be specified in a
1200 // function template declaration or a function template
1201 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001202 // If a friend function template declaration specifies a default
1203 // template-argument, that declaration shall be a definition and shall be
1204 // the only declaration of the function template in the translation unit.
1205 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001206 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001207 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1208 : diag::ext_template_parameter_default_in_function_template)
1209 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001210 return false;
1211
1212 case Sema::TPC_ClassTemplateMember:
1213 // C++0x [temp.param]p9:
1214 // A default template-argument shall not be specified in the
1215 // template-parameter-lists of the definition of a member of a
1216 // class template that appears outside of the member's class.
1217 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1218 << DefArgRange;
1219 return true;
1220
David Majnemerba8f17a2013-06-25 22:08:55 +00001221 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001222 case Sema::TPC_FriendFunctionTemplate:
1223 // C++ [temp.param]p9:
1224 // A default template-argument shall not be specified in a
1225 // friend template declaration.
1226 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1227 << DefArgRange;
1228 return true;
1229
1230 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1231 // for friend function templates if there is only a single
1232 // declaration (and it is a definition). Strange!
1233 }
1234
David Blaikie8a40f702012-01-17 06:56:22 +00001235 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001236}
1237
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001238/// \brief Check for unexpanded parameter packs within the template parameters
1239/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001240static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1241 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001242 // A template template parameter which is a parameter pack is also a pack
1243 // expansion.
1244 if (TTP->isParameterPack())
1245 return false;
1246
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001247 TemplateParameterList *Params = TTP->getTemplateParameters();
1248 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1249 NamedDecl *P = Params->getParam(I);
1250 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001251 if (!NTTP->isParameterPack() &&
1252 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001253 NTTP->getTypeSourceInfo(),
1254 Sema::UPPC_NonTypeTemplateParameterType))
1255 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001256
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001257 continue;
1258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001259
1260 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001261 = dyn_cast<TemplateTemplateParmDecl>(P))
1262 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1263 return true;
1264 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001266 return false;
1267}
1268
Douglas Gregordba32632009-02-10 19:49:53 +00001269/// \brief Checks the validity of a template parameter list, possibly
1270/// considering the template parameter list from a previous
1271/// declaration.
1272///
1273/// If an "old" template parameter list is provided, it must be
1274/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1275/// template parameter list.
1276///
1277/// \param NewParams Template parameter list for a new template
1278/// declaration. This template parameter list will be updated with any
1279/// default arguments that are carried through from the previous
1280/// template parameter list.
1281///
1282/// \param OldParams If provided, template parameter list from a
1283/// previous declaration of the same template. Default template
1284/// arguments will be merged from the old template parameter list to
1285/// the new template parameter list.
1286///
Douglas Gregored5731f2009-11-25 17:50:39 +00001287/// \param TPC Describes the context in which we are checking the given
1288/// template parameter list.
1289///
Douglas Gregordba32632009-02-10 19:49:53 +00001290/// \returns true if an error occurred, false otherwise.
1291bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001292 TemplateParameterList *OldParams,
1293 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001294 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregordba32632009-02-10 19:49:53 +00001296 // C++ [temp.param]p10:
1297 // The set of default template-arguments available for use with a
1298 // template declaration or definition is obtained by merging the
1299 // default arguments from the definition (if in scope) and all
1300 // declarations in scope in the same way default function
1301 // arguments are (8.3.6).
1302 bool SawDefaultArgument = false;
1303 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001304
Mike Stumpc89c8e32009-02-11 23:03:27 +00001305 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001306 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001307 if (OldParams)
1308 OldParam = OldParams->begin();
1309
Douglas Gregor0693def2011-01-27 01:40:17 +00001310 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001311 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1312 NewParamEnd = NewParams->end();
1313 NewParam != NewParamEnd; ++NewParam) {
1314 // Variables used to diagnose redundant default arguments
1315 bool RedundantDefaultArg = false;
1316 SourceLocation OldDefaultLoc;
1317 SourceLocation NewDefaultLoc;
1318
David Blaikie651c73c2011-10-19 05:19:50 +00001319 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001320 bool MissingDefaultArg = false;
1321
David Blaikie651c73c2011-10-19 05:19:50 +00001322 // Variable used to diagnose non-final parameter packs
1323 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001324
Douglas Gregordba32632009-02-10 19:49:53 +00001325 if (TemplateTypeParmDecl *NewTypeParm
1326 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001327 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328 if (NewTypeParm->hasDefaultArgument() &&
1329 DiagnoseDefaultTemplateArgument(*this, TPC,
1330 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001331 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001332 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001333 NewTypeParm->removeDefaultArgument();
1334
1335 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001336 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001337 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001338 if (NewTypeParm->isParameterPack()) {
1339 assert(!NewTypeParm->hasDefaultArgument() &&
1340 "Parameter packs can't have a default argument!");
1341 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001342 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001343 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001344 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1345 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1346 SawDefaultArgument = true;
1347 RedundantDefaultArg = true;
1348 PreviousDefaultArgLoc = NewDefaultLoc;
1349 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1350 // Merge the default argument from the old declaration to the
1351 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001352 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001353 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1354 } else if (NewTypeParm->hasDefaultArgument()) {
1355 SawDefaultArgument = true;
1356 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1357 } else if (SawDefaultArgument)
1358 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001359 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001360 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001361 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001362 if (!NewNonTypeParm->isParameterPack() &&
1363 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001365 UPPC_NonTypeTemplateParameterType)) {
1366 Invalid = true;
1367 continue;
1368 }
1369
Douglas Gregored5731f2009-11-25 17:50:39 +00001370 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001371 if (NewNonTypeParm->hasDefaultArgument() &&
1372 DiagnoseDefaultTemplateArgument(*this, TPC,
1373 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001374 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001375 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001376 }
1377
Mike Stump12b8ce12009-08-04 21:02:39 +00001378 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001379 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001380 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001381 if (NewNonTypeParm->isParameterPack()) {
1382 assert(!NewNonTypeParm->hasDefaultArgument() &&
1383 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001384 if (!NewNonTypeParm->isPackExpansion())
1385 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001386 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001387 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001388 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1389 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1390 SawDefaultArgument = true;
1391 RedundantDefaultArg = true;
1392 PreviousDefaultArgLoc = NewDefaultLoc;
1393 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1394 // Merge the default argument from the old declaration to the
1395 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001396 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001397 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1398 } else if (NewNonTypeParm->hasDefaultArgument()) {
1399 SawDefaultArgument = true;
1400 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1401 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001402 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001403 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001404 TemplateTemplateParmDecl *NewTemplateParm
1405 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001407 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001408 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001409 Invalid = true;
1410 continue;
1411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412
David Blaikie651c73c2011-10-19 05:19:50 +00001413 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414 if (NewTemplateParm->hasDefaultArgument() &&
1415 DiagnoseDefaultTemplateArgument(*this, TPC,
1416 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001417 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001418 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001419
1420 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001421 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001422 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001423 if (NewTemplateParm->isParameterPack()) {
1424 assert(!NewTemplateParm->hasDefaultArgument() &&
1425 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001426 if (!NewTemplateParm->isPackExpansion())
1427 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001428 } else if (OldTemplateParm &&
1429 hasVisibleDefaultArgument(OldTemplateParm) &&
1430 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001431 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1432 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001433 SawDefaultArgument = true;
1434 RedundantDefaultArg = true;
1435 PreviousDefaultArgLoc = NewDefaultLoc;
1436 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1437 // Merge the default argument from the old declaration to the
1438 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001439 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001440 PreviousDefaultArgLoc
1441 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001442 } else if (NewTemplateParm->hasDefaultArgument()) {
1443 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001444 PreviousDefaultArgLoc
1445 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001446 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001447 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001448 }
1449
Richard Smith1fde8ec2012-09-07 02:06:42 +00001450 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001451 // If a template parameter of a primary class template or alias template
1452 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001453 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001454 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1455 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001456 Diag((*NewParam)->getLocation(),
1457 diag::err_template_param_pack_must_be_last_template_parameter);
1458 Invalid = true;
1459 }
1460
Douglas Gregordba32632009-02-10 19:49:53 +00001461 if (RedundantDefaultArg) {
1462 // C++ [temp.param]p12:
1463 // A template-parameter shall not be given default arguments
1464 // by two different declarations in the same scope.
1465 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1466 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1467 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001468 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001469 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 // If a template-parameter of a class template has a default
1471 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001472 // have a default template-argument supplied or be a template parameter
1473 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001474 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001475 diag::err_template_param_default_arg_missing);
1476 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1477 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001478 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001479 }
1480
1481 // If we have an old template parameter list that we're merging
1482 // in, move on to the next parameter.
1483 if (OldParams)
1484 ++OldParam;
1485 }
1486
Douglas Gregor0693def2011-01-27 01:40:17 +00001487 // We were missing some default arguments at the end of the list, so remove
1488 // all of the default arguments.
1489 if (RemoveDefaultArguments) {
1490 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1491 NewParamEnd = NewParams->end();
1492 NewParam != NewParamEnd; ++NewParam) {
1493 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1494 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001496 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1497 NTTP->removeDefaultArgument();
1498 else
1499 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1500 }
1501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001502
Douglas Gregordba32632009-02-10 19:49:53 +00001503 return Invalid;
1504}
Douglas Gregord32e0282009-02-09 23:23:08 +00001505
John McCalla020a012010-10-20 05:44:58 +00001506namespace {
1507
1508/// A class which looks for a use of a certain level of template
1509/// parameter.
1510struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1511 typedef RecursiveASTVisitor<DependencyChecker> super;
1512
1513 unsigned Depth;
1514 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001515 SourceLocation MatchLoc;
1516
1517 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001518
1519 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1520 NamedDecl *ND = Params->getParam(0);
1521 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1522 Depth = PD->getDepth();
1523 } else if (NonTypeTemplateParmDecl *PD =
1524 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1525 Depth = PD->getDepth();
1526 } else {
1527 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1528 }
1529 }
1530
Richard Smith6056d5e2014-02-09 00:54:43 +00001531 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001532 if (ParmDepth >= Depth) {
1533 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001534 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001535 return true;
1536 }
1537 return false;
1538 }
1539
Richard Smith6056d5e2014-02-09 00:54:43 +00001540 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1541 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1542 }
1543
John McCalla020a012010-10-20 05:44:58 +00001544 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1545 return !Matches(T->getDepth());
1546 }
1547
1548 bool TraverseTemplateName(TemplateName N) {
1549 if (TemplateTemplateParmDecl *PD =
1550 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001551 if (Matches(PD->getDepth()))
1552 return false;
John McCalla020a012010-10-20 05:44:58 +00001553 return super::TraverseTemplateName(N);
1554 }
1555
1556 bool VisitDeclRefExpr(DeclRefExpr *E) {
1557 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001558 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1559 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001560 return false;
John McCalla020a012010-10-20 05:44:58 +00001561 return super::VisitDeclRefExpr(E);
1562 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001563
1564 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1565 return TraverseType(T->getReplacementType());
1566 }
1567
1568 bool
1569 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1570 return TraverseTemplateArgument(T->getArgumentPack());
1571 }
1572
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001573 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1574 return TraverseType(T->getInjectedSpecializationType());
1575 }
John McCalla020a012010-10-20 05:44:58 +00001576};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001577} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001578
Douglas Gregor972fe532011-05-10 18:27:06 +00001579/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001580/// list.
1581static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001582DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001583 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001584 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001585 return Checker.Match;
1586}
1587
Douglas Gregor972fe532011-05-10 18:27:06 +00001588// Find the source range corresponding to the named type in the given
1589// nested-name-specifier, if any.
1590static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1591 QualType T,
1592 const CXXScopeSpec &SS) {
1593 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1594 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1595 if (const Type *CurType = NNS->getAsType()) {
1596 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1597 return NNSLoc.getTypeLoc().getSourceRange();
1598 } else
1599 break;
1600
1601 NNSLoc = NNSLoc.getPrefix();
1602 }
1603
1604 return SourceRange();
1605}
1606
Mike Stump11289f42009-09-09 15:08:12 +00001607/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001608/// specifier, returning the template parameter list that applies to the
1609/// name.
1610///
1611/// \param DeclStartLoc the start of the declaration that has a scope
1612/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001613///
Douglas Gregor972fe532011-05-10 18:27:06 +00001614/// \param DeclLoc The location of the declaration itself.
1615///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001616/// \param SS the scope specifier that will be matched to the given template
1617/// parameter lists. This scope specifier precedes a qualified name that is
1618/// being declared.
1619///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001620/// \param TemplateId The template-id following the scope specifier, if there
1621/// is one. Used to check for a missing 'template<>'.
1622///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001623/// \param ParamLists the template parameter lists, from the outermost to the
1624/// innermost template parameter lists.
1625///
John McCalle820e5e2010-04-13 20:37:33 +00001626/// \param IsFriend Whether to apply the slightly different rules for
1627/// matching template parameters to scope specifiers in friend
1628/// declarations.
1629///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001630/// \param IsExplicitSpecialization will be set true if the entity being
1631/// declared is an explicit specialization, false otherwise.
1632///
Mike Stump11289f42009-09-09 15:08:12 +00001633/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001634/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001635/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001636/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001637/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001638/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001639TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1640 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001641 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001642 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1643 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001644 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001645 Invalid = false;
1646
1647 // The sequence of nested types to which we will match up the template
1648 // parameter lists. We first build this list by starting with the type named
1649 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001650 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001651 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001652 if (SS.getScopeRep()) {
1653 if (CXXRecordDecl *Record
1654 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1655 T = Context.getTypeDeclType(Record);
1656 else
1657 T = QualType(SS.getScopeRep()->getAsType(), 0);
1658 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001659
1660 // If we found an explicit specialization that prevents us from needing
1661 // 'template<>' headers, this will be set to the location of that
1662 // explicit specialization.
1663 SourceLocation ExplicitSpecLoc;
1664
1665 while (!T.isNull()) {
1666 NestedTypes.push_back(T);
1667
1668 // Retrieve the parent of a record type.
1669 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1670 // If this type is an explicit specialization, we're done.
1671 if (ClassTemplateSpecializationDecl *Spec
1672 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1673 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1674 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1675 ExplicitSpecLoc = Spec->getLocation();
1676 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001677 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001678 } else if (Record->getTemplateSpecializationKind()
1679 == TSK_ExplicitSpecialization) {
1680 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001681 break;
1682 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001683
1684 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1685 T = Context.getTypeDeclType(Parent);
1686 else
1687 T = QualType();
1688 continue;
1689 }
1690
1691 if (const TemplateSpecializationType *TST
1692 = T->getAs<TemplateSpecializationType>()) {
1693 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1694 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1695 T = Context.getTypeDeclType(Parent);
1696 else
1697 T = QualType();
1698 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001699 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001700 }
1701
1702 // Look one step prior in a dependent template specialization type.
1703 if (const DependentTemplateSpecializationType *DependentTST
1704 = T->getAs<DependentTemplateSpecializationType>()) {
1705 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1706 T = QualType(NNS->getAsType(), 0);
1707 else
1708 T = QualType();
1709 continue;
1710 }
1711
1712 // Look one step prior in a dependent name type.
1713 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1714 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1715 T = QualType(NNS->getAsType(), 0);
1716 else
1717 T = QualType();
1718 continue;
1719 }
1720
1721 // Retrieve the parent of an enumeration type.
1722 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1723 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1724 // check here.
1725 EnumDecl *Enum = EnumT->getDecl();
1726
1727 // Get to the parent type.
1728 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1729 T = Context.getTypeDeclType(Parent);
1730 else
1731 T = QualType();
1732 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001733 }
Mike Stump11289f42009-09-09 15:08:12 +00001734
Douglas Gregor972fe532011-05-10 18:27:06 +00001735 T = QualType();
1736 }
1737 // Reverse the nested types list, since we want to traverse from the outermost
1738 // to the innermost while checking template-parameter-lists.
1739 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001740
Douglas Gregor972fe532011-05-10 18:27:06 +00001741 // C++0x [temp.expl.spec]p17:
1742 // A member or a member template may be nested within many
1743 // enclosing class templates. In an explicit specialization for
1744 // such a member, the member declaration shall be preceded by a
1745 // template<> for each enclosing class template that is
1746 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001747 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001748
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001749 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001750 if (SawNonEmptyTemplateParameterList) {
1751 Diag(DeclLoc, diag::err_specialize_member_of_template)
1752 << !Recovery << Range;
1753 Invalid = true;
1754 IsExplicitSpecialization = false;
1755 return true;
1756 }
1757
1758 return false;
1759 };
1760
1761 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1762 // Check that we can have an explicit specialization here.
1763 if (CheckExplicitSpecialization(Range, true))
1764 return true;
1765
1766 // We don't have a template header, but we should.
1767 SourceLocation ExpectedTemplateLoc;
1768 if (!ParamLists.empty())
1769 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1770 else
1771 ExpectedTemplateLoc = DeclStartLoc;
1772
1773 Diag(DeclLoc, diag::err_template_spec_needs_header)
1774 << Range
1775 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1776 return false;
1777 };
1778
Douglas Gregor972fe532011-05-10 18:27:06 +00001779 unsigned ParamIdx = 0;
1780 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1781 ++TypeIdx) {
1782 T = NestedTypes[TypeIdx];
1783
1784 // Whether we expect a 'template<>' header.
1785 bool NeedEmptyTemplateHeader = false;
1786
1787 // Whether we expect a template header with parameters.
1788 bool NeedNonemptyTemplateHeader = false;
1789
1790 // For a dependent type, the set of template parameters that we
1791 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001792 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001793
Douglas Gregor373af9b2011-05-11 23:26:17 +00001794 // C++0x [temp.expl.spec]p15:
1795 // A member or a member template may be nested within many enclosing
1796 // class templates. In an explicit specialization for such a member, the
1797 // member declaration shall be preceded by a template<> for each
1798 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001799 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1800 if (ClassTemplatePartialSpecializationDecl *Partial
1801 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1802 ExpectedTemplateParams = Partial->getTemplateParameters();
1803 NeedNonemptyTemplateHeader = true;
1804 } else if (Record->isDependentType()) {
1805 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001806 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001807 ->getTemplateParameters();
1808 NeedNonemptyTemplateHeader = true;
1809 }
1810 } else if (ClassTemplateSpecializationDecl *Spec
1811 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1812 // C++0x [temp.expl.spec]p4:
1813 // Members of an explicitly specialized class template are defined
1814 // in the same manner as members of normal classes, and not using
1815 // the template<> syntax.
1816 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1817 NeedEmptyTemplateHeader = true;
1818 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001819 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001820 } else if (Record->getTemplateSpecializationKind()) {
1821 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001822 != TSK_ExplicitSpecialization &&
1823 TypeIdx == NumTypes - 1)
1824 IsExplicitSpecialization = true;
1825
1826 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001827 }
1828 } else if (const TemplateSpecializationType *TST
1829 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001830 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001831 ExpectedTemplateParams = Template->getTemplateParameters();
1832 NeedNonemptyTemplateHeader = true;
1833 }
1834 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1835 // FIXME: We actually could/should check the template arguments here
1836 // against the corresponding template parameter list.
1837 NeedNonemptyTemplateHeader = false;
1838 }
1839
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001840 // C++ [temp.expl.spec]p16:
1841 // In an explicit specialization declaration for a member of a class
1842 // template or a member template that ap- pears in namespace scope, the
1843 // member template and some of its enclosing class templates may remain
1844 // unspecialized, except that the declaration shall not explicitly
1845 // specialize a class member template if its en- closing class templates
1846 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001847 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001848 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001849 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1850 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001851 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001852 } else
1853 SawNonEmptyTemplateParameterList = true;
1854 }
1855
Douglas Gregor972fe532011-05-10 18:27:06 +00001856 if (NeedEmptyTemplateHeader) {
1857 // If we're on the last of the types, and we need a 'template<>' header
1858 // here, then it's an explicit specialization.
1859 if (TypeIdx == NumTypes - 1)
1860 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001861
1862 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001863 if (ParamLists[ParamIdx]->size() > 0) {
1864 // The header has template parameters when it shouldn't. Complain.
1865 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1866 diag::err_template_param_list_matches_nontemplate)
1867 << T
1868 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1869 ParamLists[ParamIdx]->getRAngleLoc())
1870 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1871 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001872 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001873 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001874
Douglas Gregor972fe532011-05-10 18:27:06 +00001875 // Consume this template header.
1876 ++ParamIdx;
1877 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001878 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001879
1880 if (!IsFriend)
1881 if (DiagnoseMissingExplicitSpecialization(
1882 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001883 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001884
Douglas Gregor972fe532011-05-10 18:27:06 +00001885 continue;
1886 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001887
Douglas Gregor972fe532011-05-10 18:27:06 +00001888 if (NeedNonemptyTemplateHeader) {
1889 // In friend declarations we can have template-ids which don't
1890 // depend on the corresponding template parameter lists. But
1891 // assume that empty parameter lists are supposed to match this
1892 // template-id.
1893 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001894 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001895 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001896 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001897 else
1898 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001899 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001900
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001901 if (ParamIdx < ParamLists.size()) {
1902 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001903 if (ExpectedTemplateParams &&
1904 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1905 ExpectedTemplateParams,
1906 true, TPL_TemplateMatch))
1907 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001908
Douglas Gregor972fe532011-05-10 18:27:06 +00001909 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001911 TPC_ClassTemplateMember))
1912 Invalid = true;
1913
1914 ++ParamIdx;
1915 continue;
1916 }
1917
1918 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1919 << T
1920 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1921 Invalid = true;
1922 continue;
1923 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001924 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001925
Douglas Gregord8d297c2009-07-21 23:53:31 +00001926 // If there were at least as many template-ids as there were template
1927 // parameter lists, then there are no template parameter lists remaining for
1928 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001929 if (ParamIdx >= ParamLists.size()) {
1930 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001931 // We don't have a template header for the declaration itself, but we
1932 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001933 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001934 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1935 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001936
1937 // Fabricate an empty template parameter list for the invented header.
1938 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00001939 SourceLocation(), None,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001940 SourceLocation());
1941 }
1942
Craig Topperc3ec1492014-05-26 06:22:03 +00001943 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
Douglas Gregord8d297c2009-07-21 23:53:31 +00001946 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001947 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001948 bool HasAnyExplicitSpecHeader = false;
1949 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001950 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001951 if (ParamLists[I]->size() == 0)
1952 HasAnyExplicitSpecHeader = true;
1953 else
1954 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001955 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001956
Douglas Gregor972fe532011-05-10 18:27:06 +00001957 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001958 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1959 : diag::err_template_spec_extra_headers)
1960 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1961 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001962
1963 // If there was a specialization somewhere, such that 'template<>' is
1964 // not required, and there were any 'template<>' headers, note where the
1965 // specialization occurred.
1966 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1967 Diag(ExplicitSpecLoc,
1968 diag::note_explicit_template_spec_does_not_need_header)
1969 << NestedTypes.back();
1970
1971 // We have a template parameter list with no corresponding scope, which
1972 // means that the resulting template declaration can't be instantiated
1973 // properly (we'll end up with dependent nodes when we shouldn't).
1974 if (!AllExplicitSpecHeaders)
1975 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001976 }
Mike Stump11289f42009-09-09 15:08:12 +00001977
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001978 // C++ [temp.expl.spec]p16:
1979 // In an explicit specialization declaration for a member of a class
1980 // template or a member template that ap- pears in namespace scope, the
1981 // member template and some of its enclosing class templates may remain
1982 // unspecialized, except that the declaration shall not explicitly
1983 // specialize a class member template if its en- closing class templates
1984 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001985 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001986 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1987 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001988 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001989
Douglas Gregord8d297c2009-07-21 23:53:31 +00001990 // Return the last template parameter list, which corresponds to the
1991 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001992 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001993}
1994
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001995void Sema::NoteAllFoundTemplates(TemplateName Name) {
1996 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1997 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001998 << (isa<FunctionTemplateDecl>(Template)
1999 ? 0
2000 : isa<ClassTemplateDecl>(Template)
2001 ? 1
2002 : isa<VarTemplateDecl>(Template)
2003 ? 2
2004 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2005 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002006 return;
2007 }
2008
2009 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2010 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2011 IEnd = OST->end();
2012 I != IEnd; ++I)
2013 Diag((*I)->getLocation(), diag::note_template_declared_here)
2014 << 0 << (*I)->getDeclName();
2015
2016 return;
2017 }
2018}
2019
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002020static QualType
2021checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2022 const SmallVectorImpl<TemplateArgument> &Converted,
2023 SourceLocation TemplateLoc,
2024 TemplateArgumentListInfo &TemplateArgs) {
2025 ASTContext &Context = SemaRef.getASTContext();
2026 switch (BTD->getBuiltinTemplateKind()) {
2027 case BTK__make_integer_seq:
2028 // Specializations of __make_integer_seq<S, T, N> are treated like
2029 // S<T, 0, ..., N-1>.
2030
2031 // C++14 [inteseq.intseq]p1:
2032 // T shall be an integer type.
2033 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2034 SemaRef.Diag(TemplateArgs[1].getLocation(),
2035 diag::err_integer_sequence_integral_element_type);
2036 return QualType();
2037 }
2038
2039 // C++14 [inteseq.make]p1:
2040 // If N is negative the program is ill-formed.
2041 TemplateArgument NumArgsArg = Converted[2];
2042 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2043 if (NumArgs < 0) {
2044 SemaRef.Diag(TemplateArgs[2].getLocation(),
2045 diag::err_integer_sequence_negative_length);
2046 return QualType();
2047 }
2048
2049 QualType ArgTy = NumArgsArg.getIntegralType();
2050 TemplateArgumentListInfo SyntheticTemplateArgs;
2051 // The type argument gets reused as the first template argument in the
2052 // synthetic template argument list.
2053 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2054 // Expand N into 0 ... N-1.
2055 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2056 I < NumArgs; ++I) {
2057 TemplateArgument TA(Context, I, ArgTy);
2058 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2059 TA, TemplateArgs[2].getLocation())
2060 .getAs<Expr>();
2061 SyntheticTemplateArgs.addArgument(
2062 TemplateArgumentLoc(TemplateArgument(E), E));
2063 }
2064 // The first template argument will be reused as the template decl that
2065 // our synthetic template arguments will be applied to.
2066 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2067 TemplateLoc, SyntheticTemplateArgs);
2068 }
2069 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2070}
2071
Douglas Gregordc572a32009-03-30 22:58:21 +00002072QualType Sema::CheckTemplateIdType(TemplateName Name,
2073 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002074 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002075 DependentTemplateName *DTN
2076 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002077 if (DTN && DTN->isIdentifier())
2078 // When building a template-id where the template-name is dependent,
2079 // assume the template is a type template. Either our assumption is
2080 // correct, or the code is ill-formed and will be diagnosed when the
2081 // dependent name is substituted.
2082 return Context.getDependentTemplateSpecializationType(ETK_None,
2083 DTN->getQualifier(),
2084 DTN->getIdentifier(),
2085 TemplateArgs);
2086
Douglas Gregordc572a32009-03-30 22:58:21 +00002087 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002088 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2089 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002090 // We might have a substituted template template parameter pack. If so,
2091 // build a template specialization type for it.
2092 if (Name.getAsSubstTemplateTemplateParmPack())
2093 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002094
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002095 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2096 << Name;
2097 NoteAllFoundTemplates(Name);
2098 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002099 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002100
Douglas Gregorc40290e2009-03-09 23:48:35 +00002101 // Check that the template argument list is well-formed for this
2102 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002103 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002104 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002105 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002106 return QualType();
2107
Douglas Gregorc40290e2009-03-09 23:48:35 +00002108 QualType CanonType;
2109
Douglas Gregor678d76c2011-07-01 01:22:09 +00002110 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002111 if (TypeAliasTemplateDecl *AliasTemplate =
2112 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002113 // Find the canonical type for this type alias template specialization.
2114 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2115 if (Pattern->isInvalidDecl())
2116 return QualType();
2117
2118 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2119 Converted.data(), Converted.size());
2120
2121 // Only substitute for the innermost template argument list.
2122 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002123 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002124 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2125 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002126 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002127
Richard Smith802c4b72012-08-23 06:16:52 +00002128 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002129 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002130 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002131 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002132
Richard Smith3f1b5d02011-05-05 21:57:07 +00002133 CanonType = SubstType(Pattern->getUnderlyingType(),
2134 TemplateArgLists, AliasTemplate->getLocation(),
2135 AliasTemplate->getDeclName());
2136 if (CanonType.isNull())
2137 return QualType();
2138 } else if (Name.isDependent() ||
2139 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002140 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002141 // This class template specialization is a dependent
2142 // type. Therefore, its canonical type is another class template
2143 // specialization type that contains all of the converted
2144 // arguments in canonical form. This ensures that, e.g., A<T> and
2145 // A<T, T> have identical types when A is declared as:
2146 //
2147 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002148 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002149 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002150 Converted.data(),
2151 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregora8e02e72009-07-28 23:00:59 +00002153 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002154 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002155 // In the future, we need to teach getTemplateSpecializationType to only
2156 // build the canonical type and return that to us.
2157 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002158
2159 // This might work out to be a current instantiation, in which
2160 // case the canonical type needs to be the InjectedClassNameType.
2161 //
2162 // TODO: in theory this could be a simple hashtable lookup; most
2163 // changes to CurContext don't change the set of current
2164 // instantiations.
2165 if (isa<ClassTemplateDecl>(Template)) {
2166 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2167 // If we get out to a namespace, we're done.
2168 if (Ctx->isFileContext()) break;
2169
2170 // If this isn't a record, keep looking.
2171 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2172 if (!Record) continue;
2173
2174 // Look for one of the two cases with InjectedClassNameTypes
2175 // and check whether it's the same template.
2176 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2177 !Record->getDescribedClassTemplate())
2178 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179
John McCall2408e322010-04-27 00:57:59 +00002180 // Fetch the injected class name type and check whether its
2181 // injected type is equal to the type we just built.
2182 QualType ICNT = Context.getTypeDeclType(Record);
2183 QualType Injected = cast<InjectedClassNameType>(ICNT)
2184 ->getInjectedSpecializationType();
2185
2186 if (CanonType != Injected->getCanonicalTypeInternal())
2187 continue;
2188
2189 // If so, the canonical type of this TST is the injected
2190 // class name type of the record we just found.
2191 assert(ICNT.isCanonical());
2192 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002193 break;
2194 }
2195 }
Mike Stump11289f42009-09-09 15:08:12 +00002196 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002197 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002198 // Find the class template specialization declaration that
2199 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002200 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002201 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002202 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002203 if (!Decl) {
2204 // This is the first time we have referenced this class template
2205 // specialization. Create the canonical declaration and add it to
2206 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002207 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002208 ClassTemplate->getTemplatedDecl()->getTagKind(),
2209 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002210 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002211 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002212 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002213 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002214 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002215 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002216 if (ClassTemplate->isOutOfLine())
2217 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002218 }
2219
Chandler Carruth2acfb222013-09-27 22:14:40 +00002220 // Diagnose uses of this specialization.
2221 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2222
Douglas Gregorc40290e2009-03-09 23:48:35 +00002223 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002224 assert(isa<RecordType>(CanonType) &&
2225 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002226 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2227 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2228 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002229 }
Mike Stump11289f42009-09-09 15:08:12 +00002230
Douglas Gregorc40290e2009-03-09 23:48:35 +00002231 // Build the fully-sugared type for this class template
2232 // specialization, which refers back to the class template
2233 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002234 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002235}
2236
John McCallfaf5fb42010-08-26 23:41:50 +00002237TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002238Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002239 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002240 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002241 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002242 SourceLocation RAngleLoc,
2243 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002244 if (SS.isInvalid())
2245 return true;
2246
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002247 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002248
Douglas Gregorc40290e2009-03-09 23:48:35 +00002249 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002250 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002251 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002252
Douglas Gregor5a064722011-02-28 17:23:35 +00002253 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002254 QualType T
2255 = Context.getDependentTemplateSpecializationType(ETK_None,
2256 DTN->getQualifier(),
2257 DTN->getIdentifier(),
2258 TemplateArgs);
2259 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002260 TypeLocBuilder TLB;
2261 DependentTemplateSpecializationTypeLoc SpecTL
2262 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002263 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2264 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002265 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002266 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002267 SpecTL.setLAngleLoc(LAngleLoc);
2268 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002269 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2270 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2271 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2272 }
2273
John McCall6b51f282009-11-23 01:53:49 +00002274 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002275
2276 if (Result.isNull())
2277 return true;
2278
Douglas Gregore7c20652011-03-02 00:47:37 +00002279 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002280 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002281 TemplateSpecializationTypeLoc SpecTL
2282 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002283 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002284 SpecTL.setTemplateNameLoc(TemplateLoc);
2285 SpecTL.setLAngleLoc(LAngleLoc);
2286 SpecTL.setRAngleLoc(RAngleLoc);
2287 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2288 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002289
Abramo Bagnara4244b432012-01-27 08:46:19 +00002290 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2291 // constructor or destructor name (in such a case, the scope specifier
2292 // will be attached to the enclosing Decl or Expr node).
2293 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002294 // Create an elaborated-type-specifier containing the nested-name-specifier.
2295 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2296 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002297 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002298 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2299 }
2300
2301 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002302}
John McCall06f6fe8d2009-09-04 01:14:41 +00002303
Douglas Gregore7c20652011-03-02 00:47:37 +00002304TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002305 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002306 SourceLocation TagLoc,
2307 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002308 SourceLocation TemplateKWLoc,
2309 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002310 SourceLocation TemplateLoc,
2311 SourceLocation LAngleLoc,
2312 ASTTemplateArgsPtr TemplateArgsIn,
2313 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002314 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002315
2316 // Translate the parser's template argument list in our AST format.
2317 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2318 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2319
2320 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002321 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002322 ElaboratedTypeKeyword Keyword
2323 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002324
Douglas Gregore7c20652011-03-02 00:47:37 +00002325 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2326 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2327 DTN->getQualifier(),
2328 DTN->getIdentifier(),
2329 TemplateArgs);
2330
2331 // Build type-source information.
2332 TypeLocBuilder TLB;
2333 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002334 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2335 SpecTL.setElaboratedKeywordLoc(TagLoc);
2336 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002337 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002338 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002339 SpecTL.setLAngleLoc(LAngleLoc);
2340 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002341 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2342 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2343 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2344 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002345
2346 if (TypeAliasTemplateDecl *TAT =
2347 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2348 // C++0x [dcl.type.elab]p2:
2349 // If the identifier resolves to a typedef-name or the simple-template-id
2350 // resolves to an alias template specialization, the
2351 // elaborated-type-specifier is ill-formed.
2352 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2353 Diag(TAT->getLocation(), diag::note_declared_at);
2354 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002355
2356 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2357 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002358 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002359
2360 // Check the tag kind
2361 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002362 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002363
John McCalld8fe9af2009-09-08 17:47:29 +00002364 IdentifierInfo *Id = D->getIdentifier();
2365 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002366
Richard Trieucaa33d32011-06-10 03:11:26 +00002367 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002368 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002369 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002370 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002371 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002372 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002373 }
2374 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002375
Douglas Gregore7c20652011-03-02 00:47:37 +00002376 // Provide source-location information for the template specialization.
2377 TypeLocBuilder TLB;
2378 TemplateSpecializationTypeLoc SpecTL
2379 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002380 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002381 SpecTL.setTemplateNameLoc(TemplateLoc);
2382 SpecTL.setLAngleLoc(LAngleLoc);
2383 SpecTL.setRAngleLoc(RAngleLoc);
2384 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2385 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002386
Douglas Gregore7c20652011-03-02 00:47:37 +00002387 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002388 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002389 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2390 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002391 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002392 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2393 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002394}
2395
Larisse Voufo39a1e502013-08-06 01:03:05 +00002396static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002397 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2398 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002399
2400static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2401 NamedDecl *PrevDecl,
2402 SourceLocation Loc,
2403 bool IsPartialSpecialization);
2404
2405static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002406
Richard Smith300e0c32013-09-24 04:49:23 +00002407static bool isTemplateArgumentTemplateParameter(
2408 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2409 switch (Arg.getKind()) {
2410 case TemplateArgument::Null:
2411 case TemplateArgument::NullPtr:
2412 case TemplateArgument::Integral:
2413 case TemplateArgument::Declaration:
2414 case TemplateArgument::Pack:
2415 case TemplateArgument::TemplateExpansion:
2416 return false;
2417
2418 case TemplateArgument::Type: {
2419 QualType Type = Arg.getAsType();
2420 const TemplateTypeParmType *TPT =
2421 Arg.getAsType()->getAs<TemplateTypeParmType>();
2422 return TPT && !Type.hasQualifiers() &&
2423 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2424 }
2425
2426 case TemplateArgument::Expression: {
2427 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2428 if (!DRE || !DRE->getDecl())
2429 return false;
2430 const NonTypeTemplateParmDecl *NTTP =
2431 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2432 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2433 }
2434
2435 case TemplateArgument::Template:
2436 const TemplateTemplateParmDecl *TTP =
2437 dyn_cast_or_null<TemplateTemplateParmDecl>(
2438 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2439 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2440 }
2441 llvm_unreachable("unexpected kind of template argument");
2442}
2443
2444static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2445 ArrayRef<TemplateArgument> Args) {
2446 if (Params->size() != Args.size())
2447 return false;
2448
2449 unsigned Depth = Params->getDepth();
2450
2451 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2452 TemplateArgument Arg = Args[I];
2453
2454 // If the parameter is a pack expansion, the argument must be a pack
2455 // whose only element is a pack expansion.
2456 if (Params->getParam(I)->isParameterPack()) {
2457 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2458 !Arg.pack_begin()->isPackExpansion())
2459 return false;
2460 Arg = Arg.pack_begin()->getPackExpansionPattern();
2461 }
2462
2463 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2464 return false;
2465 }
2466
2467 return true;
2468}
2469
Richard Smith4b55a9c2014-04-17 03:29:33 +00002470/// Convert the parser's template argument list representation into our form.
2471static TemplateArgumentListInfo
2472makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2473 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2474 TemplateId.RAngleLoc);
2475 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2476 TemplateId.NumArgs);
2477 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2478 return TemplateArgs;
2479}
2480
Larisse Voufo39a1e502013-08-06 01:03:05 +00002481DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002482 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002483 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002484 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002485 // D must be variable template id.
2486 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2487 "Variable template specialization is declared with a template it.");
2488
2489 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002490 TemplateArgumentListInfo TemplateArgs =
2491 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002492 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2493 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2494 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002495
Richard Smithbeef3452014-01-16 23:39:20 +00002496 TemplateName Name = TemplateId->Template.get();
2497
2498 // The template-id must name a variable template.
2499 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002500 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2501 if (!VarTemplate) {
2502 NamedDecl *FnTemplate;
2503 if (auto *OTS = Name.getAsOverloadedTemplate())
2504 FnTemplate = *OTS->begin();
2505 else
2506 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2507 if (FnTemplate)
2508 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2509 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002510 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2511 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002512 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002513
2514 // Check for unexpanded parameter packs in any of the template arguments.
2515 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2516 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2517 UPPC_PartialSpecialization))
2518 return true;
2519
2520 // Check that the template argument list is well-formed for this
2521 // template.
2522 SmallVector<TemplateArgument, 4> Converted;
2523 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2524 false, Converted))
2525 return true;
2526
Larisse Voufo39a1e502013-08-06 01:03:05 +00002527 // Find the variable template (partial) specialization declaration that
2528 // corresponds to these arguments.
2529 if (IsPartialSpecialization) {
2530 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002531 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2532 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002533 return true;
2534
2535 bool InstantiationDependent;
2536 if (!Name.isDependent() &&
2537 !TemplateSpecializationType::anyDependentTemplateArguments(
2538 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2539 InstantiationDependent)) {
2540 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2541 << VarTemplate->getDeclName();
2542 IsPartialSpecialization = false;
2543 }
Richard Smith300e0c32013-09-24 04:49:23 +00002544
2545 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2546 Converted)) {
2547 // C++ [temp.class.spec]p9b3:
2548 //
2549 // -- The argument list of the specialization shall not be identical
2550 // to the implicit argument list of the primary template.
2551 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2552 << /*variable template*/ 1
2553 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2554 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2555 // FIXME: Recover from this by treating the declaration as a redeclaration
2556 // of the primary template.
2557 return true;
2558 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002559 }
2560
Craig Topperc3ec1492014-05-26 06:22:03 +00002561 void *InsertPos = nullptr;
2562 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002563
2564 if (IsPartialSpecialization)
2565 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002566 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002567 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002568 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002569
Craig Topperc3ec1492014-05-26 06:22:03 +00002570 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002571
2572 // Check whether we can declare a variable template specialization in
2573 // the current scope.
2574 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2575 TemplateNameLoc,
2576 IsPartialSpecialization))
2577 return true;
2578
2579 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2580 // Since the only prior variable template specialization with these
2581 // arguments was referenced but not declared, reuse that
2582 // declaration node as our own, updating its source location and
2583 // the list of outer template parameters to reflect our new declaration.
2584 Specialization = PrevDecl;
2585 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002586 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002587 } else if (IsPartialSpecialization) {
2588 // Create a new class template partial specialization declaration node.
2589 VarTemplatePartialSpecializationDecl *PrevPartial =
2590 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002591 VarTemplatePartialSpecializationDecl *Partial =
2592 VarTemplatePartialSpecializationDecl::Create(
2593 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2594 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002595 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002596
2597 if (!PrevPartial)
2598 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2599 Specialization = Partial;
2600
2601 // If we are providing an explicit specialization of a member variable
2602 // template specialization, make a note of that.
2603 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002604 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002605
2606 // Check that all of the template parameters of the variable template
2607 // partial specialization are deducible from the template
2608 // arguments. If not, this variable template partial specialization
2609 // will never be used.
2610 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2611 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2612 TemplateParams->getDepth(), DeducibleParams);
2613
2614 if (!DeducibleParams.all()) {
2615 unsigned NumNonDeducible =
2616 DeducibleParams.size() - DeducibleParams.count();
2617 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002618 << /*variable template*/ 1 << (NumNonDeducible > 1)
2619 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002620 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2621 if (!DeducibleParams[I]) {
2622 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2623 if (Param->getDeclName())
2624 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2625 << Param->getDeclName();
2626 else
2627 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002628 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002629 }
2630 }
2631 }
2632 } else {
2633 // Create a new class template specialization declaration node for
2634 // this explicit specialization or friend declaration.
2635 Specialization = VarTemplateSpecializationDecl::Create(
2636 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2637 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2638 Specialization->setTemplateArgsInfo(TemplateArgs);
2639
2640 if (!PrevDecl)
2641 VarTemplate->AddSpecialization(Specialization, InsertPos);
2642 }
2643
2644 // C++ [temp.expl.spec]p6:
2645 // If a template, a member template or the member of a class template is
2646 // explicitly specialized then that specialization shall be declared
2647 // before the first use of that specialization that would cause an implicit
2648 // instantiation to take place, in every translation unit in which such a
2649 // use occurs; no diagnostic is required.
2650 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2651 bool Okay = false;
2652 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2653 // Is there any previous explicit specialization declaration?
2654 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2655 Okay = true;
2656 break;
2657 }
2658 }
2659
2660 if (!Okay) {
2661 SourceRange Range(TemplateNameLoc, RAngleLoc);
2662 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2663 << Name << Range;
2664
2665 Diag(PrevDecl->getPointOfInstantiation(),
2666 diag::note_instantiation_required_here)
2667 << (PrevDecl->getTemplateSpecializationKind() !=
2668 TSK_ImplicitInstantiation);
2669 return true;
2670 }
2671 }
2672
2673 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2674 Specialization->setLexicalDeclContext(CurContext);
2675
2676 // Add the specialization into its lexical context, so that it can
2677 // be seen when iterating through the list of declarations in that
2678 // context. However, specializations are not found by name lookup.
2679 CurContext->addDecl(Specialization);
2680
2681 // Note that this is an explicit specialization.
2682 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2683
2684 if (PrevDecl) {
2685 // Check that this isn't a redefinition of this specialization,
2686 // merging with previous declarations.
2687 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2688 ForRedeclaration);
2689 PrevSpec.addDecl(PrevDecl);
2690 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002691 } else if (Specialization->isStaticDataMember() &&
2692 Specialization->isOutOfLine()) {
2693 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002694 }
2695
2696 // Link instantiations of static data members back to the template from
2697 // which they were instantiated.
2698 if (Specialization->isStaticDataMember())
2699 Specialization->setInstantiationOfStaticDataMember(
2700 VarTemplate->getTemplatedDecl(),
2701 Specialization->getSpecializationKind());
2702
2703 return Specialization;
2704}
2705
2706namespace {
2707/// \brief A partial specialization whose template arguments have matched
2708/// a given template-id.
2709struct PartialSpecMatchResult {
2710 VarTemplatePartialSpecializationDecl *Partial;
2711 TemplateArgumentList *Args;
2712};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002713} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002714
2715DeclResult
2716Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2717 SourceLocation TemplateNameLoc,
2718 const TemplateArgumentListInfo &TemplateArgs) {
2719 assert(Template && "A variable template id without template?");
2720
2721 // Check that the template argument list is well-formed for this template.
2722 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002723 if (CheckTemplateArgumentList(
2724 Template, TemplateNameLoc,
2725 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002726 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002727 return true;
2728
2729 // Find the variable template specialization declaration that
2730 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002731 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002732 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002733 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002734 // If we already have a variable template specialization, return it.
2735 return Spec;
2736
2737 // This is the first time we have referenced this variable template
2738 // specialization. Create the canonical declaration and add it to
2739 // the set of specializations, based on the closest partial specialization
2740 // that it represents. That is,
2741 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2742 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2743 Converted.data(), Converted.size());
2744 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2745 bool AmbiguousPartialSpec = false;
2746 typedef PartialSpecMatchResult MatchResult;
2747 SmallVector<MatchResult, 4> Matched;
2748 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002749 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2750 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002751
2752 // 1. Attempt to find the closest partial specialization that this
2753 // specializes, if any.
2754 // If any of the template arguments is dependent, then this is probably
2755 // a placeholder for an incomplete declarative context; which must be
2756 // complete by instantiation time. Thus, do not search through the partial
2757 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002758 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2759 // Perhaps better after unification of DeduceTemplateArguments() and
2760 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002761 bool InstantiationDependent = false;
2762 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2763 TemplateArgs, InstantiationDependent)) {
2764
2765 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2766 Template->getPartialSpecializations(PartialSpecs);
2767
2768 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2769 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2770 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2771
2772 if (TemplateDeductionResult Result =
2773 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2774 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002775 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002776 FailedCandidates.addCandidate()
2777 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2778 (void)Result;
2779 } else {
2780 Matched.push_back(PartialSpecMatchResult());
2781 Matched.back().Partial = Partial;
2782 Matched.back().Args = Info.take();
2783 }
2784 }
2785
Larisse Voufo39a1e502013-08-06 01:03:05 +00002786 if (Matched.size() >= 1) {
2787 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2788 if (Matched.size() == 1) {
2789 // -- If exactly one matching specialization is found, the
2790 // instantiation is generated from that specialization.
2791 // We don't need to do anything for this.
2792 } else {
2793 // -- If more than one matching specialization is found, the
2794 // partial order rules (14.5.4.2) are used to determine
2795 // whether one of the specializations is more specialized
2796 // than the others. If none of the specializations is more
2797 // specialized than all of the other matching
2798 // specializations, then the use of the variable template is
2799 // ambiguous and the program is ill-formed.
2800 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2801 PEnd = Matched.end();
2802 P != PEnd; ++P) {
2803 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2804 PointOfInstantiation) ==
2805 P->Partial)
2806 Best = P;
2807 }
2808
2809 // Determine if the best partial specialization is more specialized than
2810 // the others.
2811 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2812 PEnd = Matched.end();
2813 P != PEnd; ++P) {
2814 if (P != Best && getMoreSpecializedPartialSpecialization(
2815 P->Partial, Best->Partial,
2816 PointOfInstantiation) != Best->Partial) {
2817 AmbiguousPartialSpec = true;
2818 break;
2819 }
2820 }
2821 }
2822
2823 // Instantiate using the best variable template partial specialization.
2824 InstantiationPattern = Best->Partial;
2825 InstantiationArgs = Best->Args;
2826 } else {
2827 // -- If no match is found, the instantiation is generated
2828 // from the primary template.
2829 // InstantiationPattern = Template->getTemplatedDecl();
2830 }
2831 }
2832
Larisse Voufo39a1e502013-08-06 01:03:05 +00002833 // 2. Create the canonical declaration.
2834 // Note that we do not instantiate the variable just yet, since
2835 // instantiation is handled in DoMarkVarDeclReferenced().
2836 // FIXME: LateAttrs et al.?
2837 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2838 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2839 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2840 if (!Decl)
2841 return true;
2842
2843 if (AmbiguousPartialSpec) {
2844 // Partial ordering did not produce a clear winner. Complain.
2845 Decl->setInvalidDecl();
2846 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2847 << Decl;
2848
2849 // Print the matching partial specializations.
2850 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2851 PEnd = Matched.end();
2852 P != PEnd; ++P)
2853 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2854 << getTemplateArgumentBindingsText(
2855 P->Partial->getTemplateParameters(), *P->Args);
2856 return true;
2857 }
2858
2859 if (VarTemplatePartialSpecializationDecl *D =
2860 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2861 Decl->setInstantiationOf(D, InstantiationArgs);
2862
2863 assert(Decl && "No variable template specialization?");
2864 return Decl;
2865}
2866
2867ExprResult
2868Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2869 const DeclarationNameInfo &NameInfo,
2870 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2871 const TemplateArgumentListInfo *TemplateArgs) {
2872
2873 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2874 *TemplateArgs);
2875 if (Decl.isInvalid())
2876 return ExprError();
2877
2878 VarDecl *Var = cast<VarDecl>(Decl.get());
2879 if (!Var->getTemplateSpecializationKind())
2880 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2881 NameInfo.getLoc());
2882
2883 // Build an ordinary singleton decl ref.
2884 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002885 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002886}
2887
John McCalldadc5752010-08-24 06:29:42 +00002888ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002889 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002890 LookupResult &R,
2891 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002892 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002893 // FIXME: Can we do any checking at this point? I guess we could check the
2894 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002895 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002896 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002897 // foo<int> could identify a single function unambiguously
2898 // This approach does NOT work, since f<int>(1);
2899 // gets resolved prior to resorting to overload resolution
2900 // i.e., template<class T> void f(double);
2901 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002902
2903 // These should be filtered out by our callers.
2904 assert(!R.empty() && "empty lookup results when building templateid");
2905 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2906
Larisse Voufo39a1e502013-08-06 01:03:05 +00002907 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002908 bool InstantiationDependent;
2909 if (R.getAsSingle<VarTemplateDecl>() &&
2910 !TemplateSpecializationType::anyDependentTemplateArguments(
2911 *TemplateArgs, InstantiationDependent)) {
2912 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2913 R.getAsSingle<VarTemplateDecl>(),
2914 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002915 }
2916
John McCall58cc69d2010-01-27 01:50:18 +00002917 // We don't want lookup warnings at this point.
2918 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
John McCalle66edc12009-11-24 19:00:30 +00002920 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002921 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002922 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002923 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002924 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002926 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002927
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002928 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002929}
2930
John McCalle66edc12009-11-24 19:00:30 +00002931// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002932ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002933Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002934 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002935 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002936 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002937
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002938 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002939 DeclContext *DC;
2940 if (!(DC = computeDeclContext(SS, false)) ||
2941 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002942 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002943 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002944
Douglas Gregor786123d2010-05-21 23:18:07 +00002945 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002946 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002947 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002948 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002949
John McCalle66edc12009-11-24 19:00:30 +00002950 if (R.isAmbiguous())
2951 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
John McCalle66edc12009-11-24 19:00:30 +00002953 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002954 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2955 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002956 return ExprError();
2957 }
2958
2959 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002960 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002961 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002962 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002963 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2964 return ExprError();
2965 }
2966
Abramo Bagnara7945c982012-01-27 09:46:47 +00002967 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002968}
2969
Douglas Gregorb67535d2009-03-31 00:43:58 +00002970/// \brief Form a dependent template name.
2971///
2972/// This action forms a dependent template name given the template
2973/// name and its (presumably dependent) scope specifier. For
2974/// example, given "MetaFun::template apply", the scope specifier \p
2975/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2976/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002977TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002978 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002979 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002980 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002981 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002982 bool EnteringContext,
2983 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002984 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2985 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002986 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002987 diag::warn_cxx98_compat_template_outside_of_template :
2988 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002989 << FixItHint::CreateRemoval(TemplateKWLoc);
2990
Craig Topperc3ec1492014-05-26 06:22:03 +00002991 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002992 if (SS.isSet())
2993 LookupCtx = computeDeclContext(SS, EnteringContext);
2994 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002995 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002996 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002997 // C++0x [temp.names]p5:
2998 // If a name prefixed by the keyword template is not the name of
2999 // a template, the program is ill-formed. [Note: the keyword
3000 // template may not be applied to non-template members of class
3001 // templates. -end note ] [ Note: as is the case with the
3002 // typename prefix, the template prefix is allowed in cases
3003 // where it is not strictly necessary; i.e., when the
3004 // nested-name-specifier or the expression on the left of the ->
3005 // or . is not dependent on a template-parameter, or the use
3006 // does not appear in the scope of a template. -end note]
3007 //
3008 // Note: C++03 was more strict here, because it banned the use of
3009 // the "template" keyword prior to a template-name that was not a
3010 // dependent name. C++ DR468 relaxed this requirement (the
3011 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003012 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003013 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003014 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003015 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003016 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003017 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3018 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003019 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3020 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003021 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003022 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003023 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003024 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003025 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003026 << Name.getSourceRange()
3027 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003028 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003029 } else {
3030 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003031 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003032 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003033 }
3034
Aaron Ballman4a979672014-01-03 13:56:08 +00003035 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036
Douglas Gregor3cf81312009-11-03 23:16:33 +00003037 switch (Name.getKind()) {
3038 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003040 Name.Identifier));
3041 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003042
Douglas Gregor71395fa2009-11-04 00:56:37 +00003043 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003044 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003045 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003046 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003047
3048 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003049 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003050
Douglas Gregor3cf81312009-11-03 23:16:33 +00003051 default:
3052 break;
3053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003055 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003056 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003057 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003058 << Name.getSourceRange()
3059 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003060 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003061}
3062
Mike Stump11289f42009-09-09 15:08:12 +00003063bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003064 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003065 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003066 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003067 QualType ArgType;
3068 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003069
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003070 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003071 switch(Arg.getKind()) {
3072 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003073 // C++ [temp.arg.type]p1:
3074 // A template-argument for a template-parameter which is a
3075 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003076 ArgType = Arg.getAsType();
3077 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003078 break;
3079 case TemplateArgument::Template: {
3080 // We have a template type parameter but the template argument
3081 // is a template without any arguments.
3082 SourceRange SR = AL.getSourceRange();
3083 TemplateName Name = Arg.getAsTemplate();
3084 Diag(SR.getBegin(), diag::err_template_missing_args)
3085 << Name << SR;
3086 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3087 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003088
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003089 return true;
3090 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003091 case TemplateArgument::Expression: {
3092 // We have a template type parameter but the template argument is an
3093 // expression; see if maybe it is missing the "typename" keyword.
3094 CXXScopeSpec SS;
3095 DeclarationNameInfo NameInfo;
3096
3097 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3098 SS.Adopt(ArgExpr->getQualifierLoc());
3099 NameInfo = ArgExpr->getNameInfo();
3100 } else if (DependentScopeDeclRefExpr *ArgExpr =
3101 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3102 SS.Adopt(ArgExpr->getQualifierLoc());
3103 NameInfo = ArgExpr->getNameInfo();
3104 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3105 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003106 if (ArgExpr->isImplicitAccess()) {
3107 SS.Adopt(ArgExpr->getQualifierLoc());
3108 NameInfo = ArgExpr->getMemberNameInfo();
3109 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003110 }
3111
Reid Kleckner377c1592014-06-10 23:29:48 +00003112 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003113 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3114 LookupParsedName(Result, CurScope, &SS);
3115
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003116 if (Result.getAsSingle<TypeDecl>() ||
3117 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003118 LookupResult::NotFoundInCurrentInstantiation) {
3119 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003120 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003121 Diag(Loc, getLangOpts().MSVCCompat
3122 ? diag::ext_ms_template_type_arg_missing_typename
3123 : diag::err_template_arg_must_be_type_suggest)
3124 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003125 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003126
3127 // Recover by synthesizing a type using the location information that we
3128 // already have.
3129 ArgType =
3130 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3131 TypeLocBuilder TLB;
3132 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3133 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3134 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3135 TL.setNameLoc(NameInfo.getLoc());
3136 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3137
3138 // Overwrite our input TemplateArgumentLoc so that we can recover
3139 // properly.
3140 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3141 TemplateArgumentLocInfo(TSI));
3142
3143 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003144 }
3145 }
3146 // fallthrough
3147 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003148 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003149 // We have a template type parameter but the template argument
3150 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003151 SourceRange SR = AL.getSourceRange();
3152 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003153 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003154
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003155 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003156 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003157 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003158
Reid Kleckner377c1592014-06-10 23:29:48 +00003159 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003160 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003161
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003162 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003163 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003164
3165 // Objective-C ARC:
3166 // If an explicitly-specified template argument type is a lifetime type
3167 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003168 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003169 ArgType->isObjCLifetimeType() &&
3170 !ArgType.getObjCLifetime()) {
3171 Qualifiers Qs;
3172 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3173 ArgType = Context.getQualifiedType(ArgType, Qs);
3174 }
3175
3176 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003177 return false;
3178}
3179
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003180/// \brief Substitute template arguments into the default template argument for
3181/// the given template type parameter.
3182///
3183/// \param SemaRef the semantic analysis object for which we are performing
3184/// the substitution.
3185///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003186/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003187/// for.
3188///
3189/// \param TemplateLoc the location of the template name that started the
3190/// template-id we are checking.
3191///
3192/// \param RAngleLoc the location of the right angle bracket ('>') that
3193/// terminates the template-id.
3194///
3195/// \param Param the template template parameter whose default we are
3196/// substituting into.
3197///
3198/// \param Converted the list of template arguments provided for template
3199/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003200/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003201static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003202SubstDefaultTemplateArgument(Sema &SemaRef,
3203 TemplateDecl *Template,
3204 SourceLocation TemplateLoc,
3205 SourceLocation RAngleLoc,
3206 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003207 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003208 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003209
3210 // If the argument type is dependent, instantiate it now based
3211 // on the previously-computed template arguments.
3212 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003213 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003214 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003215 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003216 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003217 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003218
David Majnemer89189202013-08-28 23:48:32 +00003219 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3220 Converted.data(), Converted.size());
3221
3222 // Only substitute for the innermost template argument list.
3223 MultiLevelTemplateArgumentList TemplateArgLists;
3224 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3225 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3226 TemplateArgLists.addOuterTemplateArguments(None);
3227
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003228 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003229 ArgType =
3230 SemaRef.SubstType(ArgType, TemplateArgLists,
3231 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003232 }
3233
3234 return ArgType;
3235}
3236
3237/// \brief Substitute template arguments into the default template argument for
3238/// the given non-type template parameter.
3239///
3240/// \param SemaRef the semantic analysis object for which we are performing
3241/// the substitution.
3242///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003244/// for.
3245///
3246/// \param TemplateLoc the location of the template name that started the
3247/// template-id we are checking.
3248///
3249/// \param RAngleLoc the location of the right angle bracket ('>') that
3250/// terminates the template-id.
3251///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003252/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003253/// substituting into.
3254///
3255/// \param Converted the list of template arguments provided for template
3256/// parameters that precede \p Param in the template parameter list.
3257///
3258/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003259static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003260SubstDefaultTemplateArgument(Sema &SemaRef,
3261 TemplateDecl *Template,
3262 SourceLocation TemplateLoc,
3263 SourceLocation RAngleLoc,
3264 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003265 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003266 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003267 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003268 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003269 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003270 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003271
David Majnemer89189202013-08-28 23:48:32 +00003272 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3273 Converted.data(), Converted.size());
3274
3275 // Only substitute for the innermost template argument list.
3276 MultiLevelTemplateArgumentList TemplateArgLists;
3277 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3278 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3279 TemplateArgLists.addOuterTemplateArguments(None);
3280
Faisal Vali48401eb2015-11-19 19:20:17 +00003281 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3282 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003283 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003284}
3285
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003286/// \brief Substitute template arguments into the default template argument for
3287/// the given template template parameter.
3288///
3289/// \param SemaRef the semantic analysis object for which we are performing
3290/// the substitution.
3291///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003292/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003293/// for.
3294///
3295/// \param TemplateLoc the location of the template name that started the
3296/// template-id we are checking.
3297///
3298/// \param RAngleLoc the location of the right angle bracket ('>') that
3299/// terminates the template-id.
3300///
3301/// \param Param the template template parameter whose default we are
3302/// substituting into.
3303///
3304/// \param Converted the list of template arguments provided for template
3305/// parameters that precede \p Param in the template parameter list.
3306///
Douglas Gregordf846d12011-03-02 18:46:51 +00003307/// \param QualifierLoc Will be set to the nested-name-specifier (with
3308/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003309///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003310/// \returns the substituted template argument, or NULL if an error occurred.
3311static TemplateName
3312SubstDefaultTemplateArgument(Sema &SemaRef,
3313 TemplateDecl *Template,
3314 SourceLocation TemplateLoc,
3315 SourceLocation RAngleLoc,
3316 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003317 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003318 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003319 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003320 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003321 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003322 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323
David Majnemer89189202013-08-28 23:48:32 +00003324 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3325 Converted.data(), Converted.size());
3326
3327 // Only substitute for the innermost template argument list.
3328 MultiLevelTemplateArgumentList TemplateArgLists;
3329 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3330 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3331 TemplateArgLists.addOuterTemplateArguments(None);
3332
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003333 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003334 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003335 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003336 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003337 QualifierLoc =
3338 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003339 if (!QualifierLoc)
3340 return TemplateName();
3341 }
David Majnemer89189202013-08-28 23:48:32 +00003342
3343 return SemaRef.SubstTemplateName(
3344 QualifierLoc,
3345 Param->getDefaultArgument().getArgument().getAsTemplate(),
3346 Param->getDefaultArgument().getTemplateNameLoc(),
3347 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003348}
3349
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003350/// \brief If the given template parameter has a default template
3351/// argument, substitute into that default template argument and
3352/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003354Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3355 SourceLocation TemplateLoc,
3356 SourceLocation RAngleLoc,
3357 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003358 SmallVectorImpl<TemplateArgument>
3359 &Converted,
3360 bool &HasDefaultArg) {
3361 HasDefaultArg = false;
3362
3363 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003364 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003365 return TemplateArgumentLoc();
3366
Richard Smithc87b9382013-07-04 01:01:24 +00003367 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003368 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003369 TemplateLoc,
3370 RAngleLoc,
3371 TypeParm,
3372 Converted);
3373 if (DI)
3374 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3375
3376 return TemplateArgumentLoc();
3377 }
3378
3379 if (NonTypeTemplateParmDecl *NonTypeParm
3380 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003381 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003382 return TemplateArgumentLoc();
3383
Richard Smithc87b9382013-07-04 01:01:24 +00003384 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003385 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003386 TemplateLoc,
3387 RAngleLoc,
3388 NonTypeParm,
3389 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003390 if (Arg.isInvalid())
3391 return TemplateArgumentLoc();
3392
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003393 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003394 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3395 }
3396
3397 TemplateTemplateParmDecl *TempTempParm
3398 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003399 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003400 return TemplateArgumentLoc();
3401
Richard Smithc87b9382013-07-04 01:01:24 +00003402 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003403 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003404 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003406 RAngleLoc,
3407 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003408 Converted,
3409 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003410 if (TName.isNull())
3411 return TemplateArgumentLoc();
3412
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003414 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003415 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3416}
3417
Douglas Gregorda0fb532009-11-11 19:31:23 +00003418/// \brief Check that the given template argument corresponds to the given
3419/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003420///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003422/// checked.
3423///
Richard Trieu15b66532015-01-24 02:48:32 +00003424/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003425///
3426/// \param Template The template in which the template argument resides.
3427///
3428/// \param TemplateLoc The location of the template name for the template
3429/// whose argument list we're matching.
3430///
3431/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3432/// the template argument list.
3433///
3434/// \param ArgumentPackIndex The index into the argument pack where this
3435/// argument will be placed. Only valid if the parameter is a parameter pack.
3436///
3437/// \param Converted The checked, converted argument will be added to the
3438/// end of this small vector.
3439///
3440/// \param CTAK Describes how we arrived at this particular template argument:
3441/// explicitly written, deduced, etc.
3442///
3443/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003444bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003445 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003446 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003447 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003448 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003449 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003450 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003451 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003452 // Check template type parameters.
3453 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003454 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Douglas Gregoreebed722009-11-11 19:41:09 +00003456 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003458 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003459 // with the template arguments we've seen thus far. But if the
3460 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003461 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003462 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3463 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464
Peter Collingbourne01687632010-12-10 17:08:53 +00003465 if (NTTPType->isDependentType() &&
3466 !isa<TemplateTemplateParmDecl>(Template) &&
3467 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003468 // Do substitution on the type of the non-type template parameter.
3469 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003470 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003471 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003472 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003473 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003474
3475 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003476 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003477 NTTPType = SubstType(NTTPType,
3478 MultiLevelTemplateArgumentList(TemplateArgs),
3479 NTTP->getLocation(),
3480 NTTP->getDeclName());
3481 // If that worked, check the non-type template parameter type
3482 // for validity.
3483 if (!NTTPType.isNull())
3484 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3485 NTTP->getLocation());
3486 if (NTTPType.isNull())
3487 return true;
3488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregorda0fb532009-11-11 19:31:23 +00003490 switch (Arg.getArgument().getKind()) {
3491 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003492 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493
Douglas Gregorda0fb532009-11-11 19:31:23 +00003494 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003495 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003496 ExprResult Res =
3497 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3498 Result, CTAK);
3499 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003500 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Richard Trieu15b66532015-01-24 02:48:32 +00003502 // If the resulting expression is new, then use it in place of the
3503 // old expression in the template argument.
3504 if (Res.get() != Arg.getArgument().getAsExpr()) {
3505 TemplateArgument TA(Res.get());
3506 Arg = TemplateArgumentLoc(TA, Res.get());
3507 }
3508
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003509 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003510 break;
3511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512
Douglas Gregorda0fb532009-11-11 19:31:23 +00003513 case TemplateArgument::Declaration:
3514 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003515 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003516 // We've already checked this template argument, so just copy
3517 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003518 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003519 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520
Douglas Gregorda0fb532009-11-11 19:31:23 +00003521 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003522 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003523 // We were given a template template argument. It may not be ill-formed;
3524 // see below.
3525 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003526 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3527 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003528 // We have a template argument such as \c T::template X, which we
3529 // parsed as a template template argument. However, since we now
3530 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003531 // template name into an expression.
3532
3533 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3534 Arg.getTemplateNameLoc());
3535
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003536 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003537 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003538 // FIXME: the template-template arg was a DependentTemplateName,
3539 // so it was provided with a template keyword. However, its source
3540 // location is not stored in the template argument structure.
3541 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003542 ExprResult E = DependentScopeDeclRefExpr::Create(
3543 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3544 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003546 // If we parsed the template argument as a pack expansion, create a
3547 // pack expansion expression.
3548 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003549 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003550 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003551 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553
Douglas Gregorda0fb532009-11-11 19:31:23 +00003554 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003555 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003556 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003557 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003559 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560 break;
3561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562
Douglas Gregorda0fb532009-11-11 19:31:23 +00003563 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003564 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003565 // therefore cannot be a non-type template argument.
3566 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3567 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568
Douglas Gregorda0fb532009-11-11 19:31:23 +00003569 Diag(Param->getLocation(), diag::note_template_param_here);
3570 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregorda0fb532009-11-11 19:31:23 +00003572 case TemplateArgument::Type: {
3573 // We have a non-type template parameter but the template
3574 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Douglas Gregorda0fb532009-11-11 19:31:23 +00003576 // C++ [temp.arg]p2:
3577 // In a template-argument, an ambiguity between a type-id and
3578 // an expression is resolved to a type-id, regardless of the
3579 // form of the corresponding template-parameter.
3580 //
3581 // We warn specifically about this case, since it can be rather
3582 // confusing for users.
3583 QualType T = Arg.getArgument().getAsType();
3584 SourceRange SR = Arg.getSourceRange();
3585 if (T->isFunctionType())
3586 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3587 else
3588 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3589 Diag(Param->getLocation(), diag::note_template_param_here);
3590 return true;
3591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Douglas Gregorda0fb532009-11-11 19:31:23 +00003593 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003594 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregorda0fb532009-11-11 19:31:23 +00003597 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598 }
3599
3600
Douglas Gregorda0fb532009-11-11 19:31:23 +00003601 // Check template template parameters.
3602 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Douglas Gregorda0fb532009-11-11 19:31:23 +00003604 // Substitute into the template parameter list of the template
3605 // template parameter, since previously-supplied template arguments
3606 // may appear within the template template parameter.
3607 {
3608 // Set up a template instantiation context.
3609 LocalInstantiationScope Scope(*this);
3610 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003611 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003612 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003613 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003614 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
3616 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003617 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003618 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003620 MultiLevelTemplateArgumentList(TemplateArgs)));
3621 if (!TempParm)
3622 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624
Douglas Gregorda0fb532009-11-11 19:31:23 +00003625 switch (Arg.getArgument().getKind()) {
3626 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003627 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregorda0fb532009-11-11 19:31:23 +00003629 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003630 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003631 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003632 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003633
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003634 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003635 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636
Douglas Gregorda0fb532009-11-11 19:31:23 +00003637 case TemplateArgument::Expression:
3638 case TemplateArgument::Type:
3639 // We have a template template parameter but the template
3640 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003641 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003642 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003643 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644
Douglas Gregorda0fb532009-11-11 19:31:23 +00003645 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003646 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003647 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003648 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003649 case TemplateArgument::NullPtr:
3650 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651
Douglas Gregorda0fb532009-11-11 19:31:23 +00003652 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003653 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Douglas Gregorda0fb532009-11-11 19:31:23 +00003656 return false;
3657}
3658
Douglas Gregor8e072612012-02-03 07:34:46 +00003659/// \brief Diagnose an arity mismatch in the
3660static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3661 SourceLocation TemplateLoc,
3662 TemplateArgumentListInfo &TemplateArgs) {
3663 TemplateParameterList *Params = Template->getTemplateParameters();
3664 unsigned NumParams = Params->size();
3665 unsigned NumArgs = TemplateArgs.size();
3666
3667 SourceRange Range;
3668 if (NumArgs > NumParams)
3669 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3670 TemplateArgs.getRAngleLoc());
3671 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3672 << (NumArgs > NumParams)
3673 << (isa<ClassTemplateDecl>(Template)? 0 :
3674 isa<FunctionTemplateDecl>(Template)? 1 :
3675 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3676 << Template << Range;
3677 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3678 << Params->getSourceRange();
3679 return true;
3680}
3681
Richard Smith1fde8ec2012-09-07 02:06:42 +00003682/// \brief Check whether the template parameter is a pack expansion, and if so,
3683/// determine the number of parameters produced by that expansion. For instance:
3684///
3685/// \code
3686/// template<typename ...Ts> struct A {
3687/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3688/// };
3689/// \endcode
3690///
3691/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3692/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003693static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003694 if (NonTypeTemplateParmDecl *NTTP
3695 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3696 if (NTTP->isExpandedParameterPack())
3697 return NTTP->getNumExpansionTypes();
3698 }
3699
3700 if (TemplateTemplateParmDecl *TTP
3701 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3702 if (TTP->isExpandedParameterPack())
3703 return TTP->getNumExpansionTemplateParameters();
3704 }
3705
David Blaikie7a30dc52013-02-21 01:47:18 +00003706 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003707}
3708
Richard Smith35c1df52015-06-17 20:16:32 +00003709/// Diagnose a missing template argument.
3710template<typename TemplateParmDecl>
3711static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3712 TemplateDecl *TD,
3713 const TemplateParmDecl *D,
3714 TemplateArgumentListInfo &Args) {
3715 // Dig out the most recent declaration of the template parameter; there may be
3716 // declarations of the template that are more recent than TD.
3717 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3718 ->getTemplateParameters()
3719 ->getParam(D->getIndex()));
3720
3721 // If there's a default argument that's not visible, diagnose that we're
3722 // missing a module import.
3723 llvm::SmallVector<Module*, 8> Modules;
3724 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3725 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3726 D->getDefaultArgumentLoc(), Modules,
3727 Sema::MissingImportKind::DefaultArgument,
3728 /*Recover*/ true);
3729 return true;
3730 }
3731
3732 // FIXME: If there's a more recent default argument that *is* visible,
3733 // diagnose that it was declared too late.
3734
3735 return diagnoseArityMismatch(S, TD, Loc, Args);
3736}
3737
Douglas Gregord32e0282009-02-09 23:23:08 +00003738/// \brief Check that the given template argument list is well-formed
3739/// for specializing the given template.
3740bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3741 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003742 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003743 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003744 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003745 // Make a copy of the template arguments for processing. Only make the
3746 // changes at the end when successful in matching the arguments to the
3747 // template.
3748 TemplateArgumentListInfo NewArgs = TemplateArgs;
3749
Douglas Gregord32e0282009-02-09 23:23:08 +00003750 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003751
Richard Trieu15b66532015-01-24 02:48:32 +00003752 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003753
Mike Stump11289f42009-09-09 15:08:12 +00003754 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003755 // [...] The type and form of each template-argument specified in
3756 // a template-id shall match the type and form specified for the
3757 // corresponding parameter declared by the template in its
3758 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003759 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003760 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003761 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003762 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003763 for (TemplateParameterList::iterator Param = Params->begin(),
3764 ParamEnd = Params->end();
3765 Param != ParamEnd; /* increment in loop */) {
3766 // If we have an expanded parameter pack, make sure we don't have too
3767 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003768 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003769 if (*Expansions == ArgumentPack.size()) {
3770 // We're done with this parameter pack. Pack up its arguments and add
3771 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003772 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003773 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003774 ArgumentPack.clear();
3775
Richard Smith1fde8ec2012-09-07 02:06:42 +00003776 // This argument is assigned to the next parameter.
3777 ++Param;
3778 continue;
3779 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3780 // Not enough arguments for this parameter pack.
3781 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3782 << false
3783 << (isa<ClassTemplateDecl>(Template)? 0 :
3784 isa<FunctionTemplateDecl>(Template)? 1 :
3785 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3786 << Template;
3787 Diag(Template->getLocation(), diag::note_template_decl_here)
3788 << Params->getSourceRange();
3789 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003790 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003792
Richard Smith1fde8ec2012-09-07 02:06:42 +00003793 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003794 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003795 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003797 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003798 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003799
Richard Smith96d71c32014-11-12 23:38:38 +00003800 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003801 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003802 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3803 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003804 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003805 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003806 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003807 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003808 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003809 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003810 Diag((*Param)->getLocation(), diag::note_template_param_here);
3811 return true;
3812 }
3813
Richard Smith1fde8ec2012-09-07 02:06:42 +00003814 // We're now done with this argument.
3815 ++ArgIdx;
3816
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003817 if ((*Param)->isTemplateParameterPack()) {
3818 // The template parameter was a template parameter pack, so take the
3819 // deduced argument and place it on the argument pack. Note that we
3820 // stay on the same template parameter so that we can deduce more
3821 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003822 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003823 } else {
3824 // Move to the next template parameter.
3825 ++Param;
3826 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003827
Richard Smith96d71c32014-11-12 23:38:38 +00003828 // If we just saw a pack expansion into a non-pack, then directly convert
3829 // the remaining arguments, because we don't know what parameters they'll
3830 // match up with.
3831 if (PackExpansionIntoNonPack) {
3832 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003833 // If we were part way through filling in an expanded parameter pack,
3834 // fall back to just producing individual arguments.
3835 Converted.insert(Converted.end(),
3836 ArgumentPack.begin(), ArgumentPack.end());
3837 ArgumentPack.clear();
3838 }
3839
3840 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003841 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003842 ++ArgIdx;
3843 }
3844
Richard Smith1fde8ec2012-09-07 02:06:42 +00003845 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003846 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003847
Douglas Gregor84d49a22009-11-11 21:54:23 +00003848 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
Douglas Gregor2f157c92011-06-03 02:59:40 +00003851 // If we're checking a partial template argument list, we're done.
3852 if (PartialTemplateArgs) {
3853 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003854 Converted.push_back(
3855 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3856
Richard Smith1fde8ec2012-09-07 02:06:42 +00003857 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003858 }
3859
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003861 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003862 if ((*Param)->isTemplateParameterPack()) {
3863 assert(!getExpandedPackSize(*Param) &&
3864 "Should have dealt with this already");
3865
3866 // A non-expanded parameter pack before the end of the parameter list
3867 // only occurs for an ill-formed template parameter list, unless we've
3868 // got a partial argument list for a function template, so just bail out.
3869 if (Param + 1 != ParamEnd)
3870 return true;
3871
Benjamin Kramercce63472015-08-05 09:40:22 +00003872 Converted.push_back(
3873 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003874 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003875
3876 ++Param;
3877 continue;
3878 }
3879
Douglas Gregor8e072612012-02-03 07:34:46 +00003880 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003881 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882
Douglas Gregor84d49a22009-11-11 21:54:23 +00003883 // Retrieve the default template argument from the template
3884 // parameter. For each kind of template parameter, we substitute the
3885 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003887 // the default argument.
3888 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003889 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003890 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3891 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003892
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003894 Template,
3895 TemplateLoc,
3896 RAngleLoc,
3897 TTP,
3898 Converted);
3899 if (!ArgType)
3900 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901
Douglas Gregor84d49a22009-11-11 21:54:23 +00003902 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3903 ArgType);
3904 } else if (NonTypeTemplateParmDecl *NTTP
3905 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003906 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003907 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3908 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003909
John McCalldadc5752010-08-24 06:29:42 +00003910 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 TemplateLoc,
3912 RAngleLoc,
3913 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003914 Converted);
3915 if (E.isInvalid())
3916 return true;
3917
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003918 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003919 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3920 } else {
3921 TemplateTemplateParmDecl *TempParm
3922 = cast<TemplateTemplateParmDecl>(*Param);
3923
Richard Smith95d83952015-06-10 20:36:34 +00003924 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003925 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3926 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003927
Douglas Gregordf846d12011-03-02 18:46:51 +00003928 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003929 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930 TemplateLoc,
3931 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003932 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003933 Converted,
3934 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003935 if (Name.isNull())
3936 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
Douglas Gregor9d802122011-03-02 17:09:35 +00003938 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3939 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941
Douglas Gregor84d49a22009-11-11 21:54:23 +00003942 // Introduce an instantiation record that describes where we are using
3943 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003944 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3945 SourceRange(TemplateLoc, RAngleLoc));
3946 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003947 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
Douglas Gregor84d49a22009-11-11 21:54:23 +00003949 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003950 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003951 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003952 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953
Richard Trieu15b66532015-01-24 02:48:32 +00003954 // Core issue 150 (assumed resolution): if this is a template template
3955 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003956 // template definition.
3957 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003958 NewArgs.addArgument(Arg);
3959
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003960 // Move to the next template parameter and argument.
3961 ++Param;
3962 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003964
Richard Smith07f79912014-06-06 16:00:50 +00003965 // If we're performing a partial argument substitution, allow any trailing
3966 // pack expansions; they might be empty. This can happen even if
3967 // PartialTemplateArgs is false (the list of arguments is complete but
3968 // still dependent).
3969 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3970 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003971 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3972 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003973 }
3974
Douglas Gregor8e072612012-02-03 07:34:46 +00003975 // If we have any leftover arguments, then there were too many arguments.
3976 // Complain and fail.
3977 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003978 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3979
3980 // No problems found with the new argument list, propagate changes back
3981 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00003982 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983
Richard Smith1fde8ec2012-09-07 02:06:42 +00003984 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003985}
3986
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003987namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988 class UnnamedLocalNoLinkageFinder
3989 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003990 {
3991 Sema &S;
3992 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003994 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003995
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003996 public:
3997 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3998
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999 bool Visit(QualType T) {
4000 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004003#define TYPE(Class, Parent) \
4004 bool Visit##Class##Type(const Class##Type *);
4005#define ABSTRACT_TYPE(Class, Parent) \
4006 bool Visit##Class##Type(const Class##Type *) { return false; }
4007#define NON_CANONICAL_TYPE(Class, Parent) \
4008 bool Visit##Class##Type(const Class##Type *) { return false; }
4009#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004011 bool VisitTagDecl(const TagDecl *Tag);
4012 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4013 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004014} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004015
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004017 return false;
4018}
4019
4020bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4021 return Visit(T->getElementType());
4022}
4023
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004025 return Visit(T->getPointeeType());
4026}
4027
4028bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004029 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004030 return Visit(T->getPointeeType());
4031}
4032
4033bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004034 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004035 return Visit(T->getPointeeType());
4036}
4037
4038bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004040 return Visit(T->getPointeeType());
4041}
4042
4043bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004045 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4046}
4047
4048bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004050 return Visit(T->getElementType());
4051}
4052
4053bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004055 return Visit(T->getElementType());
4056}
4057
4058bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004060 return Visit(T->getElementType());
4061}
4062
4063bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004064 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004065 return Visit(T->getElementType());
4066}
4067
4068bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004070 return Visit(T->getElementType());
4071}
4072
4073bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4074 return Visit(T->getElementType());
4075}
4076
4077bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4078 return Visit(T->getElementType());
4079}
4080
4081bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4082 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004083 for (const auto &A : T->param_types()) {
4084 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004085 return true;
4086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087
Alp Toker314cc812014-01-25 16:55:45 +00004088 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004089}
4090
4091bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4092 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004093 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004094}
4095
4096bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4097 const UnresolvedUsingType*) {
4098 return false;
4099}
4100
4101bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4102 return false;
4103}
4104
4105bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4106 return Visit(T->getUnderlyingType());
4107}
4108
4109bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4110 return false;
4111}
4112
Alexis Hunte852b102011-05-24 22:41:36 +00004113bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4114 const UnaryTransformType*) {
4115 return false;
4116}
4117
Richard Smith30482bc2011-02-20 03:19:35 +00004118bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4119 return Visit(T->getDeducedType());
4120}
4121
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004122bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4123 return VisitTagDecl(T->getDecl());
4124}
4125
4126bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4127 return VisitTagDecl(T->getDecl());
4128}
4129
4130bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4131 const TemplateTypeParmType*) {
4132 return false;
4133}
4134
Douglas Gregorada4b792011-01-14 02:55:32 +00004135bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4136 const SubstTemplateTypeParmPackType *) {
4137 return false;
4138}
4139
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004140bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4141 const TemplateSpecializationType*) {
4142 return false;
4143}
4144
4145bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4146 const InjectedClassNameType* T) {
4147 return VisitTagDecl(T->getDecl());
4148}
4149
4150bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4151 const DependentNameType* T) {
4152 return VisitNestedNameSpecifier(T->getQualifier());
4153}
4154
4155bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4156 const DependentTemplateSpecializationType* T) {
4157 return VisitNestedNameSpecifier(T->getQualifier());
4158}
4159
Douglas Gregord2fa7662010-12-20 02:24:11 +00004160bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4161 const PackExpansionType* T) {
4162 return Visit(T->getPattern());
4163}
4164
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004165bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4166 return false;
4167}
4168
4169bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4170 const ObjCInterfaceType *) {
4171 return false;
4172}
4173
4174bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4175 const ObjCObjectPointerType *) {
4176 return false;
4177}
4178
Eli Friedman0dfb8892011-10-06 23:00:33 +00004179bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4180 return Visit(T->getValueType());
4181}
4182
Xiuli Pan9c14e282016-01-09 12:53:17 +00004183bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4184 return false;
4185}
4186
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004187bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4188 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004189 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004190 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004191 diag::warn_cxx98_compat_template_arg_local_type :
4192 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004193 << S.Context.getTypeDeclType(Tag) << SR;
4194 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004195 }
4196
John McCall5ea95772013-03-09 00:54:27 +00004197 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004198 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004199 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004200 diag::warn_cxx98_compat_template_arg_unnamed_type :
4201 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004202 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4203 return true;
4204 }
4205
4206 return false;
4207}
4208
4209bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4210 NestedNameSpecifier *NNS) {
4211 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4212 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004213
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004214 switch (NNS->getKind()) {
4215 case NestedNameSpecifier::Identifier:
4216 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004217 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004218 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004219 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004220 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004221
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004222 case NestedNameSpecifier::TypeSpec:
4223 case NestedNameSpecifier::TypeSpecWithTemplate:
4224 return Visit(QualType(NNS->getAsType(), 0));
4225 }
David Blaikie8a40f702012-01-17 06:56:22 +00004226 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004227}
4228
Douglas Gregord32e0282009-02-09 23:23:08 +00004229/// \brief Check a template argument against its corresponding
4230/// template type parameter.
4231///
4232/// This routine implements the semantics of C++ [temp.arg.type]. It
4233/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004234bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004235 TypeSourceInfo *ArgInfo) {
4236 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004237 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004238 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004239
4240 if (Arg->isVariablyModifiedType()) {
4241 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004242 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004243 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004244 }
4245
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004246 // C++03 [temp.arg.type]p2:
4247 // A local type, a type with no linkage, an unnamed type or a type
4248 // compounded from any of these types shall not be used as a
4249 // template-argument for a template type-parameter.
4250 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004251 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004252 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004253 bool NeedsCheck;
4254 if (LangOpts.CPlusPlus11)
4255 NeedsCheck =
4256 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4257 SR.getBegin()) ||
4258 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4259 SR.getBegin());
4260 else
4261 NeedsCheck = Arg->hasUnnamedOrLocalType();
4262
4263 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004264 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4265 (void)Finder.Visit(Context.getCanonicalType(Arg));
4266 }
4267
Douglas Gregord32e0282009-02-09 23:23:08 +00004268 return false;
4269}
4270
Douglas Gregor20fdef32012-04-10 17:08:25 +00004271enum NullPointerValueKind {
4272 NPV_NotNullPointer,
4273 NPV_NullPointer,
4274 NPV_Error
4275};
4276
4277/// \brief Determine whether the given template argument is a null pointer
4278/// value of the appropriate type.
4279static NullPointerValueKind
4280isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4281 QualType ParamType, Expr *Arg) {
4282 if (Arg->isValueDependent() || Arg->isTypeDependent())
4283 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004284
Richard Smithdb0ac552015-12-18 22:40:25 +00004285 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004286 llvm_unreachable(
4287 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004288
David Majnemer5c734ad2014-08-14 00:49:23 +00004289 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004290 return NPV_NotNullPointer;
4291
4292 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004293 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4294 if (ArgRV.isInvalid())
4295 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004296 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004297
Douglas Gregor20fdef32012-04-10 17:08:25 +00004298 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004299 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004300 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004301 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004302 EvalResult.HasSideEffects) {
4303 SourceLocation DiagLoc = Arg->getExprLoc();
4304
4305 // If our only note is the usual "invalid subexpression" note, just point
4306 // the caret at its location rather than producing an essentially
4307 // redundant note.
4308 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4309 diag::note_invalid_subexpr_in_const_expr) {
4310 DiagLoc = Notes[0].first;
4311 Notes.clear();
4312 }
4313
4314 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4315 << Arg->getType() << Arg->getSourceRange();
4316 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4317 S.Diag(Notes[I].first, Notes[I].second);
4318
4319 S.Diag(Param->getLocation(), diag::note_template_param_here);
4320 return NPV_Error;
4321 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004322
4323 // C++11 [temp.arg.nontype]p1:
4324 // - an address constant expression of type std::nullptr_t
4325 if (Arg->getType()->isNullPtrType())
4326 return NPV_NullPointer;
4327
4328 // - a constant expression that evaluates to a null pointer value (4.10); or
4329 // - a constant expression that evaluates to a null member pointer value
4330 // (4.11); or
4331 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4332 (EvalResult.Val.isMemberPointer() &&
4333 !EvalResult.Val.getMemberPointerDecl())) {
4334 // If our expression has an appropriate type, we've succeeded.
4335 bool ObjCLifetimeConversion;
4336 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4337 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4338 ObjCLifetimeConversion))
4339 return NPV_NullPointer;
4340
4341 // The types didn't match, but we know we got a null pointer; complain,
4342 // then recover as if the types were correct.
4343 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4344 << Arg->getType() << ParamType << Arg->getSourceRange();
4345 S.Diag(Param->getLocation(), diag::note_template_param_here);
4346 return NPV_NullPointer;
4347 }
4348
4349 // If we don't have a null pointer value, but we do have a NULL pointer
4350 // constant, suggest a cast to the appropriate type.
4351 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4352 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4353 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004354 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4355 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4356 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004357 S.Diag(Param->getLocation(), diag::note_template_param_here);
4358 return NPV_NullPointer;
4359 }
4360
4361 // FIXME: If we ever want to support general, address-constant expressions
4362 // as non-type template arguments, we should return the ExprResult here to
4363 // be interpreted by the caller.
4364 return NPV_NotNullPointer;
4365}
4366
David Majnemer61c39a12013-08-23 05:39:39 +00004367/// \brief Checks whether the given template argument is compatible with its
4368/// template parameter.
4369static bool CheckTemplateArgumentIsCompatibleWithParameter(
4370 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4371 Expr *Arg, QualType ArgType) {
4372 bool ObjCLifetimeConversion;
4373 if (ParamType->isPointerType() &&
4374 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4375 S.IsQualificationConversion(ArgType, ParamType, false,
4376 ObjCLifetimeConversion)) {
4377 // For pointer-to-object types, qualification conversions are
4378 // permitted.
4379 } else {
4380 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4381 if (!ParamRef->getPointeeType()->isFunctionType()) {
4382 // C++ [temp.arg.nontype]p5b3:
4383 // For a non-type template-parameter of type reference to
4384 // object, no conversions apply. The type referred to by the
4385 // reference may be more cv-qualified than the (otherwise
4386 // identical) type of the template- argument. The
4387 // template-parameter is bound directly to the
4388 // template-argument, which shall be an lvalue.
4389
4390 // FIXME: Other qualifiers?
4391 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4392 unsigned ArgQuals = ArgType.getCVRQualifiers();
4393
4394 if ((ParamQuals | ArgQuals) != ParamQuals) {
4395 S.Diag(Arg->getLocStart(),
4396 diag::err_template_arg_ref_bind_ignores_quals)
4397 << ParamType << Arg->getType() << Arg->getSourceRange();
4398 S.Diag(Param->getLocation(), diag::note_template_param_here);
4399 return true;
4400 }
4401 }
4402 }
4403
4404 // At this point, the template argument refers to an object or
4405 // function with external linkage. We now need to check whether the
4406 // argument and parameter types are compatible.
4407 if (!S.Context.hasSameUnqualifiedType(ArgType,
4408 ParamType.getNonReferenceType())) {
4409 // We can't perform this conversion or binding.
4410 if (ParamType->isReferenceType())
4411 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4412 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4413 else
4414 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4415 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4416 S.Diag(Param->getLocation(), diag::note_template_param_here);
4417 return true;
4418 }
4419 }
4420
4421 return false;
4422}
4423
Douglas Gregorccb07762009-02-11 19:52:55 +00004424/// \brief Checks whether the given template argument is the address
4425/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004427CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4428 NonTypeTemplateParmDecl *Param,
4429 QualType ParamType,
4430 Expr *ArgIn,
4431 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004432 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004433 Expr *Arg = ArgIn;
4434 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004435
Douglas Gregorb242683d2010-04-01 18:32:35 +00004436 bool AddressTaken = false;
4437 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004438 if (S.getLangOpts().MicrosoftExt) {
4439 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4440 // dereference and address-of operators.
4441 Arg = Arg->IgnoreParenCasts();
4442
4443 bool ExtWarnMSTemplateArg = false;
4444 UnaryOperatorKind FirstOpKind;
4445 SourceLocation FirstOpLoc;
4446 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4447 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4448 if (UnOpKind == UO_Deref)
4449 ExtWarnMSTemplateArg = true;
4450 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4451 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4452 if (!AddrOpLoc.isValid()) {
4453 FirstOpKind = UnOpKind;
4454 FirstOpLoc = UnOp->getOperatorLoc();
4455 }
4456 } else
4457 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004458 }
David Majnemer61c39a12013-08-23 05:39:39 +00004459 if (FirstOpLoc.isValid()) {
4460 if (ExtWarnMSTemplateArg)
4461 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4462 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004463
David Majnemer61c39a12013-08-23 05:39:39 +00004464 if (FirstOpKind == UO_AddrOf)
4465 AddressTaken = true;
4466 else if (Arg->getType()->isPointerType()) {
4467 // We cannot let pointers get dereferenced here, that is obviously not a
4468 // constant expression.
4469 assert(FirstOpKind == UO_Deref);
4470 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4471 << Arg->getSourceRange();
4472 }
4473 }
4474 } else {
4475 // See through any implicit casts we added to fix the type.
4476 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004477
David Majnemer61c39a12013-08-23 05:39:39 +00004478 // C++ [temp.arg.nontype]p1:
4479 //
4480 // A template-argument for a non-type, non-template
4481 // template-parameter shall be one of: [...]
4482 //
4483 // -- the address of an object or function with external
4484 // linkage, including function templates and function
4485 // template-ids but excluding non-static class members,
4486 // expressed as & id-expression where the & is optional if
4487 // the name refers to a function or array, or if the
4488 // corresponding template-parameter is a reference; or
4489
4490 // In C++98/03 mode, give an extension warning on any extra parentheses.
4491 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4492 bool ExtraParens = false;
4493 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4494 if (!Invalid && !ExtraParens) {
4495 S.Diag(Arg->getLocStart(),
4496 S.getLangOpts().CPlusPlus11
4497 ? diag::warn_cxx98_compat_template_arg_extra_parens
4498 : diag::ext_template_arg_extra_parens)
4499 << Arg->getSourceRange();
4500 ExtraParens = true;
4501 }
4502
4503 Arg = Parens->getSubExpr();
4504 }
4505
4506 while (SubstNonTypeTemplateParmExpr *subst =
4507 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4508 Arg = subst->getReplacement()->IgnoreImpCasts();
4509
4510 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4511 if (UnOp->getOpcode() == UO_AddrOf) {
4512 Arg = UnOp->getSubExpr();
4513 AddressTaken = true;
4514 AddrOpLoc = UnOp->getOperatorLoc();
4515 }
4516 }
4517
4518 while (SubstNonTypeTemplateParmExpr *subst =
4519 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4520 Arg = subst->getReplacement()->IgnoreImpCasts();
4521 }
John McCall7c454bb2011-07-15 05:09:51 +00004522
David Majnemer07910d62014-06-26 07:48:46 +00004523 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4524 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4525
4526 // If our parameter has pointer type, check for a null template value.
4527 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4528 NullPointerValueKind NPV;
4529 // dllimport'd entities aren't constant but are available inside of template
4530 // arguments.
4531 if (Entity && Entity->hasAttr<DLLImportAttr>())
4532 NPV = NPV_NotNullPointer;
4533 else
4534 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4535 switch (NPV) {
4536 case NPV_NullPointer:
4537 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004538 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4539 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004540 return false;
4541
4542 case NPV_Error:
4543 return true;
4544
4545 case NPV_NotNullPointer:
4546 break;
4547 }
4548 }
4549
Chandler Carruth724a8a12010-01-31 10:01:20 +00004550 // Stop checking the precise nature of the argument if it is value dependent,
4551 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004552 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004553 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004554 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004555 }
David Majnemer61c39a12013-08-23 05:39:39 +00004556
4557 if (isa<CXXUuidofExpr>(Arg)) {
4558 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4559 ArgIn, Arg, ArgType))
4560 return true;
4561
4562 Converted = TemplateArgument(ArgIn);
4563 return false;
4564 }
4565
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004566 if (!DRE) {
4567 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4568 << Arg->getSourceRange();
4569 S.Diag(Param->getLocation(), diag::note_template_param_here);
4570 return true;
4571 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004572
Douglas Gregorccb07762009-02-11 19:52:55 +00004573 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004574 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004575 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004576 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004577 S.Diag(Param->getLocation(), diag::note_template_param_here);
4578 return true;
4579 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004580
4581 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004583 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004584 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004585 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004586 S.Diag(Param->getLocation(), diag::note_template_param_here);
4587 return true;
4588 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004589 }
Mike Stump11289f42009-09-09 15:08:12 +00004590
Richard Smith9380e0e2012-04-04 21:11:30 +00004591 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4592 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004593
Richard Smith9380e0e2012-04-04 21:11:30 +00004594 // A non-type template argument must refer to an object or function.
4595 if (!Func && !Var) {
4596 // We found something, but we don't know specifically what it is.
4597 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4598 << Arg->getSourceRange();
4599 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4600 return true;
4601 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004602
Richard Smith9380e0e2012-04-04 21:11:30 +00004603 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004604 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004605 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004606 diag::warn_cxx98_compat_template_arg_object_internal :
4607 diag::ext_template_arg_object_internal)
4608 << !Func << Entity << Arg->getSourceRange();
4609 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4610 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004611 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004612 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4613 << !Func << Entity << Arg->getSourceRange();
4614 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4615 << !Func;
4616 return true;
4617 }
4618
4619 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004620 // If the template parameter has pointer type, the function decays.
4621 if (ParamType->isPointerType() && !AddressTaken)
4622 ArgType = S.Context.getPointerType(Func->getType());
4623 else if (AddressTaken && ParamType->isReferenceType()) {
4624 // If we originally had an address-of operator, but the
4625 // parameter has reference type, complain and (if things look
4626 // like they will work) drop the address-of operator.
4627 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4628 ParamType.getNonReferenceType())) {
4629 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4630 << ParamType;
4631 S.Diag(Param->getLocation(), diag::note_template_param_here);
4632 return true;
4633 }
4634
4635 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4636 << ParamType
4637 << FixItHint::CreateRemoval(AddrOpLoc);
4638 S.Diag(Param->getLocation(), diag::note_template_param_here);
4639
4640 ArgType = Func->getType();
4641 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004642 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004643 // A value of reference type is not an object.
4644 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004645 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004646 diag::err_template_arg_reference_var)
4647 << Var->getType() << Arg->getSourceRange();
4648 S.Diag(Param->getLocation(), diag::note_template_param_here);
4649 return true;
4650 }
4651
Richard Smith9380e0e2012-04-04 21:11:30 +00004652 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004653 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004654 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4655 << Arg->getSourceRange();
4656 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4657 return true;
4658 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004659
4660 // If the template parameter has pointer type, we must have taken
4661 // the address of this object.
4662 if (ParamType->isReferenceType()) {
4663 if (AddressTaken) {
4664 // If we originally had an address-of operator, but the
4665 // parameter has reference type, complain and (if things look
4666 // like they will work) drop the address-of operator.
4667 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4668 ParamType.getNonReferenceType())) {
4669 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4670 << ParamType;
4671 S.Diag(Param->getLocation(), diag::note_template_param_here);
4672 return true;
4673 }
4674
4675 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4676 << ParamType
4677 << FixItHint::CreateRemoval(AddrOpLoc);
4678 S.Diag(Param->getLocation(), diag::note_template_param_here);
4679
4680 ArgType = Var->getType();
4681 }
4682 } else if (!AddressTaken && ParamType->isPointerType()) {
4683 if (Var->getType()->isArrayType()) {
4684 // Array-to-pointer decay.
4685 ArgType = S.Context.getArrayDecayedType(Var->getType());
4686 } else {
4687 // If the template parameter has pointer type but the address of
4688 // this object was not taken, complain and (possibly) recover by
4689 // taking the address of the entity.
4690 ArgType = S.Context.getPointerType(Var->getType());
4691 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4692 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4693 << ParamType;
4694 S.Diag(Param->getLocation(), diag::note_template_param_here);
4695 return true;
4696 }
4697
4698 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4699 << ParamType
4700 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4701
4702 S.Diag(Param->getLocation(), diag::note_template_param_here);
4703 }
4704 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004705 }
Mike Stump11289f42009-09-09 15:08:12 +00004706
David Majnemer61c39a12013-08-23 05:39:39 +00004707 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4708 Arg, ArgType))
4709 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004710
4711 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004712 Converted =
4713 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004714 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004715 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004716}
4717
4718/// \brief Checks whether the given template argument is a pointer to
4719/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004720static bool CheckTemplateArgumentPointerToMember(Sema &S,
4721 NonTypeTemplateParmDecl *Param,
4722 QualType ParamType,
4723 Expr *&ResultArg,
4724 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004725 bool Invalid = false;
4726
Douglas Gregor20fdef32012-04-10 17:08:25 +00004727 // Check for a null pointer value.
4728 Expr *Arg = ResultArg;
4729 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4730 case NPV_Error:
4731 return true;
4732 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004733 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004734 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4735 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004736 return false;
4737 case NPV_NotNullPointer:
4738 break;
4739 }
4740
4741 bool ObjCLifetimeConversion;
4742 if (S.IsQualificationConversion(Arg->getType(),
4743 ParamType.getNonReferenceType(),
4744 false, ObjCLifetimeConversion)) {
4745 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004746 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004747 ResultArg = Arg;
4748 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4749 ParamType.getNonReferenceType())) {
4750 // We can't perform this conversion.
4751 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4752 << Arg->getType() << ParamType << Arg->getSourceRange();
4753 S.Diag(Param->getLocation(), diag::note_template_param_here);
4754 return true;
4755 }
4756
Douglas Gregorccb07762009-02-11 19:52:55 +00004757 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004758 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004759 Arg = Cast->getSubExpr();
4760
4761 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004762 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004763 // A template-argument for a non-type, non-template
4764 // template-parameter shall be one of: [...]
4765 //
4766 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004767 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004768
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004769 // In C++98/03 mode, give an extension warning on any extra parentheses.
4770 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4771 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004772 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004773 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004774 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004775 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004776 diag::warn_cxx98_compat_template_arg_extra_parens :
4777 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004778 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004779 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004780 }
4781
4782 Arg = Parens->getSubExpr();
4783 }
4784
John McCall7c454bb2011-07-15 05:09:51 +00004785 while (SubstNonTypeTemplateParmExpr *subst =
4786 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4787 Arg = subst->getReplacement()->IgnoreImpCasts();
4788
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004789 // A pointer-to-member constant written &Class::member.
4790 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004791 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004792 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4793 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004794 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004797 // A constant of pointer-to-member type.
4798 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4799 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4800 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004801 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004802 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004803 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004804 } else {
4805 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004806 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004807 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004808 return Invalid;
4809 }
4810 }
4811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812
Craig Topperc3ec1492014-05-26 06:22:03 +00004813 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815
Douglas Gregorccb07762009-02-11 19:52:55 +00004816 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004817 return S.Diag(Arg->getLocStart(),
4818 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004819 << Arg->getSourceRange();
4820
David Majnemer3ac84e62013-10-22 21:56:38 +00004821 if (isa<FieldDecl>(DRE->getDecl()) ||
4822 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4823 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004824 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004825 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004826 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4827 "Only non-static member pointers can make it here");
4828
4829 // Okay: this is the address of a non-static member, and therefore
4830 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004831 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004832 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004833 } else {
4834 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004835 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004836 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004837 return Invalid;
4838 }
4839
4840 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004841 S.Diag(Arg->getLocStart(),
4842 diag::err_template_arg_not_pointer_to_member_form)
4843 << Arg->getSourceRange();
4844 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004845 return true;
4846}
4847
Douglas Gregord32e0282009-02-09 23:23:08 +00004848/// \brief Check a template argument against its corresponding
4849/// non-type template parameter.
4850///
Douglas Gregor463421d2009-03-03 04:44:36 +00004851/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004852/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004853/// returns the converted template argument. \p ParamType is the
4854/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004855ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004856 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004857 TemplateArgument &Converted,
4858 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004859 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004860
Douglas Gregor86560402009-02-10 23:36:10 +00004861 // If either the parameter has a dependent type or the argument is
4862 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004863 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004864 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004865 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004866 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004867 }
Douglas Gregor86560402009-02-10 23:36:10 +00004868
Richard Smithd663fdd2014-12-17 20:42:37 +00004869 // We should have already dropped all cv-qualifiers by now.
4870 assert(!ParamType.hasQualifiers() &&
4871 "non-type template parameter type cannot be qualified");
4872
4873 if (CTAK == CTAK_Deduced &&
4874 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4875 // C++ [temp.deduct.type]p17:
4876 // If, in the declaration of a function template with a non-type
4877 // template-parameter, the non-type template-parameter is used
4878 // in an expression in the function parameter-list and, if the
4879 // corresponding template-argument is deduced, the
4880 // template-argument type shall match the type of the
4881 // template-parameter exactly, except that a template-argument
4882 // deduced from an array bound may be of any integral type.
4883 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4884 << Arg->getType().getUnqualifiedType()
4885 << ParamType.getUnqualifiedType();
4886 Diag(Param->getLocation(), diag::note_template_param_here);
4887 return ExprError();
4888 }
4889
Richard Smith410cc892014-11-26 03:26:53 +00004890 if (getLangOpts().CPlusPlus1z) {
4891 // FIXME: We can do some limited checking for a value-dependent but not
4892 // type-dependent argument.
4893 if (Arg->isValueDependent()) {
4894 Converted = TemplateArgument(Arg);
4895 return Arg;
4896 }
4897
4898 // C++1z [temp.arg.nontype]p1:
4899 // A template-argument for a non-type template parameter shall be
4900 // a converted constant expression of the type of the template-parameter.
4901 APValue Value;
4902 ExprResult ArgResult = CheckConvertedConstantExpression(
4903 Arg, ParamType, Value, CCEK_TemplateArg);
4904 if (ArgResult.isInvalid())
4905 return ExprError();
4906
Richard Smithd663fdd2014-12-17 20:42:37 +00004907 QualType CanonParamType = Context.getCanonicalType(ParamType);
4908
Richard Smith410cc892014-11-26 03:26:53 +00004909 // Convert the APValue to a TemplateArgument.
4910 switch (Value.getKind()) {
4911 case APValue::Uninitialized:
4912 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004913 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004914 break;
4915 case APValue::Int:
4916 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004917 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004918 break;
4919 case APValue::MemberPointer: {
4920 assert(ParamType->isMemberPointerType());
4921
4922 // FIXME: We need TemplateArgument representation and mangling for these.
4923 if (!Value.getMemberPointerPath().empty()) {
4924 Diag(Arg->getLocStart(),
4925 diag::err_template_arg_member_ptr_base_derived_not_supported)
4926 << Value.getMemberPointerDecl() << ParamType
4927 << Arg->getSourceRange();
4928 return ExprError();
4929 }
4930
4931 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004932 Converted = VD ? TemplateArgument(VD, CanonParamType)
4933 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004934 break;
4935 }
4936 case APValue::LValue: {
4937 // For a non-type template-parameter of pointer or reference type,
4938 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004939 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4940 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004941 // -- a temporary object
4942 // -- a string literal
4943 // -- the result of a typeid expression, or
4944 // -- a predefind __func__ variable
4945 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4946 if (isa<CXXUuidofExpr>(E)) {
4947 Converted = TemplateArgument(const_cast<Expr*>(E));
4948 break;
4949 }
4950 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4951 << Arg->getSourceRange();
4952 return ExprError();
4953 }
4954 auto *VD = const_cast<ValueDecl *>(
4955 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4956 // -- a subobject
4957 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4958 VD && VD->getType()->isArrayType() &&
4959 Value.getLValuePath()[0].ArrayIndex == 0 &&
4960 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4961 // Per defect report (no number yet):
4962 // ... other than a pointer to the first element of a complete array
4963 // object.
4964 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4965 Value.isLValueOnePastTheEnd()) {
4966 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4967 << Value.getAsString(Context, ParamType);
4968 return ExprError();
4969 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004970 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004971 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004972 assert((!VD || !ParamType->isNullPtrType()) &&
4973 "non-null value of type nullptr_t?");
4974 Converted = VD ? TemplateArgument(VD, CanonParamType)
4975 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004976 break;
4977 }
4978 case APValue::AddrLabelDiff:
4979 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4980 case APValue::Float:
4981 case APValue::ComplexInt:
4982 case APValue::ComplexFloat:
4983 case APValue::Vector:
4984 case APValue::Array:
4985 case APValue::Struct:
4986 case APValue::Union:
4987 llvm_unreachable("invalid kind for template argument");
4988 }
4989
4990 return ArgResult.get();
4991 }
4992
Douglas Gregor86560402009-02-10 23:36:10 +00004993 // C++ [temp.arg.nontype]p5:
4994 // The following conversions are performed on each expression used
4995 // as a non-type template-argument. If a non-type
4996 // template-argument cannot be converted to the type of the
4997 // corresponding template-parameter then the program is
4998 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00004999 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005000 // C++11:
5001 // -- for a non-type template-parameter of integral or
5002 // enumeration type, conversions permitted in a converted
5003 // constant expression are applied.
5004 //
5005 // C++98:
5006 // -- for a non-type template-parameter of integral or
5007 // enumeration type, integral promotions (4.5) and integral
5008 // conversions (4.7) are applied.
5009
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005010 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005011 // We can't check arbitrary value-dependent arguments.
5012 // FIXME: If there's no viable conversion to the template parameter type,
5013 // we should be able to diagnose that prior to instantiation.
5014 if (Arg->isValueDependent()) {
5015 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005016 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005017 }
5018
5019 // C++ [temp.arg.nontype]p1:
5020 // A template-argument for a non-type, non-template template-parameter
5021 // shall be one of:
5022 //
5023 // -- for a non-type template-parameter of integral or enumeration
5024 // type, a converted constant expression of the type of the
5025 // template-parameter; or
5026 llvm::APSInt Value;
5027 ExprResult ArgResult =
5028 CheckConvertedConstantExpression(Arg, ParamType, Value,
5029 CCEK_TemplateArg);
5030 if (ArgResult.isInvalid())
5031 return ExprError();
5032
5033 // Widen the argument value to sizeof(parameter type). This is almost
5034 // always a no-op, except when the parameter type is bool. In
5035 // that case, this may extend the argument from 1 bit to 8 bits.
5036 QualType IntegerType = ParamType;
5037 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5038 IntegerType = Enum->getDecl()->getIntegerType();
5039 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5040
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005041 Converted = TemplateArgument(Context, Value,
5042 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005043 return ArgResult;
5044 }
5045
Richard Smith08b12f12011-10-27 22:11:44 +00005046 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5047 if (ArgResult.isInvalid())
5048 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005049 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005050
5051 QualType ArgType = Arg->getType();
5052
Douglas Gregor86560402009-02-10 23:36:10 +00005053 // C++ [temp.arg.nontype]p1:
5054 // A template-argument for a non-type, non-template
5055 // template-parameter shall be one of:
5056 //
5057 // -- an integral constant-expression of integral or enumeration
5058 // type; or
5059 // -- the name of a non-type template-parameter; or
5060 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005061 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005062 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005063 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005064 diag::err_template_arg_not_integral_or_enumeral)
5065 << ArgType << Arg->getSourceRange();
5066 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005067 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005068 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005069 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5070 QualType T;
5071
5072 public:
5073 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005074
5075 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5076 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005077 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5078 }
5079 } Diagnoser(ArgType);
5080
5081 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005082 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005083 if (!Arg)
5084 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005085 }
5086
Richard Smithd663fdd2014-12-17 20:42:37 +00005087 // From here on out, all we care about is the unqualified form
5088 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005089 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005090
5091 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005092 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005093 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005094 } else if (ParamType->isBooleanType()) {
5095 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005096 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005097 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5098 !ParamType->isEnumeralType()) {
5099 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005100 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005101 } else {
5102 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005103 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005104 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005105 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005106 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005107 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005108 }
5109
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005110 // Add the value of this argument to the list of converted
5111 // arguments. We use the bitwidth and signedness of the template
5112 // parameter.
5113 if (Arg->isValueDependent()) {
5114 // The argument is value-dependent. Create a new
5115 // TemplateArgument with the converted expression.
5116 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005117 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005118 }
5119
Douglas Gregor52aba872009-03-14 00:20:21 +00005120 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005121 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005122 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005123
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005124 if (ParamType->isBooleanType()) {
5125 // Value must be zero or one.
5126 Value = Value != 0;
5127 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5128 if (Value.getBitWidth() != AllowedBits)
5129 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005130 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005131 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005132 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005133
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005135 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005136 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005137 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005138 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005139 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005140
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005141 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005142 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005143 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005144 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005145 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5146 << Arg->getSourceRange();
5147 Diag(Param->getLocation(), diag::note_template_param_here);
5148 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005149
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005150 // Complain if we overflowed the template parameter's type.
5151 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005152 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005153 RequiredBits = OldValue.getActiveBits();
5154 else if (OldValue.isUnsigned())
5155 RequiredBits = OldValue.getActiveBits() + 1;
5156 else
5157 RequiredBits = OldValue.getMinSignedBits();
5158 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005159 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005160 diag::warn_template_arg_too_large)
5161 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5162 << Arg->getSourceRange();
5163 Diag(Param->getLocation(), diag::note_template_param_here);
5164 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005165 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005166
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005167 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005168 ParamType->isEnumeralType()
5169 ? Context.getCanonicalType(ParamType)
5170 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005171 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005172 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005173
Richard Smith08b12f12011-10-27 22:11:44 +00005174 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005175 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5176
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005177 // Handle pointer-to-function, reference-to-function, and
5178 // pointer-to-member-function all in (roughly) the same way.
5179 if (// -- For a non-type template-parameter of type pointer to
5180 // function, only the function-to-pointer conversion (4.3) is
5181 // applied. If the template-argument represents a set of
5182 // overloaded functions (or a pointer to such), the matching
5183 // function is selected from the set (13.4).
5184 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005185 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005186 // -- For a non-type template-parameter of type reference to
5187 // function, no conversions apply. If the template-argument
5188 // represents a set of overloaded functions, the matching
5189 // function is selected from the set (13.4).
5190 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005191 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005192 // -- For a non-type template-parameter of type pointer to
5193 // member function, no conversions apply. If the
5194 // template-argument represents a set of overloaded member
5195 // functions, the matching member function is selected from
5196 // the set (13.4).
5197 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005198 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005199 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005200
Douglas Gregor064fdb22010-04-14 23:11:21 +00005201 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005202 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005203 true,
5204 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005205 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005206 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005207
5208 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5209 ArgType = Arg->getType();
5210 } else
John Wiegley01296292011-04-08 18:41:53 +00005211 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005212 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005213
John Wiegley01296292011-04-08 18:41:53 +00005214 if (!ParamType->isMemberPointerType()) {
5215 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5216 ParamType,
5217 Arg, Converted))
5218 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005219 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005220 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005221
Douglas Gregor20fdef32012-04-10 17:08:25 +00005222 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5223 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005224 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005225 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005226 }
5227
Chris Lattner696197c2009-02-20 21:37:53 +00005228 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005229 // -- for a non-type template-parameter of type pointer to
5230 // object, qualification conversions (4.4) and the
5231 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005232 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005233 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005234 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005235
John Wiegley01296292011-04-08 18:41:53 +00005236 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5237 ParamType,
5238 Arg, Converted))
5239 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005240 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005241 }
Mike Stump11289f42009-09-09 15:08:12 +00005242
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005243 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005244 // -- For a non-type template-parameter of type reference to
5245 // object, no conversions apply. The type referred to by the
5246 // reference may be more cv-qualified than the (otherwise
5247 // identical) type of the template-argument. The
5248 // template-parameter is bound directly to the
5249 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005250 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005251 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005252
Douglas Gregor064fdb22010-04-14 23:11:21 +00005253 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005254 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5255 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005256 true,
5257 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005258 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005259 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005260
5261 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5262 ArgType = Arg->getType();
5263 } else
John Wiegley01296292011-04-08 18:41:53 +00005264 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005266
John Wiegley01296292011-04-08 18:41:53 +00005267 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5268 ParamType,
5269 Arg, Converted))
5270 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005271 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005272 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005273
Douglas Gregor20fdef32012-04-10 17:08:25 +00005274 // Deal with parameters of type std::nullptr_t.
5275 if (ParamType->isNullPtrType()) {
5276 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5277 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005278 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005279 }
5280
5281 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5282 case NPV_NotNullPointer:
5283 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5284 << Arg->getType() << ParamType;
5285 Diag(Param->getLocation(), diag::note_template_param_here);
5286 return ExprError();
5287
5288 case NPV_Error:
5289 return ExprError();
5290
5291 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005292 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005293 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5294 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005295 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005296 }
5297 }
5298
Douglas Gregor0e558532009-02-11 16:16:59 +00005299 // -- For a non-type template-parameter of type pointer to data
5300 // member, qualification conversions (4.4) are applied.
5301 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5302
Douglas Gregor20fdef32012-04-10 17:08:25 +00005303 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5304 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005305 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005306 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005307}
5308
5309/// \brief Check a template argument against its corresponding
5310/// template template parameter.
5311///
5312/// This routine implements the semantics of C++ [temp.arg.template].
5313/// It returns true if an error occurred, and false otherwise.
5314bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005315 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005316 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005317 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005318 TemplateDecl *Template = Name.getAsTemplateDecl();
5319 if (!Template) {
5320 // Any dependent template name is fine.
5321 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5322 return false;
5323 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005324
Richard Smith3f1b5d02011-05-05 21:57:07 +00005325 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005326 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005327 // the name of a class template or an alias template, expressed as an
5328 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005329 // primary class templates are considered when matching the
5330 // template template argument with the corresponding parameter;
5331 // partial specializations are not considered even if their
5332 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005333 //
5334 // Note that we also allow template template parameters here, which
5335 // will happen when we are dealing with, e.g., class template
5336 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005337 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005338 !isa<TemplateTemplateParmDecl>(Template) &&
5339 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005340 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005341 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005342 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005343 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005344 << Template;
5345 }
5346
Richard Smith1fde8ec2012-09-07 02:06:42 +00005347 TemplateParameterList *Params = Param->getTemplateParameters();
5348 if (Param->isExpandedParameterPack())
5349 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5350
Douglas Gregor85e0f662009-02-10 00:24:35 +00005351 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005352 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005353 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005354 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005355 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005356}
5357
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005358/// \brief Given a non-type template argument that refers to a
5359/// declaration and the type of its corresponding non-type template
5360/// parameter, produce an expression that properly refers to that
5361/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005362ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005363Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5364 QualType ParamType,
5365 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005366 // C++ [temp.param]p8:
5367 //
5368 // A non-type template-parameter of type "array of T" or
5369 // "function returning T" is adjusted to be of type "pointer to
5370 // T" or "pointer to function returning T", respectively.
5371 if (ParamType->isArrayType())
5372 ParamType = Context.getArrayDecayedType(ParamType);
5373 else if (ParamType->isFunctionType())
5374 ParamType = Context.getPointerType(ParamType);
5375
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005376 // For a NULL non-type template argument, return nullptr casted to the
5377 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005378 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005379 return ImpCastExprToType(
5380 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5381 ParamType,
5382 ParamType->getAs<MemberPointerType>()
5383 ? CK_NullToMemberPointer
5384 : CK_NullToPointer);
5385 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005386 assert(Arg.getKind() == TemplateArgument::Declaration &&
5387 "Only declaration template arguments permitted here");
5388
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005389 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5390
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005392 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5393 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005394 // If the value is a class member, we might have a pointer-to-member.
5395 // Determine whether the non-type template template parameter is of
5396 // pointer-to-member type. If so, we need to build an appropriate
5397 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5398 // would refer to the member itself.
5399 if (ParamType->isMemberPointerType()) {
5400 QualType ClassType
5401 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5402 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005403 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005404 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005405 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005406 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005407
5408 // The actual value-ness of this is unimportant, but for
5409 // internal consistency's sake, references to instance methods
5410 // are r-values.
5411 ExprValueKind VK = VK_LValue;
5412 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5413 VK = VK_RValue;
5414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005415 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005416 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005417 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005418 Loc,
5419 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005420 if (RefExpr.isInvalid())
5421 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005422
John McCalle3027922010-08-25 11:45:40 +00005423 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005424
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005425 // We might need to perform a trailing qualification conversion, since
5426 // the element type on the parameter could be more qualified than the
5427 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005428 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005429 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005430 ParamType.getUnqualifiedType(), false,
5431 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005432 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005433
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005434 assert(!RefExpr.isInvalid() &&
5435 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005436 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005437 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005438 }
5439 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005440
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005441 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005442
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005443 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005444 // When the non-type template parameter is a pointer, take the
5445 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005446 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005447 if (RefExpr.isInvalid())
5448 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005449
5450 if (T->isFunctionType() || T->isArrayType()) {
5451 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005452 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005453 if (RefExpr.isInvalid())
5454 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005455
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005456 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005458
Douglas Gregorb242683d2010-04-01 18:32:35 +00005459 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005460 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005461 }
5462
John McCall7decc9e2010-11-18 06:31:45 +00005463 ExprValueKind VK = VK_RValue;
5464
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005465 // If the non-type template parameter has reference type, qualify the
5466 // resulting declaration reference with the extra qualifiers on the
5467 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005468 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5469 VK = VK_LValue;
5470 T = Context.getQualifiedType(T,
5471 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005472 } else if (isa<FunctionDecl>(VD)) {
5473 // References to functions are always lvalues.
5474 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005476
John McCall7decc9e2010-11-18 06:31:45 +00005477 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005478}
5479
5480/// \brief Construct a new expression that refers to the given
5481/// integral template argument with the given source-location
5482/// information.
5483///
5484/// This routine takes care of the mapping from an integral template
5485/// argument (which may have any integral type) to the appropriate
5486/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005487ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005488Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5489 SourceLocation Loc) {
5490 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005491 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005492 QualType OrigT = Arg.getIntegralType();
5493
5494 // If this is an enum type that we're instantiating, we need to use an integer
5495 // type the same size as the enumerator. We don't want to build an
5496 // IntegerLiteral with enum type. The integer type of an enum type can be of
5497 // any integral type with C++11 enum classes, make sure we create the right
5498 // type of literal for it.
5499 QualType T = OrigT;
5500 if (const EnumType *ET = OrigT->getAs<EnumType>())
5501 T = ET->getDecl()->getIntegerType();
5502
5503 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005504 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005505 // This does not need to handle u8 character literals because those are
5506 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005507 CharacterLiteral::CharacterKind Kind;
5508 if (T->isWideCharType())
5509 Kind = CharacterLiteral::Wide;
5510 else if (T->isChar16Type())
5511 Kind = CharacterLiteral::UTF16;
5512 else if (T->isChar32Type())
5513 Kind = CharacterLiteral::UTF32;
5514 else
5515 Kind = CharacterLiteral::Ascii;
5516
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005517 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5518 Kind, T, Loc);
5519 } else if (T->isBooleanType()) {
5520 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5521 T, Loc);
5522 } else if (T->isNullPtrType()) {
5523 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5524 } else {
5525 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005526 }
5527
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005528 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005529 // FIXME: This is a hack. We need a better way to handle substituted
5530 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005531 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5532 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005533 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005534 Loc, Loc);
5535 }
5536
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005537 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005538}
5539
Douglas Gregor641040a2011-01-12 23:45:44 +00005540/// \brief Match two template parameters within template parameter lists.
5541static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5542 bool Complain,
5543 Sema::TemplateParameterListEqualKind Kind,
5544 SourceLocation TemplateArgLoc) {
5545 // Check the actual kind (type, non-type, template).
5546 if (Old->getKind() != New->getKind()) {
5547 if (Complain) {
5548 unsigned NextDiag = diag::err_template_param_different_kind;
5549 if (TemplateArgLoc.isValid()) {
5550 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5551 NextDiag = diag::note_template_param_different_kind;
5552 }
5553 S.Diag(New->getLocation(), NextDiag)
5554 << (Kind != Sema::TPL_TemplateMatch);
5555 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5556 << (Kind != Sema::TPL_TemplateMatch);
5557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005558
Douglas Gregor641040a2011-01-12 23:45:44 +00005559 return false;
5560 }
5561
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562 // Check that both are parameter packs are neither are parameter packs.
5563 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005564 // template template parameter, the template template parameter can have
5565 // a parameter pack where the template template argument does not.
5566 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5567 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5568 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005569 if (Complain) {
5570 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5571 if (TemplateArgLoc.isValid()) {
5572 S.Diag(TemplateArgLoc,
5573 diag::err_template_arg_template_params_mismatch);
5574 NextDiag = diag::note_template_parameter_pack_non_pack;
5575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Douglas Gregor641040a2011-01-12 23:45:44 +00005577 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5578 : isa<NonTypeTemplateParmDecl>(New)? 1
5579 : 2;
5580 S.Diag(New->getLocation(), NextDiag)
5581 << ParamKind << New->isParameterPack();
5582 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5583 << ParamKind << Old->isParameterPack();
5584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005585
Douglas Gregor641040a2011-01-12 23:45:44 +00005586 return false;
5587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588
Douglas Gregor641040a2011-01-12 23:45:44 +00005589 // For non-type template parameters, check the type of the parameter.
5590 if (NonTypeTemplateParmDecl *OldNTTP
5591 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5592 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005593
Douglas Gregor641040a2011-01-12 23:45:44 +00005594 // If we are matching a template template argument to a template
5595 // template parameter and one of the non-type template parameter types
5596 // is dependent, then we must wait until template instantiation time
5597 // to actually compare the arguments.
5598 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5599 (OldNTTP->getType()->isDependentType() ||
5600 NewNTTP->getType()->isDependentType()))
5601 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005602
Douglas Gregor641040a2011-01-12 23:45:44 +00005603 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5604 if (Complain) {
5605 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5606 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005608 diag::err_template_arg_template_params_mismatch);
5609 NextDiag = diag::note_template_nontype_parm_different_type;
5610 }
5611 S.Diag(NewNTTP->getLocation(), NextDiag)
5612 << NewNTTP->getType()
5613 << (Kind != Sema::TPL_TemplateMatch);
5614 S.Diag(OldNTTP->getLocation(),
5615 diag::note_template_nontype_parm_prev_declaration)
5616 << OldNTTP->getType();
5617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618
Douglas Gregor641040a2011-01-12 23:45:44 +00005619 return false;
5620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621
Douglas Gregor641040a2011-01-12 23:45:44 +00005622 return true;
5623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005624
Douglas Gregor641040a2011-01-12 23:45:44 +00005625 // For template template parameters, check the template parameter types.
5626 // The template parameter lists of template template
5627 // parameters must agree.
5628 if (TemplateTemplateParmDecl *OldTTP
5629 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005630 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005631 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5632 OldTTP->getTemplateParameters(),
5633 Complain,
5634 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005635 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005636 : Kind),
5637 TemplateArgLoc);
5638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639
Douglas Gregor641040a2011-01-12 23:45:44 +00005640 return true;
5641}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005642
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005643/// \brief Diagnose a known arity mismatch when comparing template argument
5644/// lists.
5645static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005647 TemplateParameterList *New,
5648 TemplateParameterList *Old,
5649 Sema::TemplateParameterListEqualKind Kind,
5650 SourceLocation TemplateArgLoc) {
5651 unsigned NextDiag = diag::err_template_param_list_different_arity;
5652 if (TemplateArgLoc.isValid()) {
5653 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5654 NextDiag = diag::note_template_param_list_different_arity;
5655 }
5656 S.Diag(New->getTemplateLoc(), NextDiag)
5657 << (New->size() > Old->size())
5658 << (Kind != Sema::TPL_TemplateMatch)
5659 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5660 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5661 << (Kind != Sema::TPL_TemplateMatch)
5662 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5663}
5664
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005665/// \brief Determine whether the given template parameter lists are
5666/// equivalent.
5667///
Mike Stump11289f42009-09-09 15:08:12 +00005668/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005669/// source code as part of a new template declaration.
5670///
5671/// \param Old The old template parameter list, typically found via
5672/// name lookup of the template declared with this template parameter
5673/// list.
5674///
5675/// \param Complain If true, this routine will produce a diagnostic if
5676/// the template parameter lists are not equivalent.
5677///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005678/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005679///
5680/// \param TemplateArgLoc If this source location is valid, then we
5681/// are actually checking the template parameter list of a template
5682/// argument (New) against the template parameter list of its
5683/// corresponding template template parameter (Old). We produce
5684/// slightly different diagnostics in this scenario.
5685///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005686/// \returns True if the template parameter lists are equal, false
5687/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005688bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005689Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5690 TemplateParameterList *Old,
5691 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005692 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005693 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005694 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5695 if (Complain)
5696 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5697 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005698
5699 return false;
5700 }
5701
Douglas Gregor641040a2011-01-12 23:45:44 +00005702 // C++0x [temp.arg.template]p3:
5703 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005704 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005705 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005706 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005707 // template-parameter-list of P. [...]
5708 TemplateParameterList::iterator NewParm = New->begin();
5709 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005710 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005711 OldParmEnd = Old->end();
5712 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005713 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5714 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005715 if (NewParm == NewParmEnd) {
5716 if (Complain)
5717 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5718 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005720 return false;
5721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005722
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005723 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5724 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725 return false;
5726
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005727 ++NewParm;
5728 continue;
5729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005731 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005732 // [...] When P's template- parameter-list contains a template parameter
5733 // pack (14.5.3), the template parameter pack will match zero or more
5734 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005735 // template-parameter-list of A with the same type and form as the
5736 // template parameter pack in P (ignoring whether those template
5737 // parameters are template parameter packs).
5738 for (; NewParm != NewParmEnd; ++NewParm) {
5739 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5740 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005742 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005744
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005745 // Make sure we exhausted all of the arguments.
5746 if (NewParm != NewParmEnd) {
5747 if (Complain)
5748 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5749 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005750
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005751 return false;
5752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005754 return true;
5755}
5756
5757/// \brief Check whether a template can be declared within this scope.
5758///
5759/// If the template declaration is valid in this scope, returns
5760/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005761bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005762Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005763 if (!S)
5764 return false;
5765
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005766 // Find the nearest enclosing declaration scope.
5767 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5768 (S->getFlags() & Scope::TemplateParamScope) != 0)
5769 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005770
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005771 // C++ [temp]p4:
5772 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005773 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005774 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005775 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005776 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005777
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005778 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005779 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005780
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005781 // C++ [temp]p2:
5782 // A template-declaration can appear only as a namespace scope or
5783 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005784 if (Ctx) {
5785 if (Ctx->isFileContext())
5786 return false;
5787 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5788 // C++ [temp.mem]p2:
5789 // A local class shall not have member templates.
5790 if (RD->isLocalClass())
5791 return Diag(TemplateParams->getTemplateLoc(),
5792 diag::err_template_inside_local_class)
5793 << TemplateParams->getSourceRange();
5794 else
5795 return false;
5796 }
5797 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005798
Mike Stump11289f42009-09-09 15:08:12 +00005799 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005800 diag::err_template_outside_namespace_or_class_scope)
5801 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005802}
Douglas Gregor67a65642009-02-17 23:15:12 +00005803
Douglas Gregor54888652009-10-07 00:13:32 +00005804/// \brief Determine what kind of template specialization the given declaration
5805/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005806static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005807 if (!D)
5808 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005809
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005810 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5811 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005812 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5813 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005814 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5815 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005816
Douglas Gregor54888652009-10-07 00:13:32 +00005817 return TSK_Undeclared;
5818}
5819
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005820/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005821/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005822///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005823/// This routine determines whether a template specialization can be declared
5824/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005825///
5826/// \param S the semantic analysis object for which this check is being
5827/// performed.
5828///
5829/// \param Specialized the entity being specialized or instantiated, which
5830/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005831/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005832/// member class).
5833///
5834/// \param PrevDecl the previous declaration of this entity, if any.
5835///
5836/// \param Loc the location of the explicit specialization or instantiation of
5837/// this entity.
5838///
5839/// \param IsPartialSpecialization whether this is a partial specialization of
5840/// a class template.
5841///
Douglas Gregor54888652009-10-07 00:13:32 +00005842/// \returns true if there was an error that we cannot recover from, false
5843/// otherwise.
5844static bool CheckTemplateSpecializationScope(Sema &S,
5845 NamedDecl *Specialized,
5846 NamedDecl *PrevDecl,
5847 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005848 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005849 // Keep these "kind" numbers in sync with the %select statements in the
5850 // various diagnostics emitted by this routine.
5851 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005852 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005853 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005854 else if (isa<VarTemplateDecl>(Specialized))
5855 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005856 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005857 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005858 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005859 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005860 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005861 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005862 else if (isa<RecordDecl>(Specialized))
5863 EntityKind = 7;
5864 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5865 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005866 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005867 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005868 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005869 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005870 return true;
5871 }
5872
Douglas Gregorf47b9112009-02-25 22:02:03 +00005873 // C++ [temp.expl.spec]p2:
5874 // An explicit specialization shall be declared in the namespace
5875 // of which the template is a member, or, for member templates, in
5876 // the namespace of which the enclosing class or enclosing class
5877 // template is a member. An explicit specialization of a member
5878 // function, member class or static data member of a class
5879 // template shall be declared in the namespace of which the class
5880 // template is a member. Such a declaration may also be a
5881 // definition. If the declaration is not a definition, the
5882 // specialization may be defined later in the name- space in which
5883 // the explicit specialization was declared, or in a namespace
5884 // that encloses the one in which the explicit specialization was
5885 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005886 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005887 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005888 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005889 return true;
5890 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005891
Douglas Gregor40fb7442009-10-07 17:30:37 +00005892 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005893 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005894 // Do not warn for class scope explicit specialization during
5895 // instantiation, warning was already emitted during pattern
5896 // semantic analysis.
5897 if (!S.ActiveTemplateInstantiations.size())
5898 S.Diag(Loc, diag::ext_function_specialization_in_class)
5899 << Specialized;
5900 } else {
5901 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5902 << Specialized;
5903 return true;
5904 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005906
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005907 if (S.CurContext->isRecord() &&
5908 !S.CurContext->Equals(Specialized->getDeclContext())) {
5909 // Make sure that we're specializing in the right record context.
5910 // Otherwise, things can go horribly wrong.
5911 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5912 << Specialized;
5913 return true;
5914 }
5915
Douglas Gregore4b05162009-10-07 17:21:34 +00005916 // C++ [temp.class.spec]p6:
5917 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005918 // in any namespace scope in which its definition may be defined (14.5.1
5919 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005920 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005921 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005922 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005923
5924 // Make sure that this redeclaration (or definition) occurs in an enclosing
5925 // namespace.
5926 // Note that HandleDeclarator() performs this check for explicit
5927 // specializations of function templates, static data members, and member
5928 // functions, so we skip the check here for those kinds of entities.
5929 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5930 // Should we refactor that check, so that it occurs later?
5931 if (!DC->Encloses(SpecializedContext) &&
5932 !(isa<FunctionTemplateDecl>(Specialized) ||
5933 isa<FunctionDecl>(Specialized) ||
5934 isa<VarTemplateDecl>(Specialized) ||
5935 isa<VarDecl>(Specialized))) {
5936 if (isa<TranslationUnitDecl>(SpecializedContext))
5937 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5938 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005939 else if (isa<NamespaceDecl>(SpecializedContext)) {
5940 int Diag = diag::err_template_spec_redecl_out_of_scope;
5941 if (S.getLangOpts().MicrosoftExt)
5942 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5943 S.Diag(Loc, Diag) << EntityKind << Specialized
5944 << cast<NamedDecl>(SpecializedContext);
5945 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005946 llvm_unreachable("unexpected namespace context for specialization");
5947
5948 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5949 } else if ((!PrevDecl ||
5950 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5951 getTemplateSpecializationKind(PrevDecl) ==
5952 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005953 // C++ [temp.exp.spec]p2:
5954 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005955 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005956 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005957 // An explicit specialization of a member function, member class or
5958 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005959 // namespace of which the class template is a member.
5960 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005961 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005962 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005963 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005964 // C++11 [temp.explicit]p3:
5965 // An explicit instantiation shall appear in an enclosing namespace of its
5966 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005967 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005968 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005969 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005970 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005971 "DC encloses TU but isn't in enclosing namespace set");
5972 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005973 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005974 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5975 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005976 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005977 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005978 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005979 Diag = diag::ext_template_spec_decl_out_of_scope;
5980 else
5981 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5982 S.Diag(Loc, Diag)
5983 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005986 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005987 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005989
Douglas Gregorf47b9112009-02-25 22:02:03 +00005990 return false;
5991}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005992
Richard Smith6056d5e2014-02-09 00:54:43 +00005993static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5994 if (!E->isInstantiationDependent())
5995 return SourceLocation();
5996 DependencyChecker Checker(Depth);
5997 Checker.TraverseStmt(E);
5998 if (Checker.Match && Checker.MatchLoc.isInvalid())
5999 return E->getSourceRange();
6000 return Checker.MatchLoc;
6001}
6002
6003static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6004 if (!TL.getType()->isDependentType())
6005 return SourceLocation();
6006 DependencyChecker Checker(Depth);
6007 Checker.TraverseTypeLoc(TL);
6008 if (Checker.Match && Checker.MatchLoc.isInvalid())
6009 return TL.getSourceRange();
6010 return Checker.MatchLoc;
6011}
6012
Larisse Voufo39a1e502013-08-06 01:03:05 +00006013/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006014/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006015static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006016 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6017 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006018 for (unsigned I = 0; I != NumArgs; ++I) {
6019 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006020 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006021 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6022 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006023 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006025 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006027
Eli Friedmanb826a002012-09-26 02:36:12 +00006028 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006029 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006030
6031 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006032
Douglas Gregor98318c22011-01-03 21:37:45 +00006033 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006034 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6035 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006036
6037 // Strip off any implicit casts we added as part of type checking.
6038 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6039 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006041 // C++ [temp.class.spec]p8:
6042 // A non-type argument is non-specialized if it is the name of a
6043 // non-type parameter. All other non-type arguments are
6044 // specialized.
6045 //
6046 // Below, we check the two conditions that only apply to
6047 // specialized non-type arguments, so skip any non-specialized
6048 // arguments.
6049 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006050 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006051 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006052
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006053 // C++ [temp.class.spec]p9:
6054 // Within the argument list of a class template partial
6055 // specialization, the following restrictions apply:
6056 // -- A partially specialized non-type argument expression
6057 // shall not involve a template parameter of the partial
6058 // specialization except when the argument expression is a
6059 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006060 SourceRange ParamUseRange =
6061 findTemplateParameter(Param->getDepth(), ArgExpr);
6062 if (ParamUseRange.isValid()) {
6063 if (IsDefaultArgument) {
6064 S.Diag(TemplateNameLoc,
6065 diag::err_dependent_non_type_arg_in_partial_spec);
6066 S.Diag(ParamUseRange.getBegin(),
6067 diag::note_dependent_non_type_default_arg_in_partial_spec)
6068 << ParamUseRange;
6069 } else {
6070 S.Diag(ParamUseRange.getBegin(),
6071 diag::err_dependent_non_type_arg_in_partial_spec)
6072 << ParamUseRange;
6073 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006074 return true;
6075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006077 // -- The type of a template parameter corresponding to a
6078 // specialized non-type argument shall not be dependent on a
6079 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006080 //
6081 // FIXME: We need to delay this check until instantiation in some cases:
6082 //
6083 // template<template<typename> class X> struct A {
6084 // template<typename T, X<T> N> struct B;
6085 // template<typename T> struct B<T, 0>;
6086 // };
6087 // template<typename> using X = int;
6088 // A<X>::B<int, 0> b;
6089 ParamUseRange = findTemplateParameter(
6090 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6091 if (ParamUseRange.isValid()) {
6092 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6093 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6094 << Param->getType() << ParamUseRange;
6095 S.Diag(Param->getLocation(), diag::note_template_param_here)
6096 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006097 return true;
6098 }
6099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006101 return false;
6102}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006103
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006104/// \brief Check the non-type template arguments of a class template
6105/// partial specialization according to C++ [temp.class.spec]p9.
6106///
Richard Smith6056d5e2014-02-09 00:54:43 +00006107/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006108/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006109/// template.
6110/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006111/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006112/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006113///
Richard Smith6056d5e2014-02-09 00:54:43 +00006114/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006115static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006116 Sema &S, SourceLocation TemplateNameLoc,
6117 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006118 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006119 const TemplateArgument *ArgList = TemplateArgs.data();
6120
6121 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6122 NonTypeTemplateParmDecl *Param
6123 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6124 if (!Param)
6125 continue;
6126
Richard Smith6056d5e2014-02-09 00:54:43 +00006127 if (CheckNonTypeTemplatePartialSpecializationArgs(
6128 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006129 return true;
6130 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006131
6132 return false;
6133}
6134
John McCall48871652010-08-21 09:40:31 +00006135DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006136Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6137 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006138 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006139 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006140 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006141 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006142 MultiTemplateParamsArg
6143 TemplateParameterLists,
6144 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006145 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006146
Richard Smith4b55a9c2014-04-17 03:29:33 +00006147 CXXScopeSpec &SS = TemplateId.SS;
6148
Abramo Bagnara60804e12011-03-18 15:16:37 +00006149 // NOTE: KWLoc is the location of the tag keyword. This will instead
6150 // store the location of the outermost template keyword in the declaration.
6151 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006152 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6153 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6154 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6155 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006156
Douglas Gregor67a65642009-02-17 23:15:12 +00006157 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006158 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006159 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006160 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6161
6162 if (!ClassTemplate) {
6163 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006164 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006165 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6166 return true;
6167 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006168
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006169 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006170 bool isPartialSpecialization = false;
6171
Douglas Gregorf47b9112009-02-25 22:02:03 +00006172 // Check the validity of the template headers that introduce this
6173 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006174 // FIXME: We probably shouldn't complain about these headers for
6175 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006176 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006177 TemplateParameterList *TemplateParams =
6178 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006179 KWLoc, TemplateNameLoc, SS, &TemplateId,
6180 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6181 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006182 if (Invalid)
6183 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006184
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006185 if (TemplateParams && TemplateParams->size() > 0) {
6186 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006187
Douglas Gregorec9518b2010-12-21 08:14:57 +00006188 if (TUK == TUK_Friend) {
6189 Diag(KWLoc, diag::err_partial_specialization_friend)
6190 << SourceRange(LAngleLoc, RAngleLoc);
6191 return true;
6192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006193
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006194 // C++ [temp.class.spec]p10:
6195 // The template parameter list of a specialization shall not
6196 // contain default template argument values.
6197 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6198 Decl *Param = TemplateParams->getParam(I);
6199 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6200 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006201 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006202 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006203 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006204 }
6205 } else if (NonTypeTemplateParmDecl *NTTP
6206 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6207 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006208 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006209 diag::err_default_arg_in_partial_spec)
6210 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006211 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006212 }
6213 } else {
6214 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006215 if (TTP->hasDefaultArgument()) {
6216 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006217 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006218 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006219 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006220 }
6221 }
6222 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006223 } else if (TemplateParams) {
6224 if (TUK == TUK_Friend)
6225 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006226 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006227 SourceRange(TemplateParams->getTemplateLoc(),
6228 TemplateParams->getRAngleLoc()))
6229 << SourceRange(LAngleLoc, RAngleLoc);
6230 else
6231 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006232 } else {
6233 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006234 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006235
Douglas Gregor67a65642009-02-17 23:15:12 +00006236 // Check that the specialization uses the same tag kind as the
6237 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006238 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6239 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006240 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006241 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006242 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006243 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006244 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006245 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006246 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006247 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006248 diag::note_previous_use);
6249 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6250 }
6251
Douglas Gregorc40290e2009-03-09 23:48:35 +00006252 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006253 TemplateArgumentListInfo TemplateArgs =
6254 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006255
Douglas Gregor14406932011-01-03 20:35:03 +00006256 // Check for unexpanded parameter packs in any of the template arguments.
6257 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006258 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006259 UPPC_PartialSpecialization))
6260 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006261
Douglas Gregor67a65642009-02-17 23:15:12 +00006262 // Check that the template argument list is well-formed for this
6263 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006264 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006265 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6266 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006267 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006268
Douglas Gregor2373c592009-05-31 09:31:02 +00006269 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006270 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006271 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006272 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006273 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6274 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006275 return true;
6276
Douglas Gregor678d76c2011-07-01 01:22:09 +00006277 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006278 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006279 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006280 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006281 TemplateArgs.size(),
6282 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006283 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6284 << ClassTemplate->getDeclName();
6285 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006286 }
6287 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006288
Craig Topperc3ec1492014-05-26 06:22:03 +00006289 void *InsertPos = nullptr;
6290 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006291
6292 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006293 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006294 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006295 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006296 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006297
Craig Topperc3ec1492014-05-26 06:22:03 +00006298 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006299
Douglas Gregorf47b9112009-02-25 22:02:03 +00006300 // Check whether we can declare a class template specialization in
6301 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006302 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006303 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6304 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006305 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006306 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006307
Douglas Gregor15301382009-07-30 17:40:51 +00006308 // The canonical type
6309 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006310 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006311 // Build the canonical type that describes the converted template
6312 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006313 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6314 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006315 Converted.data(),
6316 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006317
6318 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006319 ClassTemplate->getInjectedClassNameSpecialization())) {
6320 // C++ [temp.class.spec]p9b3:
6321 //
6322 // -- The argument list of the specialization shall not be identical
6323 // to the implicit argument list of the primary template.
6324 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006325 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006326 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006327 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6328 ClassTemplate->getIdentifier(),
6329 TemplateNameLoc,
6330 Attr,
6331 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006332 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006333 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006334 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006335 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006336 }
Douglas Gregor15301382009-07-30 17:40:51 +00006337
Douglas Gregor2373c592009-05-31 09:31:02 +00006338 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006339 ClassTemplatePartialSpecializationDecl *PrevPartial
6340 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006341 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006342 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006343 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006344 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006345 TemplateParams,
6346 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006347 Converted.data(),
6348 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006349 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006350 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006351 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006352 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006353 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006354 Partial->setTemplateParameterListsInfo(
6355 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006356 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006357
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006358 if (!PrevPartial)
6359 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006360 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006361
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006362 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006363 // template specialization, make a note of that.
6364 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6365 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006366
Douglas Gregor91772d12009-06-13 00:26:55 +00006367 // Check that all of the template parameters of the class template
6368 // partial specialization are deducible from the template
6369 // arguments. If not, this class template partial specialization
6370 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006371 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006372 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006373 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006374 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006375
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006376 if (!DeducibleParams.all()) {
6377 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006378 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006379 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006380 << SourceRange(TemplateNameLoc, RAngleLoc);
6381 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6382 if (!DeducibleParams[I]) {
6383 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6384 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006385 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006386 diag::note_partial_spec_unused_parameter)
6387 << Param->getDeclName();
6388 else
Mike Stump11289f42009-09-09 15:08:12 +00006389 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006390 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006391 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006392 }
6393 }
6394 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006395 } else {
6396 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006397 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006398 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006399 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006400 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006401 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006402 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006403 Converted.data(),
6404 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006405 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006406 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006407 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006408 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006409 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006410 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006411
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006412 if (!PrevDecl)
6413 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006414
David Majnemer678f50b2015-11-18 19:49:19 +00006415 if (CurContext->isDependentContext()) {
6416 // -fms-extensions permits specialization of nested classes without
6417 // fully specializing the outer class(es).
6418 assert(getLangOpts().MicrosoftExt &&
6419 "Only possible with -fms-extensions!");
6420 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6421 CanonType = Context.getTemplateSpecializationType(
6422 CanonTemplate, Converted.data(), Converted.size());
6423 } else {
6424 CanonType = Context.getTypeDeclType(Specialization);
6425 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006426 }
6427
Douglas Gregor06db9f52009-10-12 20:18:28 +00006428 // C++ [temp.expl.spec]p6:
6429 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006430 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006431 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006432 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006433 // use occurs; no diagnostic is required.
6434 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006435 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006436 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006437 // Is there any previous explicit specialization declaration?
6438 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6439 Okay = true;
6440 break;
6441 }
6442 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006443
Douglas Gregorc854c662010-02-26 06:03:23 +00006444 if (!Okay) {
6445 SourceRange Range(TemplateNameLoc, RAngleLoc);
6446 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6447 << Context.getTypeDeclType(Specialization) << Range;
6448
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006450 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006451 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006452 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006453 return true;
6454 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006456
Douglas Gregor2208a292009-09-26 20:57:03 +00006457 // If this is not a friend, note that this is an explicit specialization.
6458 if (TUK != TUK_Friend)
6459 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006460
6461 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006462 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006463 RecordDecl *Def = Specialization->getDefinition();
6464 NamedDecl *Hidden = nullptr;
6465 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6466 SkipBody->ShouldSkip = true;
6467 makeMergedDefinitionVisible(Hidden, KWLoc);
6468 // From here on out, treat this as just a redeclaration.
6469 TUK = TUK_Declaration;
6470 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006471 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006472 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006473 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006474 Diag(Def->getLocation(), diag::note_previous_definition);
6475 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006476 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006477 }
6478 }
6479
John McCall659a3372010-12-18 03:30:47 +00006480 if (Attr)
6481 ProcessDeclAttributeList(S, Specialization, Attr);
6482
Richard Smith034b94a2012-08-17 03:20:55 +00006483 // Add alignment attributes if necessary; these attributes are checked when
6484 // the ASTContext lays out the structure.
6485 if (TUK == TUK_Definition) {
6486 AddAlignmentAttributesForRecord(Specialization);
6487 AddMsStructLayoutForRecord(Specialization);
6488 }
6489
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006490 if (ModulePrivateLoc.isValid())
6491 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6492 << (isPartialSpecialization? 1 : 0)
6493 << FixItHint::CreateRemoval(ModulePrivateLoc);
6494
Douglas Gregord56a91e2009-02-26 22:19:44 +00006495 // Build the fully-sugared type for this class template
6496 // specialization as the user wrote in the specialization
6497 // itself. This means that we'll pretty-print the type retrieved
6498 // from the specialization's declaration the way that the user
6499 // actually wrote the specialization, rather than formatting the
6500 // name based on the "canonical" representation used to store the
6501 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006502 TypeSourceInfo *WrittenTy
6503 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6504 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006505 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006506 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006507 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006508 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006509
Douglas Gregor1e249f82009-02-25 22:18:32 +00006510 // C++ [temp.expl.spec]p9:
6511 // A template explicit specialization is in the scope of the
6512 // namespace in which the template was defined.
6513 //
6514 // We actually implement this paragraph where we set the semantic
6515 // context (in the creation of the ClassTemplateSpecializationDecl),
6516 // but we also maintain the lexical context where the actual
6517 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006518 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006519
Douglas Gregor67a65642009-02-17 23:15:12 +00006520 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006521 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006522 Specialization->startDefinition();
6523
Douglas Gregor2208a292009-09-26 20:57:03 +00006524 if (TUK == TUK_Friend) {
6525 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6526 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006527 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006528 /*FIXME:*/KWLoc);
6529 Friend->setAccess(AS_public);
6530 CurContext->addDecl(Friend);
6531 } else {
6532 // Add the specialization into its lexical context, so that it can
6533 // be seen when iterating through the list of declarations in that
6534 // context. However, specializations are not found by name lookup.
6535 CurContext->addDecl(Specialization);
6536 }
John McCall48871652010-08-21 09:40:31 +00006537 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006538}
Douglas Gregor333489b2009-03-27 23:10:48 +00006539
John McCall48871652010-08-21 09:40:31 +00006540Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006541 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006542 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006543 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006544 ActOnDocumentableDecl(NewDecl);
6545 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006546}
6547
John McCall4f7ced62010-02-11 01:33:53 +00006548/// \brief Strips various properties off an implicit instantiation
6549/// that has just been explicitly specialized.
6550static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006551 D->dropAttr<DLLImportAttr>();
6552 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006553
Nico Webere4974382014-12-19 23:52:45 +00006554 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006555 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006556}
6557
Nico Webera8f80b32012-01-09 19:52:25 +00006558/// \brief Compute the diagnostic location for an explicit instantiation
6559// declaration or definition.
6560static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006561 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006562 // Explicit instantiations following a specialization have no effect and
6563 // hence no PointOfInstantiation. In that case, walk decl backwards
6564 // until a valid name loc is found.
6565 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006566 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6567 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006568 PrevDiagLoc = Prev->getLocation();
6569 }
6570 assert(PrevDiagLoc.isValid() &&
6571 "Explicit instantiation without point of instantiation?");
6572 return PrevDiagLoc;
6573}
6574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006575/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006576/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006578/// new specialization/instantiation will have any effect.
6579///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006580/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006581/// instantiation.
6582///
6583/// \param NewTSK the kind of the new explicit specialization or instantiation.
6584///
6585/// \param PrevDecl the previous declaration of the entity.
6586///
6587/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6588///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006589/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006590/// declaration was instantiated (either implicitly or explicitly).
6591///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006592/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006593/// specialization or instantiation has no effect and should be ignored.
6594///
6595/// \returns true if there was an error that should prevent the introduction of
6596/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006597bool
6598Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6599 TemplateSpecializationKind NewTSK,
6600 NamedDecl *PrevDecl,
6601 TemplateSpecializationKind PrevTSK,
6602 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006603 bool &HasNoEffect) {
6604 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006606 switch (NewTSK) {
6607 case TSK_Undeclared:
6608 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006609 assert(
6610 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6611 "previous declaration must be implicit!");
6612 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006613
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006614 case TSK_ExplicitSpecialization:
6615 switch (PrevTSK) {
6616 case TSK_Undeclared:
6617 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006619 // explicitly specialized or has merely been mentioned without any
6620 // instantiation.
6621 return false;
6622
6623 case TSK_ImplicitInstantiation:
6624 if (PrevPointOfInstantiation.isInvalid()) {
6625 // The declaration itself has not actually been instantiated, so it is
6626 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006627 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006628 return false;
6629 }
6630 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006631
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006632 case TSK_ExplicitInstantiationDeclaration:
6633 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634 assert((PrevTSK == TSK_ImplicitInstantiation ||
6635 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006636 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006637
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006638 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006640 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006641 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006642 // implicit instantiation to take place, in every translation unit in
6643 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006644 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006645 // Is there any previous explicit specialization declaration?
6646 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6647 return false;
6648 }
6649
Douglas Gregor1d957a32009-10-27 18:42:08 +00006650 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006651 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006652 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006653 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006654
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006655 return true;
6656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006658 case TSK_ExplicitInstantiationDeclaration:
6659 switch (PrevTSK) {
6660 case TSK_ExplicitInstantiationDeclaration:
6661 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006662 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006663 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006665 case TSK_Undeclared:
6666 case TSK_ImplicitInstantiation:
6667 // We're explicitly instantiating something that may have already been
6668 // implicitly instantiated; that's fine.
6669 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006670
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006671 case TSK_ExplicitSpecialization:
6672 // C++0x [temp.explicit]p4:
6673 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006674 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006675 // specialization for that template, the explicit instantiation has no
6676 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006677 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006678 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006679
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006680 case TSK_ExplicitInstantiationDefinition:
6681 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006682 // If an entity is the subject of both an explicit instantiation
6683 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006684 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006685 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006686 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006687
6688 // Explicit instantiations following a specialization have no effect and
6689 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6690 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006691 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6692 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006693 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006694 return false;
6695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006697 case TSK_ExplicitInstantiationDefinition:
6698 switch (PrevTSK) {
6699 case TSK_Undeclared:
6700 case TSK_ImplicitInstantiation:
6701 // We're explicitly instantiating something that may have already been
6702 // implicitly instantiated; that's fine.
6703 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006704
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006705 case TSK_ExplicitSpecialization:
6706 // C++ DR 259, C++0x [temp.explicit]p4:
6707 // For a given set of template parameters, if an explicit
6708 // instantiation of a template appears after a declaration of
6709 // an explicit specialization for that template, the explicit
6710 // instantiation has no effect.
6711 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006713 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006714 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006715 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006716 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6717 diag::ext_explicit_instantiation_after_specialization)
6718 << PrevDecl;
6719 Diag(PrevDecl->getLocation(),
6720 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006721 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006722 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006723
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006724 case TSK_ExplicitInstantiationDeclaration:
6725 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006727
6728 // C++0x [temp.explicit]p4:
6729 // For a given set of template parameters, if an explicit instantiation
6730 // of a template appears after a declaration of an explicit
6731 // specialization for that template, the explicit instantiation has no
6732 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006733 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006734 // Is there any previous explicit specialization declaration?
6735 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6736 HasNoEffect = true;
6737 break;
6738 }
6739 }
6740
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006741 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006742
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006743 case TSK_ExplicitInstantiationDefinition:
6744 // C++0x [temp.spec]p5:
6745 // For a given template and a given set of template-arguments,
6746 // - an explicit instantiation definition shall appear at most once
6747 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006748
6749 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6750 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006751 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006752 : diag::err_explicit_instantiation_duplicate)
6753 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006754 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006755 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006756 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006757 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006758 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006760
David Blaikie83d382b2011-09-23 05:06:16 +00006761 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006762}
6763
John McCallb9c78482010-04-08 09:05:18 +00006764/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006765/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006766///
James Dennettf14a6e52012-06-15 22:23:43 +00006767/// The only possible way to get a dependent function template specialization
6768/// is with a friend declaration, like so:
6769///
6770/// \code
6771/// template \<class T> void foo(T);
6772/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006773/// friend void foo<>(T);
6774/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006775/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006776///
6777/// There really isn't any useful analysis we can do here, so we
6778/// just store the information.
6779bool
6780Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6781 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6782 LookupResult &Previous) {
6783 // Remove anything from Previous that isn't a function template in
6784 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006785 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006786 LookupResult::Filter F = Previous.makeFilter();
6787 while (F.hasNext()) {
6788 NamedDecl *D = F.next()->getUnderlyingDecl();
6789 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006790 !FDLookupContext->InEnclosingNamespaceSetOf(
6791 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006792 F.erase();
6793 }
6794 F.done();
6795
6796 // Should this be diagnosed here?
6797 if (Previous.empty()) return true;
6798
6799 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6800 ExplicitTemplateArgs);
6801 return false;
6802}
6803
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006804/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006805/// specialization.
6806///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006807/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006808/// explicit function template specialization. On successful completion,
6809/// the function declaration \p FD will become a function template
6810/// specialization.
6811///
6812/// \param FD the function declaration, which will be updated to become a
6813/// function template specialization.
6814///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006815/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6816/// if any. Note that this may be valid info even when 0 arguments are
6817/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6818/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006819///
Francois Pichet3a44e432011-07-08 06:21:47 +00006820/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006821/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006822bool Sema::CheckFunctionTemplateSpecialization(
6823 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6824 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006825 // The set of function template specializations that could match this
6826 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006827 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006828 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6829 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006831 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6832 ConvertedTemplateArgs;
6833
Sebastian Redl50c68252010-08-31 00:36:30 +00006834 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006835 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6836 I != E; ++I) {
6837 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6838 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006840 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006841 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6842 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006843 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Richard Smith574f4f62013-01-14 05:37:29 +00006845 // When matching a constexpr member function template specialization
6846 // against the primary template, we don't yet know whether the
6847 // specialization has an implicit 'const' (because we don't know whether
6848 // it will be a static member function until we know which template it
6849 // specializes), so adjust it now assuming it specializes this template.
6850 QualType FT = FD->getType();
6851 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006852 CXXMethodDecl *OldMD =
6853 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006854 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006855 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006856 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6857 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006858 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006859 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006860 }
6861 }
6862
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006863 TemplateArgumentListInfo Args;
6864 if (ExplicitTemplateArgs)
6865 Args = *ExplicitTemplateArgs;
6866
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006867 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006868 // A trailing template-argument can be left unspecified in the
6869 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006870 // provided it can be deduced from the function argument type.
6871 // Perform template argument deduction to determine whether we may be
6872 // specializing this template.
6873 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006874 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006875 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006876 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6877 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006878 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006879 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006880 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006881 FailedCandidates.addCandidate()
6882 .set(FunTmpl->getTemplatedDecl(),
6883 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006884 (void)TDK;
6885 continue;
6886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006888 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006889 if (ExplicitTemplateArgs)
6890 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006891 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006892 }
6893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894
Douglas Gregor5de279c2009-09-26 03:41:46 +00006895 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006896 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006897 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006898 FD->getLocation(),
6899 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6900 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006901 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006902 PDiag(diag::note_function_template_spec_matched));
6903
John McCall58cc69d2010-01-27 01:50:18 +00006904 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006905 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006906
6907 // Ignore access information; it doesn't figure into redeclaration checking.
6908 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006909
6910 FunctionTemplateSpecializationInfo *SpecInfo
6911 = Specialization->getTemplateSpecializationInfo();
6912 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006913
6914 // Note: do not overwrite location info if previous template
6915 // specialization kind was explicit.
6916 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006917 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006918 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006919 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6920 // function can differ from the template declaration with respect to
6921 // the constexpr specifier.
6922 Specialization->setConstexpr(FD->isConstexpr());
6923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006925 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006926 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006927
6928 // If this is a friend declaration, then we're not really declaring
6929 // an explicit specialization.
6930 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006931
Douglas Gregor54888652009-10-07 00:13:32 +00006932 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006933 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006935 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006937 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006938 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006939
6940 // C++ [temp.expl.spec]p6:
6941 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006943 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006944 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006945 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006946 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006947 if (!isFriend &&
6948 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006949 TSK_ExplicitSpecialization,
6950 Specialization,
6951 SpecInfo->getTemplateSpecializationKind(),
6952 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006953 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006954 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006955
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006956 // Mark the prior declaration as an explicit specialization, so that later
6957 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006958 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006959 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006960 MarkUnusedFileScopedDecl(Specialization);
6961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006963 // Turn the given function declaration into a function template
6964 // specialization, with the template arguments from the previous
6965 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006966 // Take copies of (semantic and syntactic) template argument lists.
6967 const TemplateArgumentList* TemplArgs = new (Context)
6968 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006969 FD->setFunctionTemplateSpecialization(
6970 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
6971 SpecInfo->getTemplateSpecializationKind(),
6972 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006973
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006974 // The "previous declaration" for this function template specialization is
6975 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006976 Previous.clear();
6977 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006978 return false;
6979}
6980
Douglas Gregor86d142a2009-10-08 07:24:58 +00006981/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006982/// specialization.
6983///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006985/// explicit member function specialization. On successful completion,
6986/// the function declaration \p FD will become a member function
6987/// specialization.
6988///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006989/// \param Member the member declaration, which will be updated to become a
6990/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006991///
John McCall1f82f242009-11-18 22:49:29 +00006992/// \param Previous the set of declarations, one of which may be specialized
6993/// by this function specialization; the set will be modified to contain the
6994/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006995bool
John McCall1f82f242009-11-18 22:49:29 +00006996Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006997 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006998
Douglas Gregor86d142a2009-10-08 07:24:58 +00006999 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00007000 NamedDecl *Instantiation = nullptr;
7001 NamedDecl *InstantiatedFrom = nullptr;
7002 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007003
John McCall1f82f242009-11-18 22:49:29 +00007004 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007005 // Nowhere to look anyway.
7006 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007007 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7008 I != E; ++I) {
7009 NamedDecl *D = (*I)->getUnderlyingDecl();
7010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007011 QualType Adjusted = Function->getType();
7012 if (!hasExplicitCallingConv(Adjusted))
7013 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7014 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007015 Instantiation = Method;
7016 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007017 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007018 break;
7019 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007020 }
7021 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007022 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007023 VarDecl *PrevVar;
7024 if (Previous.isSingleResult() &&
7025 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007026 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00007027 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007028 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007029 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007030 }
7031 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007032 CXXRecordDecl *PrevRecord;
7033 if (Previous.isSingleResult() &&
7034 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7035 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007036 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007037 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007038 }
Richard Smith7d137e32012-03-23 03:33:32 +00007039 } else if (isa<EnumDecl>(Member)) {
7040 EnumDecl *PrevEnum;
7041 if (Previous.isSingleResult() &&
7042 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7043 Instantiation = PrevEnum;
7044 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7045 MSInfo = PrevEnum->getMemberSpecializationInfo();
7046 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007049 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007050 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007051 // specializations are always out-of-line, the caller will complain about
7052 // this mismatch later.
7053 return false;
7054 }
John McCalle820e5e2010-04-13 20:37:33 +00007055
7056 // If this is a friend, just bail out here before we start turning
7057 // things into explicit specializations.
7058 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7059 // Preserve instantiation information.
7060 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7061 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7062 cast<CXXMethodDecl>(InstantiatedFrom),
7063 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7064 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7065 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7066 cast<CXXRecordDecl>(InstantiatedFrom),
7067 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7068 }
7069
7070 Previous.clear();
7071 Previous.addDecl(Instantiation);
7072 return false;
7073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007074
Douglas Gregor86d142a2009-10-08 07:24:58 +00007075 // Make sure that this is a specialization of a member.
7076 if (!InstantiatedFrom) {
7077 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7078 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007079 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7080 return true;
7081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007082
Douglas Gregor06db9f52009-10-12 20:18:28 +00007083 // C++ [temp.expl.spec]p6:
7084 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007085 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007086 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007088 // use occurs; no diagnostic is required.
7089 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007090
Abramo Bagnara8075c852010-06-12 07:44:57 +00007091 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007092 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7093 TSK_ExplicitSpecialization,
7094 Instantiation,
7095 MSInfo->getTemplateSpecializationKind(),
7096 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007097 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007098 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007099
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007100 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007101 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007102 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007104 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007105 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007106
Douglas Gregor86d142a2009-10-08 07:24:58 +00007107 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007108 // the original declaration to note that it is an explicit specialization
7109 // (if it was previously an implicit instantiation). This latter step
7110 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007111 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007112 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7113 if (InstantiationFunction->getTemplateSpecializationKind() ==
7114 TSK_ImplicitInstantiation) {
7115 InstantiationFunction->setTemplateSpecializationKind(
7116 TSK_ExplicitSpecialization);
7117 InstantiationFunction->setLocation(Member->getLocation());
7118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119
Douglas Gregor86d142a2009-10-08 07:24:58 +00007120 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7121 cast<CXXMethodDecl>(InstantiatedFrom),
7122 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007123 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007124 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007125 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7126 if (InstantiationVar->getTemplateSpecializationKind() ==
7127 TSK_ImplicitInstantiation) {
7128 InstantiationVar->setTemplateSpecializationKind(
7129 TSK_ExplicitSpecialization);
7130 InstantiationVar->setLocation(Member->getLocation());
7131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007132
Larisse Voufo39a1e502013-08-06 01:03:05 +00007133 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7134 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007135 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007136 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007137 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7138 if (InstantiationClass->getTemplateSpecializationKind() ==
7139 TSK_ImplicitInstantiation) {
7140 InstantiationClass->setTemplateSpecializationKind(
7141 TSK_ExplicitSpecialization);
7142 InstantiationClass->setLocation(Member->getLocation());
7143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007144
Douglas Gregor86d142a2009-10-08 07:24:58 +00007145 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007146 cast<CXXRecordDecl>(InstantiatedFrom),
7147 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007148 } else {
7149 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7150 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7151 if (InstantiationEnum->getTemplateSpecializationKind() ==
7152 TSK_ImplicitInstantiation) {
7153 InstantiationEnum->setTemplateSpecializationKind(
7154 TSK_ExplicitSpecialization);
7155 InstantiationEnum->setLocation(Member->getLocation());
7156 }
7157
7158 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7159 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007161
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007162 // Save the caller the trouble of having to figure out which declaration
7163 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007164 Previous.clear();
7165 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007166 return false;
7167}
7168
Douglas Gregore47f5a72009-10-14 23:41:34 +00007169/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007170///
7171/// \returns true if a serious error occurs, false otherwise.
7172static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007173 SourceLocation InstLoc,
7174 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007175 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7176 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007178 if (CurContext->isRecord()) {
7179 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7180 << D;
7181 return true;
7182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Richard Smith050d2612011-10-18 02:28:33 +00007184 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007186 // template. If the name declared in the explicit instantiation is an
7187 // unqualified name, the explicit instantiation shall appear in the
7188 // namespace where its template is declared or, if that namespace is inline
7189 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007190 //
7191 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007192 if (WasQualifiedName) {
7193 if (CurContext->Encloses(OrigContext))
7194 return false;
7195 } else {
7196 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7197 return false;
7198 }
7199
7200 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7201 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007202 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007203 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007204 diag::err_explicit_instantiation_out_of_scope :
7205 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007206 << D << NS;
7207 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007208 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007209 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007210 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7211 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7212 << D << NS;
7213 } else
7214 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007215 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007216 diag::err_explicit_instantiation_must_be_global :
7217 diag::warn_explicit_instantiation_must_be_global_0x)
7218 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007219 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007220 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007221}
7222
7223/// \brief Determine whether the given scope specifier has a template-id in it.
7224static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7225 if (!SS.isSet())
7226 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007227
Richard Smith050d2612011-10-18 02:28:33 +00007228 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007229 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007230 // or a static data member of a class template specialization, the name of
7231 // the class template specialization in the qualified-id for the member
7232 // name shall be a simple-template-id.
7233 //
7234 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007235 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7236 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007237 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007238 if (isa<TemplateSpecializationType>(T))
7239 return true;
7240
7241 return false;
7242}
7243
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007244// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007245DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007246Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007247 SourceLocation ExternLoc,
7248 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007249 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007250 SourceLocation KWLoc,
7251 const CXXScopeSpec &SS,
7252 TemplateTy TemplateD,
7253 SourceLocation TemplateNameLoc,
7254 SourceLocation LAngleLoc,
7255 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007256 SourceLocation RAngleLoc,
7257 AttributeList *Attr) {
7258 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007259 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007260 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007261 // Check that the specialization uses the same tag kind as the
7262 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007263 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7264 assert(Kind != TTK_Enum &&
7265 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007266
7267 if (isa<TypeAliasTemplateDecl>(TD)) {
7268 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7269 Diag(TD->getTemplatedDecl()->getLocation(),
7270 diag::note_previous_use);
7271 return true;
7272 }
7273
7274 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7275
Douglas Gregord9034f02009-05-14 16:41:31 +00007276 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007277 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007278 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007279 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007280 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007281 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007282 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007283 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007284 diag::note_previous_use);
7285 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7286 }
7287
Douglas Gregore47f5a72009-10-14 23:41:34 +00007288 // C++0x [temp.explicit]p2:
7289 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290 // definition and an explicit instantiation declaration. An explicit
7291 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007292 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7293 ? TSK_ExplicitInstantiationDefinition
7294 : TSK_ExplicitInstantiationDeclaration;
7295
7296 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7297 // Check for dllexport class template instantiation declarations.
7298 for (AttributeList *A = Attr; A; A = A->getNext()) {
7299 if (A->getKind() == AttributeList::AT_DLLExport) {
7300 Diag(ExternLoc,
7301 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7302 Diag(A->getLoc(), diag::note_attribute);
7303 break;
7304 }
7305 }
7306
7307 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7308 Diag(ExternLoc,
7309 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7310 Diag(A->getLocation(), diag::note_attribute);
7311 }
7312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007313
Douglas Gregora1f49972009-05-13 00:25:59 +00007314 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007315 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007316 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007317
7318 // Check that the template argument list is well-formed for this
7319 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007320 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007321 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7322 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007323 return true;
7324
Douglas Gregora1f49972009-05-13 00:25:59 +00007325 // Find the class template specialization declaration that
7326 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007327 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007328 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007329 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007330
Abramo Bagnara8075c852010-06-12 07:44:57 +00007331 TemplateSpecializationKind PrevDecl_TSK
7332 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7333
Douglas Gregor54888652009-10-07 00:13:32 +00007334 // C++0x [temp.explicit]p2:
7335 // [...] An explicit instantiation shall appear in an enclosing
7336 // namespace of its template. [...]
7337 //
7338 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007339 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7340 SS.isSet()))
7341 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007342
Craig Topperc3ec1492014-05-26 06:22:03 +00007343 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007344
Abramo Bagnara8075c852010-06-12 07:44:57 +00007345 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007346 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007347 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007348 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007349 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007350 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007351 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007352
Abramo Bagnara8075c852010-06-12 07:44:57 +00007353 // Even though HasNoEffect == true means that this explicit instantiation
7354 // has no effect on semantics, we go on to put its syntax in the AST.
7355
7356 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7357 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007358 // Since the only prior class template specialization with these
7359 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007360 // declaration node as our own, updating the source location
7361 // for the template name to reflect our new declaration.
7362 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007363 Specialization = PrevDecl;
7364 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007365 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007366 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007367 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007368
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007369 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007370 // Create a new class template specialization declaration node for
7371 // this explicit specialization.
7372 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007373 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007374 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007375 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007376 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007377 Converted.data(),
7378 Converted.size(),
7379 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007380 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007381
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007382 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007383 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007384 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007385 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007386 }
7387
7388 // Build the fully-sugared type for this explicit instantiation as
7389 // the user wrote in the explicit instantiation itself. This means
7390 // that we'll pretty-print the type retrieved from the
7391 // specialization's declaration the way that the user actually wrote
7392 // the explicit instantiation, rather than formatting the name based
7393 // on the "canonical" representation used to store the template
7394 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007395 TypeSourceInfo *WrittenTy
7396 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7397 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007398 Context.getTypeDeclType(Specialization));
7399 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007400
Abramo Bagnara8075c852010-06-12 07:44:57 +00007401 // Set source locations for keywords.
7402 Specialization->setExternLoc(ExternLoc);
7403 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007404 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007405
Rafael Espindola0b062072012-01-03 06:04:21 +00007406 if (Attr)
7407 ProcessDeclAttributeList(S, Specialization, Attr);
7408
Abramo Bagnara8075c852010-06-12 07:44:57 +00007409 // Add the explicit instantiation into its lexical context. However,
7410 // since explicit instantiations are never found by name lookup, we
7411 // just put it into the declaration context directly.
7412 Specialization->setLexicalDeclContext(CurContext);
7413 CurContext->addDecl(Specialization);
7414
7415 // Syntax is now OK, so return if it has no other effect on semantics.
7416 if (HasNoEffect) {
7417 // Set the template specialization kind.
7418 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007419 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007420 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007421
7422 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007423 // A definition of a class template or class member template
7424 // shall be in scope at the point of the explicit instantiation of
7425 // the class template or class member template.
7426 //
7427 // This check comes when we actually try to perform the
7428 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007429 ClassTemplateSpecializationDecl *Def
7430 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007431 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007432 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007433 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007434 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007435 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007436 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7437 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007438
Douglas Gregor1d957a32009-10-27 18:42:08 +00007439 // Instantiate the members of this class template specialization.
7440 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007441 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007442 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007443 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7444
7445 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7446 // TSK_ExplicitInstantiationDefinition
7447 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007448 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007449 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007450 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007451
Hans Wennborgc0875502015-06-09 00:39:05 +00007452 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7453 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7454 // In the MS ABI, an explicit instantiation definition can add a dll
7455 // attribute to a template with a previous instantiation declaration.
7456 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007457 auto *A = cast<InheritableAttr>(
7458 getDLLAttr(Specialization)->clone(getASTContext()));
7459 A->setInherited(true);
7460 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007461
7462 // We reject explicit instantiations in class scope, so there should
7463 // never be any delayed exported classes to worry about.
7464 assert(DelayedDllExportClasses.empty() &&
7465 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007466 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007467 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007468
7469 // Propagate attribute to base class templates.
7470 for (auto &B : Def->bases()) {
7471 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7472 B.getType()->getAsCXXRecordDecl()))
7473 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7474 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007475 }
7476 }
7477
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007478 // Set the template specialization kind. Make sure it is set before
7479 // instantiating the members which will trigger ASTConsumer callbacks.
7480 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007481 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007482 } else {
7483
7484 // Set the template specialization kind.
7485 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007486 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007487
John McCall48871652010-08-21 09:40:31 +00007488 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007489}
7490
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007491// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007492DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007493Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007494 SourceLocation ExternLoc,
7495 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007496 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007497 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007498 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007499 IdentifierInfo *Name,
7500 SourceLocation NameLoc,
7501 AttributeList *Attr) {
7502
Douglas Gregord6ab8742009-05-28 23:31:59 +00007503 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007504 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007505 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007506 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007507 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007508 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007509 SourceLocation(), false, TypeResult(),
7510 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007511 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7512
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007513 if (!TagD)
7514 return true;
7515
John McCall48871652010-08-21 09:40:31 +00007516 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007517 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007518
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007519 if (Tag->isInvalidDecl())
7520 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007521
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007522 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7523 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7524 if (!Pattern) {
7525 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7526 << Context.getTypeDeclType(Record);
7527 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7528 return true;
7529 }
7530
Douglas Gregore47f5a72009-10-14 23:41:34 +00007531 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007532 // If the explicit instantiation is for a class or member class, the
7533 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007534 // simple-template-id.
7535 //
7536 // C++98 has the same restriction, just worded differently.
7537 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007538 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007539 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007540
Douglas Gregore47f5a72009-10-14 23:41:34 +00007541 // C++0x [temp.explicit]p2:
7542 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007543 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007544 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007545 TemplateSpecializationKind TSK
7546 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7547 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007548
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007549 // C++0x [temp.explicit]p2:
7550 // [...] An explicit instantiation shall appear in an enclosing
7551 // namespace of its template. [...]
7552 //
7553 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007554 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007555
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007556 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007557 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007558 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007559 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007560 PrevDecl = Record;
7561 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007562 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007563 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007564 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007565 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007566 PrevDecl,
7567 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007568 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007569 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007570 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007571 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007572 return TagD;
7573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574
Douglas Gregor12e49d32009-10-15 22:53:21 +00007575 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007576 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007577 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007578 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007579 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007580 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007582 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007583 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007584 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7585 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007586 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7587 << Pattern;
7588 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007589 } else {
7590 if (InstantiateClass(NameLoc, Record, Def,
7591 getTemplateInstantiationArgs(Record),
7592 TSK))
7593 return true;
7594
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007595 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007596 if (!RecordDef)
7597 return true;
7598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007599 }
7600
Douglas Gregor1d957a32009-10-27 18:42:08 +00007601 // Instantiate all of the members of the class.
7602 InstantiateClassMembers(NameLoc, RecordDef,
7603 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007604
Douglas Gregor88d292c2010-05-13 16:44:06 +00007605 if (TSK == TSK_ExplicitInstantiationDefinition)
7606 MarkVTableUsed(NameLoc, RecordDef, true);
7607
Mike Stump87c57ac2009-05-16 07:39:55 +00007608 // FIXME: We don't have any representation for explicit instantiations of
7609 // member classes. Such a representation is not needed for compilation, but it
7610 // should be available for clients that want to see all of the declarations in
7611 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007612 return TagD;
7613}
7614
John McCallfaf5fb42010-08-26 23:41:50 +00007615DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7616 SourceLocation ExternLoc,
7617 SourceLocation TemplateLoc,
7618 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007619 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007620 // TODO: check if/when DNInfo should replace Name.
7621 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7622 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007623 if (!Name) {
7624 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007625 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007626 diag::err_explicit_instantiation_requires_name)
7627 << D.getDeclSpec().getSourceRange()
7628 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007629
Douglas Gregor450f00842009-09-25 18:43:00 +00007630 return true;
7631 }
7632
7633 // The scope passed in may not be a decl scope. Zip up the scope tree until
7634 // we find one that is.
7635 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7636 (S->getFlags() & Scope::TemplateParamScope) != 0)
7637 S = S->getParent();
7638
7639 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007640 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7641 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007642 if (R.isNull())
7643 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007644
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007645 // C++ [dcl.stc]p1:
7646 // A storage-class-specifier shall not be specified in [...] an explicit
7647 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007648 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007649 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7650 << Name;
7651 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007652 } else if (D.getDeclSpec().getStorageClassSpec()
7653 != DeclSpec::SCS_unspecified) {
7654 // Complain about then remove the storage class specifier.
7655 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7656 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7657
7658 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007659 }
7660
Douglas Gregor3c74d412009-10-14 20:14:33 +00007661 // C++0x [temp.explicit]p1:
7662 // [...] An explicit instantiation of a function template shall not use the
7663 // inline or constexpr specifiers.
7664 // Presumably, this also applies to member functions of class templates as
7665 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007666 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007667 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007668 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007669 diag::err_explicit_instantiation_inline :
7670 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007671 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007672 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007673 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7674 // not already specified.
7675 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7676 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007677
Nathan Wilsonde498452016-02-08 05:34:00 +00007678 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7679 // applied only to the definition of a function template or variable template,
7680 // declared in namespace scope.
7681 if (D.getDeclSpec().isConceptSpecified()) {
7682 Diag(D.getDeclSpec().getConceptSpecLoc(),
7683 diag::err_concept_specified_specialization) << 0;
7684 return true;
7685 }
7686
Douglas Gregore47f5a72009-10-14 23:41:34 +00007687 // C++0x [temp.explicit]p2:
7688 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007689 // definition and an explicit instantiation declaration. An explicit
7690 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007691 TemplateSpecializationKind TSK
7692 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7693 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007694
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007695 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007696 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007697
7698 if (!R->isFunctionType()) {
7699 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007700 // A [...] static data member of a class template can be explicitly
7701 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007702 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007703 // C++1y [temp.explicit]p1:
7704 // A [...] variable [...] template specialization can be explicitly
7705 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007706 if (Previous.isAmbiguous())
7707 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007708
John McCall67c00872009-12-02 08:25:40 +00007709 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007710 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007711
Larisse Voufo39a1e502013-08-06 01:03:05 +00007712 if (!PrevTemplate) {
7713 if (!Prev || !Prev->isStaticDataMember()) {
7714 // We expect to see a data data member here.
7715 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7716 << Name;
7717 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7718 P != PEnd; ++P)
7719 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7720 return true;
7721 }
7722
7723 if (!Prev->getInstantiatedFromStaticDataMember()) {
7724 // FIXME: Check for explicit specialization?
7725 Diag(D.getIdentifierLoc(),
7726 diag::err_explicit_instantiation_data_member_not_instantiated)
7727 << Prev;
7728 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7729 // FIXME: Can we provide a note showing where this was declared?
7730 return true;
7731 }
7732 } else {
7733 // Explicitly instantiate a variable template.
7734
7735 // C++1y [dcl.spec.auto]p6:
7736 // ... A program that uses auto or decltype(auto) in a context not
7737 // explicitly allowed in this section is ill-formed.
7738 //
7739 // This includes auto-typed variable template instantiations.
7740 if (R->isUndeducedType()) {
7741 Diag(T->getTypeLoc().getLocStart(),
7742 diag::err_auto_not_allowed_var_inst);
7743 return true;
7744 }
7745
Richard Smithef985ac2013-09-18 02:10:12 +00007746 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7747 // C++1y [temp.explicit]p3:
7748 // If the explicit instantiation is for a variable, the unqualified-id
7749 // in the declaration shall be a template-id.
7750 Diag(D.getIdentifierLoc(),
7751 diag::err_explicit_instantiation_without_template_id)
7752 << PrevTemplate;
7753 Diag(PrevTemplate->getLocation(),
7754 diag::note_explicit_instantiation_here);
7755 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007756 }
7757
Richard Smithef985ac2013-09-18 02:10:12 +00007758 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007759 TemplateArgumentListInfo TemplateArgs =
7760 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007761
Larisse Voufo39a1e502013-08-06 01:03:05 +00007762 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7763 D.getIdentifierLoc(), TemplateArgs);
7764 if (Res.isInvalid())
7765 return true;
7766
7767 // Ignore access control bits, we don't need them for redeclaration
7768 // checking.
7769 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007771
Douglas Gregore47f5a72009-10-14 23:41:34 +00007772 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007773 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007774 // or a static data member of a class template specialization, the name of
7775 // the class template specialization in the qualified-id for the member
7776 // name shall be a simple-template-id.
7777 //
7778 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007779 //
Richard Smith5977d872013-09-18 21:55:14 +00007780 // This does not apply to variable template specializations, where the
7781 // template-id is in the unqualified-id instead.
7782 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007783 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007784 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007785 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007786
Douglas Gregore47f5a72009-10-14 23:41:34 +00007787 // Check the scope of this explicit instantiation.
7788 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007789
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007790 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007791 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7792 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007793 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007794 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007795 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007796 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007797
Larisse Voufo39a1e502013-08-06 01:03:05 +00007798 if (!HasNoEffect) {
7799 // Instantiate static data member or variable template.
7800
7801 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7802 if (PrevTemplate) {
7803 // Merge attributes.
7804 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7805 ProcessDeclAttributeList(S, Prev, Attr);
7806 }
7807 if (TSK == TSK_ExplicitInstantiationDefinition)
7808 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7809 }
7810
7811 // Check the new variable specialization against the parsed input.
7812 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7813 Diag(T->getTypeLoc().getLocStart(),
7814 diag::err_invalid_var_template_spec_type)
7815 << 0 << PrevTemplate << R << Prev->getType();
7816 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7817 << 2 << PrevTemplate->getDeclName();
7818 return true;
7819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007820
Douglas Gregor450f00842009-09-25 18:43:00 +00007821 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007822 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007824
7825 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007826 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007827 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007828 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007829 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007830 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007831 HasExplicitTemplateArgs = true;
7832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007833
Douglas Gregor450f00842009-09-25 18:43:00 +00007834 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007835 // A [...] function [...] can be explicitly instantiated from its template.
7836 // A member function [...] of a class template can be explicitly
7837 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007838 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007839 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007840 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007841 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7842 P != PEnd; ++P) {
7843 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007844 if (!HasExplicitTemplateArgs) {
7845 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007846 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7847 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007848 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007849
John McCall58cc69d2010-01-27 01:50:18 +00007850 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007851 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7852 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007853 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007854 }
7855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007856
Douglas Gregor450f00842009-09-25 18:43:00 +00007857 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7858 if (!FunTmpl)
7859 continue;
7860
Larisse Voufo98b20f12013-07-19 23:00:19 +00007861 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007862 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007863 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007864 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007865 (HasExplicitTemplateArgs ? &TemplateArgs
7866 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007867 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007868 // Keep track of almost-matches.
7869 FailedCandidates.addCandidate()
7870 .set(FunTmpl->getTemplatedDecl(),
7871 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007872 (void)TDK;
7873 continue;
7874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007875
John McCall58cc69d2010-01-27 01:50:18 +00007876 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007878
Douglas Gregor450f00842009-09-25 18:43:00 +00007879 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007880 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007881 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007882 D.getIdentifierLoc(),
7883 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7884 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7885 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007886
John McCall58cc69d2010-01-27 01:50:18 +00007887 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007888 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007889
7890 // Ignore access control bits, we don't need them for redeclaration checking.
7891 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
Alexey Bataev73983912014-11-06 10:10:50 +00007893 // C++11 [except.spec]p4
7894 // In an explicit instantiation an exception-specification may be specified,
7895 // but is not required.
7896 // If an exception-specification is specified in an explicit instantiation
7897 // directive, it shall be compatible with the exception-specifications of
7898 // other declarations of that function.
7899 if (auto *FPT = R->getAs<FunctionProtoType>())
7900 if (FPT->hasExceptionSpec()) {
7901 unsigned DiagID =
7902 diag::err_mismatched_exception_spec_explicit_instantiation;
7903 if (getLangOpts().MicrosoftExt)
7904 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7905 bool Result = CheckEquivalentExceptionSpec(
7906 PDiag(DiagID) << Specialization->getType(),
7907 PDiag(diag::note_explicit_instantiation_here),
7908 Specialization->getType()->getAs<FunctionProtoType>(),
7909 Specialization->getLocation(), FPT, D.getLocStart());
7910 // In Microsoft mode, mismatching exception specifications just cause a
7911 // warning.
7912 if (!getLangOpts().MicrosoftExt && Result)
7913 return true;
7914 }
7915
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007916 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007917 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007918 diag::err_explicit_instantiation_member_function_not_instantiated)
7919 << Specialization
7920 << (Specialization->getTemplateSpecializationKind() ==
7921 TSK_ExplicitSpecialization);
7922 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7923 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007924 }
7925
Douglas Gregorec9fd132012-01-14 16:38:05 +00007926 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007927 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7928 PrevDecl = Specialization;
7929
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007930 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007931 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007932 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007933 PrevDecl,
7934 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007935 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007936 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007937 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007938
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007939 // FIXME: We may still want to build some representation of this
7940 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007941 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007942 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007943 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007944
7945 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007946 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7947 if (Attr)
7948 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007949
Richard Smitheb36ddf2014-04-24 22:45:46 +00007950 if (Specialization->isDefined()) {
7951 // Let the ASTConsumer know that this function has been explicitly
7952 // instantiated now, and its linkage might have changed.
7953 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7954 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007955 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007956
Douglas Gregore47f5a72009-10-14 23:41:34 +00007957 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007959 // or a static data member of a class template specialization, the name of
7960 // the class template specialization in the qualified-id for the member
7961 // name shall be a simple-template-id.
7962 //
7963 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007964 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007965 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007966 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007967 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007968 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007969 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007970 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971
Douglas Gregore47f5a72009-10-14 23:41:34 +00007972 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007973 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007974 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007975 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007976 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007977
Douglas Gregor450f00842009-09-25 18:43:00 +00007978 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007979 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007980}
7981
John McCallfaf5fb42010-08-26 23:41:50 +00007982TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007983Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7984 const CXXScopeSpec &SS, IdentifierInfo *Name,
7985 SourceLocation TagLoc, SourceLocation NameLoc) {
7986 // This has to hold, because SS is expected to be defined.
7987 assert(Name && "Expected a name in a dependent tag");
7988
Aaron Ballman4a979672014-01-03 13:56:08 +00007989 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007990 if (!NNS)
7991 return true;
7992
Abramo Bagnara6150c882010-05-11 21:36:43 +00007993 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007994
Douglas Gregorba41d012010-04-24 16:38:41 +00007995 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7996 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007997 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007998 return true;
7999 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008000
Douglas Gregore7c20652011-03-02 00:47:37 +00008001 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008002 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008003 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8004
8005 // Create type-source location information for this type.
8006 TypeLocBuilder TLB;
8007 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008008 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008009 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8010 TL.setNameLoc(NameLoc);
8011 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008012}
8013
John McCallfaf5fb42010-08-26 23:41:50 +00008014TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008015Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8016 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008017 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008018 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008019 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008020
Richard Smith0bf8a4922011-10-18 20:49:44 +00008021 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8022 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008023 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008024 diag::warn_cxx98_compat_typename_outside_of_template :
8025 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008026 << FixItHint::CreateRemoval(TypenameLoc);
8027
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008028 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008029 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8030 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008031 if (T.isNull())
8032 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008033
8034 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8035 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008036 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008037 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008038 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008039 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008040 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008041 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008042 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008043 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008044 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008046
John McCallba7bf592010-08-24 05:47:05 +00008047 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008048}
8049
John McCallfaf5fb42010-08-26 23:41:50 +00008050TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008051Sema::ActOnTypenameType(Scope *S,
8052 SourceLocation TypenameLoc,
8053 const CXXScopeSpec &SS,
8054 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008055 TemplateTy TemplateIn,
8056 SourceLocation TemplateNameLoc,
8057 SourceLocation LAngleLoc,
8058 ASTTemplateArgsPtr TemplateArgsIn,
8059 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008060 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8061 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008062 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008063 diag::warn_cxx98_compat_typename_outside_of_template :
8064 diag::ext_typename_outside_of_template)
8065 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008066
8067 // Translate the parser's template argument list in our AST format.
8068 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8069 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8070
8071 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008072 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8073 // Construct a dependent template specialization type.
8074 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008075 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008076 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8077 DTN->getQualifier(),
8078 DTN->getIdentifier(),
8079 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008080
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008081 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008082 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008083 DependentTemplateSpecializationTypeLoc SpecTL
8084 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008085 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8086 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008087 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008088 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008089 SpecTL.setLAngleLoc(LAngleLoc);
8090 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008091 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8092 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008093 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008094 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008095
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008096 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8097 if (T.isNull())
8098 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008099
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008100 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008101 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008102 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008103 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008104 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8105 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008106 SpecTL.setLAngleLoc(LAngleLoc);
8107 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008108 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8109 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8110
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008111 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8112 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008113 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008114 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8115
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008116 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8117 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008118}
8119
Douglas Gregorb09518c2011-02-27 22:46:49 +00008120
Richard Smith6f8d2c62012-05-09 05:17:00 +00008121/// Determine whether this failed name lookup should be treated as being
8122/// disabled by a usage of std::enable_if.
8123static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8124 SourceRange &CondRange) {
8125 // We must be looking for a ::type...
8126 if (!II.isStr("type"))
8127 return false;
8128
8129 // ... within an explicitly-written template specialization...
8130 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8131 return false;
8132 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008133 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8134 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8135 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008136 return false;
8137 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008138 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008139
8140 // ... which names a complete class template declaration...
8141 const TemplateDecl *EnableIfDecl =
8142 EnableIfTST->getTemplateName().getAsTemplateDecl();
8143 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8144 return false;
8145
8146 // ... called "enable_if".
8147 const IdentifierInfo *EnableIfII =
8148 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8149 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8150 return false;
8151
8152 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008153 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008154 return true;
8155}
8156
Douglas Gregor333489b2009-03-27 23:10:48 +00008157/// \brief Build the type that describes a C++ typename specifier,
8158/// e.g., "typename T::type".
8159QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008160Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8161 SourceLocation KeywordLoc,
8162 NestedNameSpecifierLoc QualifierLoc,
8163 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008164 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008165 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008166 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008167
John McCall0b66eb32010-05-01 00:40:08 +00008168 DeclContext *Ctx = computeDeclContext(SS);
8169 if (!Ctx) {
8170 // If the nested-name-specifier is dependent and couldn't be
8171 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008172 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8173 return Context.getDependentNameType(Keyword,
8174 QualifierLoc.getNestedNameSpecifier(),
8175 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008176 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008177
John McCall0b66eb32010-05-01 00:40:08 +00008178 // If the nested-name-specifier refers to the current instantiation,
8179 // the "typename" keyword itself is superfluous. In C++03, the
8180 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8181 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008182 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008183
John McCall0b66eb32010-05-01 00:40:08 +00008184 if (RequireCompleteDeclContext(SS, Ctx))
8185 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008186
8187 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008188 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008189 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008190 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008191 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008192 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008193 case LookupResult::NotFound: {
8194 // If we're looking up 'type' within a template named 'enable_if', produce
8195 // a more specific diagnostic.
8196 SourceRange CondRange;
8197 if (isEnableIf(QualifierLoc, II, CondRange)) {
8198 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8199 << Ctx << CondRange;
8200 return QualType();
8201 }
8202
Douglas Gregore40876a2009-10-13 21:16:44 +00008203 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008204 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008205 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008206
8207 case LookupResult::FoundUnresolvedValue: {
8208 // We found a using declaration that is a value. Most likely, the using
8209 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008210 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008211 IILoc);
8212 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8213 << Name << Ctx << FullRange;
8214 if (UnresolvedUsingValueDecl *Using
8215 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008216 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008217 Diag(Loc, diag::note_using_value_decl_missing_typename)
8218 << FixItHint::CreateInsertion(Loc, "typename ");
8219 }
8220 }
8221 // Fall through to create a dependent typename type, from which we can recover
8222 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008223
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008224 case LookupResult::NotFoundInCurrentInstantiation:
8225 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008226 return Context.getDependentNameType(Keyword,
8227 QualifierLoc.getNestedNameSpecifier(),
8228 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008229
8230 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008231 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008232 // We found a type. Build an ElaboratedType, since the
8233 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008234 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008235 return Context.getElaboratedType(ETK_Typename,
8236 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008237 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008238 }
8239
8240 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008241 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008242 break;
8243
8244 case LookupResult::FoundOverloaded:
8245 DiagID = diag::err_typename_nested_not_type;
8246 Referenced = *Result.begin();
8247 break;
8248
John McCall6538c932009-10-10 05:48:19 +00008249 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008250 return QualType();
8251 }
8252
8253 // If we get here, it's because name lookup did not find a
8254 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008255 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008256 IILoc);
8257 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008258 if (Referenced)
8259 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8260 << Name;
8261 return QualType();
8262}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008263
8264namespace {
8265 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008266 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008267 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008268 SourceLocation Loc;
8269 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008270
Douglas Gregor15acfb92009-08-06 16:20:37 +00008271 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008272 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008273
Mike Stump11289f42009-09-09 15:08:12 +00008274 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008275 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008276 DeclarationName Entity)
8277 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008278 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008279
8280 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008281 /// transformed.
8282 ///
8283 /// For the purposes of type reconstruction, a type has already been
8284 /// transformed if it is NULL or if it is not dependent.
8285 bool AlreadyTransformed(QualType T) {
8286 return T.isNull() || !T->isDependentType();
8287 }
Mike Stump11289f42009-09-09 15:08:12 +00008288
8289 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008290 /// rebuilt.
8291 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008292
Douglas Gregor15acfb92009-08-06 16:20:37 +00008293 /// \brief Returns the name of the entity whose type is being rebuilt.
8294 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008295
Douglas Gregoref6ab412009-10-27 06:26:26 +00008296 /// \brief Sets the "base" location and entity when that
8297 /// information is known based on another transformation.
8298 void setBase(SourceLocation Loc, DeclarationName Entity) {
8299 this->Loc = Loc;
8300 this->Entity = Entity;
8301 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008302
8303 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8304 // Lambdas never need to be transformed.
8305 return E;
8306 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008307 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008308} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008309
Douglas Gregor15acfb92009-08-06 16:20:37 +00008310/// \brief Rebuilds a type within the context of the current instantiation.
8311///
Mike Stump11289f42009-09-09 15:08:12 +00008312/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008313/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008314/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008315/// partial specialization thereof). This routine will rebuild that type now
8316/// that we have entered the declarator's scope, which may produce different
8317/// canonical types, e.g.,
8318///
8319/// \code
8320/// template<typename T>
8321/// struct X {
8322/// typedef T* pointer;
8323/// pointer data();
8324/// };
8325///
8326/// template<typename T>
8327/// typename X<T>::pointer X<T>::data() { ... }
8328/// \endcode
8329///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008330/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008331/// since we do not know that we can look into X<T> when we parsed the type.
8332/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008333/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008334/// as the canonical type of T*, allowing the return types of the out-of-line
8335/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008336TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8337 SourceLocation Loc,
8338 DeclarationName Name) {
8339 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008340 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008341
Douglas Gregor15acfb92009-08-06 16:20:37 +00008342 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8343 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008344}
Douglas Gregorbe999392009-09-15 16:23:51 +00008345
John McCalldadc5752010-08-24 06:29:42 +00008346ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008347 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8348 DeclarationName());
8349 return Rebuilder.TransformExpr(E);
8350}
8351
John McCall99b2fe52010-04-29 23:50:39 +00008352bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008353 if (SS.isInvalid())
8354 return true;
John McCall2408e322010-04-27 00:57:59 +00008355
Douglas Gregor10176412011-02-25 16:07:42 +00008356 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008357 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8358 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008359 NestedNameSpecifierLoc Rebuilt
8360 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8361 if (!Rebuilt)
8362 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008363
Douglas Gregor10176412011-02-25 16:07:42 +00008364 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008365 return false;
John McCall2408e322010-04-27 00:57:59 +00008366}
8367
Douglas Gregor041b0842011-10-14 15:31:12 +00008368/// \brief Rebuild the template parameters now that we know we're in a current
8369/// instantiation.
8370bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8371 TemplateParameterList *Params) {
8372 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8373 Decl *Param = Params->getParam(I);
8374
8375 // There is nothing to rebuild in a type parameter.
8376 if (isa<TemplateTypeParmDecl>(Param))
8377 continue;
8378
8379 // Rebuild the template parameter list of a template template parameter.
8380 if (TemplateTemplateParmDecl *TTP
8381 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8382 if (RebuildTemplateParamsInCurrentInstantiation(
8383 TTP->getTemplateParameters()))
8384 return true;
8385
8386 continue;
8387 }
8388
8389 // Rebuild the type of a non-type template parameter.
8390 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8391 TypeSourceInfo *NewTSI
8392 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8393 NTTP->getLocation(),
8394 NTTP->getDeclName());
8395 if (!NewTSI)
8396 return true;
8397
8398 if (NewTSI != NTTP->getTypeSourceInfo()) {
8399 NTTP->setTypeSourceInfo(NewTSI);
8400 NTTP->setType(NewTSI->getType());
8401 }
8402 }
8403
8404 return false;
8405}
8406
Douglas Gregorbe999392009-09-15 16:23:51 +00008407/// \brief Produces a formatted string that describes the binding of
8408/// template parameters to template arguments.
8409std::string
8410Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8411 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008412 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008413}
8414
8415std::string
8416Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8417 const TemplateArgument *Args,
8418 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008419 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008420 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008421
Douglas Gregore62e6a02009-11-11 19:13:48 +00008422 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008423 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008424
Douglas Gregorbe999392009-09-15 16:23:51 +00008425 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008426 if (I >= NumArgs)
8427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008428
Douglas Gregorbe999392009-09-15 16:23:51 +00008429 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008430 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008431 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008432 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008433
Douglas Gregorbe999392009-09-15 16:23:51 +00008434 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008435 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008436 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008437 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008439
Douglas Gregor0192c232010-12-20 16:52:59 +00008440 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008441 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008442 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008443
8444 Out << ']';
8445 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008446}
Francois Pichet1c229c02011-04-22 22:18:13 +00008447
Richard Smithe40f2ba2013-08-07 21:41:30 +00008448void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8449 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008450 if (!FD)
8451 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008452
8453 LateParsedTemplate *LPT = new LateParsedTemplate;
8454
8455 // Take tokens to avoid allocations
8456 LPT->Toks.swap(Toks);
8457 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008458 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008459
8460 FD->setLateTemplateParsed(true);
8461}
8462
8463void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8464 if (!FD)
8465 return;
8466 FD->setLateTemplateParsed(false);
8467}
Francois Pichet1c229c02011-04-22 22:18:13 +00008468
8469bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8470 DeclContext *DC = CurContext;
8471
8472 while (DC) {
8473 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8474 const FunctionDecl *FD = RD->isLocalClass();
8475 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8476 } else if (DC->isTranslationUnit() || DC->isNamespace())
8477 return false;
8478
8479 DC = DC->getParent();
8480 }
8481 return false;
8482}