blob: b335e7e2602e1f7d06f83dc89311b8e7725d20a7 [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
Eric Fiselier6ad68552016-07-01 01:24:09 +000036#include <iterator>
Douglas Gregor5101c242008-12-05 18:15:24 +000037using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000039
John McCall9b72f892010-11-10 02:40:36 +000040// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
Douglas Gregorb7bfe792009-09-02 22:59:36 +000048/// \brief Determine whether the declaration found is acceptable as the name
49/// of a template and, if so, return that template declaration. Otherwise,
50/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000051static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000052 NamedDecl *Orig,
53 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000054 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000055
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000056 if (isa<TemplateDecl>(D)) {
57 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000058 return nullptr;
59
John McCalle9cccd82010-06-16 08:42:20 +000060 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000061 }
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregorb7bfe792009-09-02 22:59:36 +000063 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
64 // C++ [temp.local]p1:
65 // Like normal (non-template) classes, class templates have an
66 // injected-class-name (Clause 9). The injected-class-name
67 // can be used with or without a template-argument-list. When
68 // it is used without a template-argument-list, it is
69 // equivalent to the injected-class-name followed by the
70 // template-parameters of the class template enclosed in
71 // <>. When it is used with a template-argument-list, it
72 // refers to the specified class template specialization,
73 // which could be the current specialization or another
74 // specialization.
75 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000076 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077 if (Record->getDescribedClassTemplate())
78 return Record->getDescribedClassTemplate();
79
80 if (ClassTemplateSpecializationDecl *Spec
81 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
82 return Spec->getSpecializedTemplate();
83 }
Mike Stump11289f42009-09-09 15:08:12 +000084
Craig Topperc3ec1492014-05-26 06:22:03 +000085 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000086 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Craig Topperc3ec1492014-05-26 06:22:03 +000088 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000089}
90
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000091void Sema::FilterAcceptableTemplateNames(LookupResult &R,
92 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000093 // The set of class templates we've already seen.
94 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000095 LookupResult::Filter filter = R.makeFilter();
96 while (filter.hasNext()) {
97 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000098 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
99 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +0000100 if (!Repl)
101 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +0000102 else if (Repl != Orig) {
103
104 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000106 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000107 // one base class). If all of the injected-class-names that are found
108 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000109 // is used as a template-name, the reference refers to the class
110 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000112 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000113 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000114 filter.erase();
115 continue;
116 }
John McCallbd8062d2010-08-13 07:02:08 +0000117
118 // FIXME: we promote access to public here as a workaround to
119 // the fact that LookupResult doesn't let us remember that we
120 // found this template through a particular injected class name,
121 // which means we end up doing nasty things to the invariants.
122 // Pretending that access is public is *much* safer.
123 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000124 }
John McCalle66edc12009-11-24 19:00:30 +0000125 }
126 filter.done();
127}
128
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
130 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000131 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000132 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133 return true;
134
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000135 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000136}
137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000139 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000140 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000141 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000142 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000143 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000144 TemplateTy &TemplateResult,
145 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000149 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150
Douglas Gregor3cf81312009-11-03 23:16:33 +0000151 switch (Name.getKind()) {
152 case UnqualifiedId::IK_Identifier:
153 TName = DeclarationName(Name.Identifier);
154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000155
Douglas Gregor3cf81312009-11-03 23:16:33 +0000156 case UnqualifiedId::IK_OperatorFunctionId:
157 TName = Context.DeclarationNames.getCXXOperatorName(
158 Name.OperatorFunctionId.Operator);
159 break;
160
Alexis Hunted0530f2009-11-28 08:58:14 +0000161 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000162 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
163 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000164
Douglas Gregor3cf81312009-11-03 23:16:33 +0000165 default:
166 return TNK_Non_template;
167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCallba7bf592010-08-24 05:47:05 +0000169 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000170
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000171 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000172 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
173 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000174 if (R.empty()) return TNK_Non_template;
175 if (R.isAmbiguous()) {
176 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000177 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000178
179 // FIXME: we might have ambiguous templates, in which case we
180 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000181 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000182 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 TemplateName Template;
185 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCalld28ae272009-12-02 08:04:21 +0000187 unsigned ResultCount = R.end() - R.begin();
188 if (ResultCount > 1) {
189 // We assume that we'll preserve the qualifier from a function
190 // template name in other ways.
191 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
192 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000193
194 // We'll do this lookup again later.
195 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000196 } else {
John McCalld28ae272009-12-02 08:04:21 +0000197 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
198
199 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000200 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000201 Template = Context.getQualifiedTemplateName(Qualifier,
202 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000203 } else {
204 Template = TemplateName(TD);
205 }
206
John McCalldcc71402010-08-13 02:23:42 +0000207 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000208 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000209
210 // We'll do this lookup again later.
211 R.suppressDiagnostics();
212 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000213 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000214 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
215 isa<BuiltinTemplateDecl>(TD));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000216 TemplateKind =
217 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000218 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 }
Mike Stump11289f42009-09-09 15:08:12 +0000220
John McCalld28ae272009-12-02 08:04:21 +0000221 TemplateResult = TemplateTy::make(Template);
222 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000223}
224
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000225bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000226 SourceLocation IILoc,
227 Scope *S,
228 const CXXScopeSpec *SS,
229 TemplateTy &SuggestedTemplate,
230 TemplateNameKind &SuggestedKind) {
231 // We can't recover unless there's a dependent scope specifier preceding the
232 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000233 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
235 computeDeclContext(*SS))
236 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Douglas Gregor18473f32010-01-12 21:28:44 +0000238 // The code is missing a 'template' keyword prior to the dependent template
239 // name.
240 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
241 Diag(IILoc, diag::err_template_kw_missing)
242 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000243 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000244 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000245 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
246 SuggestedKind = TNK_Dependent_template_name;
247 return true;
248}
249
John McCalle66edc12009-11-24 19:00:30 +0000250void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000251 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000252 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000253 bool EnteringContext,
254 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000255 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000256 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000257 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000258 bool isDependent = false;
259 if (!ObjectType.isNull()) {
260 // This nested-name-specifier occurs in a member access expression, e.g.,
261 // x->B::f, and we are looking into the type of the object.
262 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
263 LookupCtx = computeDeclContext(ObjectType);
264 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000265 assert((isDependent || !ObjectType->isIncompleteType() ||
266 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000267 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000268
269 // Template names cannot appear inside an Objective-C class or object type.
270 if (ObjectType->isObjCObjectOrInterfaceType()) {
271 Found.clear();
272 return;
273 }
John McCalle66edc12009-11-24 19:00:30 +0000274 } else if (SS.isSet()) {
275 // This nested-name-specifier occurs after another nested-name-specifier,
276 // so long into the context associated with the prior nested-name-specifier.
277 LookupCtx = computeDeclContext(SS, EnteringContext);
278 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
John McCalle66edc12009-11-24 19:00:30 +0000280 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000281 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000282 return;
283 }
284
285 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000286 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000287 if (LookupCtx) {
288 // Perform "qualified" name lookup into the declaration context we
289 // computed, which is either the type of the base of a member access
290 // expression or the declaration context associated with a prior
291 // nested-name-specifier.
292 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000293 if (!ObjectType.isNull() && Found.empty()) {
294 // C++ [basic.lookup.classref]p1:
295 // In a class member access expression (5.2.5), if the . or -> token is
296 // immediately followed by an identifier followed by a <, the
297 // identifier must be looked up to determine whether the < is the
298 // beginning of a template argument list (14.2) or a less-than operator.
299 // The identifier is first looked up in the class of the object
300 // expression. If the identifier is not found, it is then looked up in
301 // the context of the entire postfix-expression and shall name a class
302 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000303 if (S) LookupName(Found, S);
304 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000305 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000306 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000307 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000308 // We cannot look into a dependent object type or nested nme
309 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000310 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000311 return;
312 } else {
313 // Perform unqualified name lookup in the current scope.
314 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000315
316 if (!ObjectType.isNull())
317 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000318 }
319
Douglas Gregorc119dd52010-01-12 17:06:20 +0000320 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000321 // If we did not find any names, attempt to correct any typos.
322 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000323 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000324 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000325 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
326 FilterCCC->WantTypeSpecifiers = false;
327 FilterCCC->WantExpressionKeywords = false;
328 FilterCCC->WantRemainingKeywords = false;
329 FilterCCC->WantCXXNamedCasts = true;
330 if (TypoCorrection Corrected = CorrectTypo(
331 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
332 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000333 Found.setLookupName(Corrected.getCorrection());
Richard Smithde6d6c42015-12-29 19:43:10 +0000334 if (auto *ND = Corrected.getFoundDecl())
335 Found.addDecl(ND);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000336 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000337 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000338 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000339 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
340 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
343 << Name << LookupCtx << DroppedSpecifier
344 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000345 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000346 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000347 }
John McCalle9cccd82010-06-16 08:42:20 +0000348 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000349 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000350 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000351 }
352 }
353
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000354 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 if (Found.empty()) {
356 if (isDependent)
357 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000358 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000359 }
John McCalle66edc12009-11-24 19:00:30 +0000360
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000361 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000362 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000363 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000364 // [...] If the lookup in the class of the object expression finds a
365 // template, the name is also looked up in the context of the entire
366 // postfix-expression and [...]
367 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000368 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000369 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
370 LookupOrdinaryName);
371 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000372 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000373
John McCalle66edc12009-11-24 19:00:30 +0000374 if (FoundOuter.empty()) {
375 // - if the name is not found, the name found in the class of the
376 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000377 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
378 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000379 // - if the name is found in the context of the entire
380 // postfix-expression and does not name a class template, the name
381 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000382 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000383 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000384 // - if the name found is a class template, it must refer to the same
385 // entity as the one found in the class of the object expression,
386 // otherwise the program is ill-formed.
387 if (!Found.isSingleResult() ||
388 Found.getFoundDecl()->getCanonicalDecl()
389 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000391 diag::ext_nested_name_member_ref_lookup_ambiguous)
392 << Found.getLookupName()
393 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000394 Diag(Found.getRepresentativeDecl()->getLocation(),
395 diag::note_ambig_member_ref_object_type)
396 << ObjectType;
397 Diag(FoundOuter.getFoundDecl()->getLocation(),
398 diag::note_ambig_member_ref_scope);
399
400 // Recover by taking the template that we found in the object
401 // expression's type.
402 }
403 }
404 }
405}
406
John McCallcd4b4772009-12-02 03:53:29 +0000407/// ActOnDependentIdExpression - Handle a dependent id-expression that
408/// was just parsed. This is only possible with an explicit scope
409/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000410ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000411Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000412 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000413 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000414 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000415 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000416 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Reid Kleckner1af391df2016-03-11 18:59:12 +0000418 // C++11 [expr.prim.general]p12:
419 // An id-expression that denotes a non-static data member or non-static
420 // member function of a class can only be used:
421 // (...)
422 // - if that id-expression denotes a non-static data member and it
423 // appears in an unevaluated operand.
424 //
425 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
426 // CXXDependentScopeMemberExpr. The former can instantiate to either
427 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
428 // always a MemberExpr.
429 bool MightBeCxx11UnevalField =
430 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
431
Akira Hatanakad644e022016-12-16 03:19:41 +0000432 // Check if the nested name specifier is an enum type.
433 bool IsEnum = false;
434 if (NestedNameSpecifier *NNS = SS.getScopeRep())
435 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
436
437 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
Reid Kleckner1af391df2016-03-11 18:59:12 +0000438 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000439 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
John McCalle66edc12009-11-24 19:00:30 +0000441 // Since the 'this' expression is synthesized, we don't need to
442 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000443 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000444
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000445 return CXXDependentScopeMemberExpr::Create(
446 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
447 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
448 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000449 }
450
Abramo Bagnara7945c982012-01-27 09:46:47 +0000451 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000452}
453
John McCalldadc5752010-08-24 06:29:42 +0000454ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000455Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000456 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000457 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000458 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000459 return DependentScopeDeclRefExpr::Create(
460 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
461 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000462}
463
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000464
465/// Determine whether we would be unable to instantiate this template (because
466/// it either has no definition, or is in the process of being instantiated).
467bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
468 NamedDecl *Instantiation,
469 bool InstantiatedFromMember,
470 const NamedDecl *Pattern,
471 const NamedDecl *PatternDef,
472 TemplateSpecializationKind TSK,
473 bool Complain /*= true*/) {
Richard Smithedbc6e92016-10-14 21:41:24 +0000474 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
475 isa<VarDecl>(Instantiation));
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000476
Richard Smithedbc6e92016-10-14 21:41:24 +0000477 bool IsEntityBeingDefined = false;
478 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
479 IsEntityBeingDefined = TD->isBeingDefined();
480
481 if (PatternDef && !IsEntityBeingDefined) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000482 NamedDecl *SuggestedDef = nullptr;
483 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
484 /*OnlyNeedComplete*/false)) {
485 // If we're allowed to diagnose this and recover, do so.
486 bool Recover = Complain && !isSFINAEContext();
487 if (Complain)
488 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
489 Sema::MissingImportKind::Definition, Recover);
490 return !Recover;
491 }
492 return false;
493 }
494
Richard Smith6f4e2e02016-08-23 19:41:39 +0000495 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
496 return true;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000497
Richard Smithedbc6e92016-10-14 21:41:24 +0000498 llvm::Optional<unsigned> Note;
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000499 QualType InstantiationTy;
500 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
501 InstantiationTy = Context.getTypeDeclType(TD);
Richard Smith6f4e2e02016-08-23 19:41:39 +0000502 if (PatternDef) {
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000503 Diag(PointOfInstantiation,
504 diag::err_template_instantiate_within_definition)
Richard Smithedbc6e92016-10-14 21:41:24 +0000505 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000506 << InstantiationTy;
507 // Not much point in noting the template declaration here, since
508 // we're lexically inside it.
509 Instantiation->setInvalidDecl();
510 } else if (InstantiatedFromMember) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000511 if (isa<FunctionDecl>(Instantiation)) {
512 Diag(PointOfInstantiation,
513 diag::err_explicit_instantiation_undefined_member)
Richard Smithedbc6e92016-10-14 21:41:24 +0000514 << /*member function*/ 1 << Instantiation->getDeclName()
515 << Instantiation->getDeclContext();
516 Note = diag::note_explicit_instantiation_here;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000517 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000518 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
Richard Smith6f4e2e02016-08-23 19:41:39 +0000519 Diag(PointOfInstantiation,
520 diag::err_implicit_instantiate_member_undefined)
521 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000522 Note = diag::note_member_declared_at;
Richard Smith6f4e2e02016-08-23 19:41:39 +0000523 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000524 } else {
Richard Smithedbc6e92016-10-14 21:41:24 +0000525 if (isa<FunctionDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000526 Diag(PointOfInstantiation,
527 diag::err_explicit_instantiation_undefined_func_template)
528 << Pattern;
Richard Smithedbc6e92016-10-14 21:41:24 +0000529 Note = diag::note_explicit_instantiation_here;
530 } else if (isa<TagDecl>(Instantiation)) {
Richard Smith6f4e2e02016-08-23 19:41:39 +0000531 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
532 << (TSK != TSK_ImplicitInstantiation)
533 << InstantiationTy;
Richard Smithedbc6e92016-10-14 21:41:24 +0000534 Note = diag::note_template_decl_here;
535 } else {
536 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
537 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
538 Diag(PointOfInstantiation,
539 diag::err_explicit_instantiation_undefined_var_template)
540 << Instantiation;
541 Instantiation->setInvalidDecl();
542 } else
543 Diag(PointOfInstantiation,
544 diag::err_explicit_instantiation_undefined_member)
545 << /*static data member*/ 2 << Instantiation->getDeclName()
546 << Instantiation->getDeclContext();
547 Note = diag::note_explicit_instantiation_here;
548 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000549 }
Richard Smithedbc6e92016-10-14 21:41:24 +0000550 if (Note) // Diagnostics were emitted.
551 Diag(Pattern->getLocation(), Note.getValue());
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000552
553 // In general, Instantiation isn't marked invalid to get more than one
554 // error for multiple undefined instantiations. But the code that does
555 // explicit declaration -> explicit definition conversion can't handle
556 // invalid declarations, so mark as invalid in that case.
557 if (TSK == TSK_ExplicitInstantiationDeclaration)
558 Instantiation->setInvalidDecl();
559 return true;
560}
561
Douglas Gregor5101c242008-12-05 18:15:24 +0000562/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
563/// that the template parameter 'PrevDecl' is being shadowed by a new
564/// declaration at location Loc. Returns true to indicate that this is
565/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000566void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000567 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000568
569 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000570 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000571 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000572
573 // C++ [temp.local]p4:
574 // A template-parameter shall not be redeclared within its
575 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000576 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 << cast<NamedDecl>(PrevDecl)->getDeclName();
578 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000579}
580
Douglas Gregor463421d2009-03-03 04:44:36 +0000581/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000582/// the parameter D to reference the templated declaration and return a pointer
583/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000584TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
585 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
586 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000587 return Temp;
588 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000589 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000590}
591
Douglas Gregoreb29d182011-01-05 17:40:24 +0000592ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
593 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000595 "Only template template arguments can be pack expansions here");
596 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
597 "Template template argument pack expansion without packs");
598 ParsedTemplateArgument Result(*this);
599 Result.EllipsisLoc = EllipsisLoc;
600 return Result;
601}
602
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000603static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
604 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000606 switch (Arg.getKind()) {
607 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000608 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000609 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000611 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000612 return TemplateArgumentLoc(TemplateArgument(T), DI);
613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000615 case ParsedTemplateArgument::NonType: {
616 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
617 return TemplateArgumentLoc(TemplateArgument(E), E);
618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000620 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000621 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000622 TemplateArgument TArg;
623 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000624 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000625 else
626 TArg = Template;
627 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000628 Arg.getScopeSpec().getWithLocInContext(
629 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000630 Arg.getLocation(),
631 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000632 }
633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000635 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000636}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000638/// \brief Translates template arguments as provided by the parser
639/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000640void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
641 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000642 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000643 TemplateArgs.addArgument(translateTemplateArgument(*this,
644 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000645}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000646
Richard Smithb80d5402013-06-25 22:21:36 +0000647static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
648 SourceLocation Loc,
649 IdentifierInfo *Name) {
650 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
651 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
652 if (PrevDecl && PrevDecl->isTemplateParameter())
653 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
654}
655
Douglas Gregor5101c242008-12-05 18:15:24 +0000656/// ActOnTypeParameter - Called when a C++ template type parameter
657/// (e.g., "typename T") has been parsed. Typename specifies whether
658/// the keyword "typename" was used to declare the type parameter
659/// (otherwise, "class" was used), and KeyLoc is the location of the
660/// "class" or "typename" keyword. ParamName is the name of the
661/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000662/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000663/// If the type parameter has a default argument, it will be added
664/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000665Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000666 SourceLocation EllipsisLoc,
667 SourceLocation KeyLoc,
668 IdentifierInfo *ParamName,
669 SourceLocation ParamNameLoc,
670 unsigned Depth, unsigned Position,
671 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000672 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000673 assert(S->isTemplateParamScope() &&
674 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000675
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000676 SourceLocation Loc = ParamNameLoc;
677 if (!ParamName)
678 Loc = KeyLoc;
679
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000680 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000681 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000682 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000683 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000684 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000685 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000686
687 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000688 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
689
Douglas Gregor5101c242008-12-05 18:15:24 +0000690 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000691 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000692 IdResolver.AddDecl(Param);
693 }
694
Douglas Gregorf5500772011-01-05 15:48:55 +0000695 // C++0x [temp.param]p9:
696 // A default template-argument may be specified for any kind of
697 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000698 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000699 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000700 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000701 }
702
Douglas Gregordc13ded2010-07-01 00:00:45 +0000703 // Handle the default argument, if provided.
704 if (DefaultArg) {
705 TypeSourceInfo *DefaultTInfo;
706 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707
Douglas Gregordc13ded2010-07-01 00:00:45 +0000708 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000710 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000712 UPPC_DefaultArgument))
713 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregordc13ded2010-07-01 00:00:45 +0000715 // Check the template argument itself.
716 if (CheckTemplateArgument(Param, DefaultTInfo)) {
717 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000718 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720
Richard Smith1469b912015-06-10 00:29:03 +0000721 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
John McCall48871652010-08-21 09:40:31 +0000724 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000725}
726
Douglas Gregor463421d2009-03-03 04:44:36 +0000727/// \brief Check that the type of a non-type template parameter is
728/// well-formed.
729///
730/// \returns the (possibly-promoted) parameter type if valid;
731/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000732QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000733Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000734 // We don't allow variably-modified types as the type of non-type template
735 // parameters.
736 if (T->isVariablyModifiedType()) {
737 Diag(Loc, diag::err_variably_modified_nontype_template_param)
738 << T;
739 return QualType();
740 }
741
Douglas Gregor463421d2009-03-03 04:44:36 +0000742 // C++ [temp.param]p4:
743 //
744 // A non-type template-parameter shall have one of the following
745 // (optionally cv-qualified) types:
746 //
747 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000748 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000749 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000750 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000751 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000752 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000753 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000754 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000755 // -- std::nullptr_t.
756 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000757 // If T is a dependent type, we can't do the check now, so we
758 // assume that it is well-formed.
Richard Smith5f274382016-09-28 23:55:27 +0000759 T->isDependentType() ||
760 // Allow use of auto in template parameter declarations.
761 T->isUndeducedType()) {
762 if (T->isUndeducedType()) {
763 Diag(Loc, diag::warn_cxx14_compat_template_nontype_parm_auto_type)
764 << QualType(T->getContainedAutoType(), 0);
765 }
Richard Smithd0e1c952012-03-13 07:21:50 +0000766 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
767 // are ignored when determining its type.
768 return T.getUnqualifiedType();
769 }
770
Douglas Gregor463421d2009-03-03 04:44:36 +0000771 // C++ [temp.param]p8:
772 //
773 // A non-type template-parameter of type "array of T" or
774 // "function returning T" is adjusted to be of type "pointer to
775 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000776 else if (T->isArrayType() || T->isFunctionType())
777 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778
Douglas Gregor463421d2009-03-03 04:44:36 +0000779 Diag(Loc, diag::err_template_nontype_parm_bad_type)
780 << T;
781
782 return QualType();
783}
784
John McCall48871652010-08-21 09:40:31 +0000785Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
786 unsigned Depth,
787 unsigned Position,
788 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000789 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000790 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
791 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000792
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000793 assert(S->isTemplateParamScope() &&
794 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000795 bool Invalid = false;
796
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000797 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
798 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000799 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000800 Invalid = true;
801 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Richard Smithb80d5402013-06-25 22:21:36 +0000803 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000804 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000805 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000806 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000807 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000808 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000810 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000811 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000812
Douglas Gregor5101c242008-12-05 18:15:24 +0000813 if (Invalid)
814 Param->setInvalidDecl();
815
Richard Smithb80d5402013-06-25 22:21:36 +0000816 if (ParamName) {
817 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
818 ParamName);
819
Douglas Gregor5101c242008-12-05 18:15:24 +0000820 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000821 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000822 IdResolver.AddDecl(Param);
823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregorf5500772011-01-05 15:48:55 +0000825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
828 if (Default && IsParameterPack) {
829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000830 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000831 }
832
Douglas Gregordc13ded2010-07-01 00:00:45 +0000833 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000834 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000835 // Check for unexpanded parameter packs.
836 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
837 return Param;
838
Douglas Gregordc13ded2010-07-01 00:00:45 +0000839 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000840 ExprResult DefaultRes =
841 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000842 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000843 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000844 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000845 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000846 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
Richard Smith1469b912015-06-10 00:29:03 +0000848 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
John McCall48871652010-08-21 09:40:31 +0000851 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000852}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000853
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000854/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000855/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000856/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000857Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
858 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000859 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000860 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000861 IdentifierInfo *Name,
862 SourceLocation NameLoc,
863 unsigned Depth,
864 unsigned Position,
865 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000866 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000867 assert(S->isTemplateParamScope() &&
868 "Template template parameter not in template parameter scope!");
869
870 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000871 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000872 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000873 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874 NameLoc.isInvalid()? TmpLoc : NameLoc,
875 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000876 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000877 Param->setAccess(AS_public);
878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000880 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000881 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000882 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
883
John McCall48871652010-08-21 09:40:31 +0000884 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000885 IdResolver.AddDecl(Param);
886 }
887
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000888 if (Params->size() == 0) {
889 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
890 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
891 Param->setInvalidDecl();
892 }
893
Douglas Gregorf5500772011-01-05 15:48:55 +0000894 // C++0x [temp.param]p9:
895 // A default template-argument may be specified for any kind of
896 // template-parameter that is not a template parameter pack.
897 if (IsParameterPack && !Default.isInvalid()) {
898 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
899 Default = ParsedTemplateArgument();
900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901
Douglas Gregordc13ded2010-07-01 00:00:45 +0000902 if (!Default.isInvalid()) {
903 // Check only that we have a template template argument. We don't want to
904 // try to check well-formedness now, because our template template parameter
905 // might have dependent types in its template parameters, which we wouldn't
906 // be able to match now.
907 //
908 // If none of the template template parameter's template arguments mention
909 // other template parameters, we could actually perform more checking here.
910 // However, it isn't worth doing.
911 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
912 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000913 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000914 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000915 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000916 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000917
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000918 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000919 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000920 DefaultArg.getArgument().getAsTemplate(),
921 UPPC_DefaultArgument))
922 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000923
Richard Smith1469b912015-06-10 00:29:03 +0000924 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000926
John McCall48871652010-08-21 09:40:31 +0000927 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000928}
929
Hubert Tongf608c052016-04-29 18:05:37 +0000930/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
931/// constrained by RequiresClause, that contains the template parameters in
932/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000933TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000934Sema::ActOnTemplateParameterList(unsigned Depth,
935 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000936 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000937 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000938 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000939 SourceLocation RAngleLoc,
940 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000941 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000942 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000943
David Majnemer902f8c62015-12-27 07:16:27 +0000944 return TemplateParameterList::Create(
945 Context, TemplateLoc, LAngleLoc,
946 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000947 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000948}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000949
John McCall3e11ebe2010-03-15 10:12:16 +0000950static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
951 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000952 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000953}
954
John McCallfaf5fb42010-08-26 23:41:50 +0000955DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000956Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000957 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000958 IdentifierInfo *Name, SourceLocation NameLoc,
959 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000960 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000961 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000962 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000963 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000964 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000965 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000966 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000967 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000968 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000969 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000970
971 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000972 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000973 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000974
Abramo Bagnara6150c882010-05-11 21:36:43 +0000975 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
976 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000977
978 // There is no such thing as an unnamed class template.
979 if (!Name) {
980 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000981 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000982 }
983
Richard Smith6483d222012-04-21 01:27:54 +0000984 // Find any previous declaration with this name. For a friend with no
985 // scope explicitly specified, we only look for tag declarations (per
986 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000987 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000988 LookupResult Previous(*this, Name, NameLoc,
989 (SS.isEmpty() && TUK == TUK_Friend)
990 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000991 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000992 if (SS.isNotEmpty() && !SS.isInvalid()) {
993 SemanticContext = computeDeclContext(SS, true);
994 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000995 // FIXME: Horrible, horrible hack! We can't currently represent this
996 // in the AST, and historically we have just ignored such friend
997 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000998 Diag(NameLoc, TUK == TUK_Friend
999 ? diag::warn_template_qualified_friend_ignored
1000 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +00001001 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +00001002 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004
John McCall0b66eb32010-05-01 00:40:08 +00001005 if (RequireCompleteDeclContext(SS, SemanticContext))
1006 return true;
1007
Douglas Gregor041b0842011-10-14 15:31:12 +00001008 // If we're adding a template to a dependent context, we may need to
1009 // rebuilding some of the types used within the template parameter list,
1010 // now that we know what the current instantiation is.
1011 if (SemanticContext->isDependentContext()) {
1012 ContextRAII SavedContext(*this, SemanticContext);
1013 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1014 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001015 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1016 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +00001017
John McCall27b18f82009-11-17 02:14:36 +00001018 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001019 } else {
1020 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +00001021
1022 // C++14 [class.mem]p14:
1023 // If T is the name of a class, then each of the following shall have a
1024 // name different from T:
1025 // -- every member template of class T
1026 if (TUK != TUK_Friend &&
1027 DiagnoseClassNameShadow(SemanticContext,
1028 DeclarationNameInfo(Name, NameLoc)))
1029 return true;
1030
John McCall27b18f82009-11-17 02:14:36 +00001031 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00001032 }
Mike Stump11289f42009-09-09 15:08:12 +00001033
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001034 if (Previous.isAmbiguous())
1035 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Craig Topperc3ec1492014-05-26 06:22:03 +00001037 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001038 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001039 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040
Serge Pavlove50bf752016-06-10 04:39:07 +00001041 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1042 // Maybe we will complain about the shadowed template parameter.
1043 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1044 // Just pretend that we didn't see the previous declaration.
1045 PrevDecl = nullptr;
1046 }
1047
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001048 // If there is a previous declaration with the same name, check
1049 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001050 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001051 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001052
1053 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001055 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001056 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001057 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1058 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001059 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001060 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1061 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1062 PrevClassTemplate
1063 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1064 ->getSpecializedTemplate();
1065 }
1066 }
1067
John McCalld43784f2009-12-18 11:25:59 +00001068 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001069 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070 // [...] When looking for a prior declaration of a class or a function
1071 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001072 // function is neither a qualified name nor a template-id, scopes outside
1073 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001074 if (!SS.isSet()) {
1075 DeclContext *OutermostContext = CurContext;
1076 while (!OutermostContext->isFileContext())
1077 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001078
Richard Smith61e582f2012-04-20 07:12:26 +00001079 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001080 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1081 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1082 SemanticContext = PrevDecl->getDeclContext();
1083 } else {
1084 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001086 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001087 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001088 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001089
1090 // Check that the chosen semantic context doesn't already contain a
1091 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001092 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001093 DeclContext *LookupContext = SemanticContext;
1094 while (LookupContext->isTransparentContext())
1095 LookupContext = LookupContext->getLookupParent();
1096 LookupQualifiedName(Previous, LookupContext);
1097
1098 if (Previous.isAmbiguous())
1099 return true;
1100
1101 if (Previous.begin() != Previous.end())
1102 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001103 }
John McCall90d3bb92009-12-17 23:21:11 +00001104 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001105 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001106 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1107 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001108 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001109
Richard Smithfc805ca2015-07-06 04:43:58 +00001110 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1111 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1112 if (SS.isEmpty() &&
1113 !(PrevClassTemplate &&
1114 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1115 SemanticContext->getRedeclContext()))) {
1116 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1117 Diag(Shadow->getTargetDecl()->getLocation(),
1118 diag::note_using_decl_target);
1119 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1120 // Recover by ignoring the old declaration.
1121 PrevDecl = PrevClassTemplate = nullptr;
1122 }
1123 }
1124
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001125 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001126 // Ensure that the template parameter lists are compatible. Skip this check
1127 // for a friend in a dependent context: the template parameter list itself
1128 // could be dependent.
1129 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1130 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001131 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001132 /*Complain=*/true,
1133 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001134 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001135
1136 // C++ [temp.class]p4:
1137 // In a redeclaration, partial specialization, explicit
1138 // specialization or explicit instantiation of a class template,
1139 // the class-key shall agree in kind with the original class
1140 // template declaration (7.1.5.3).
1141 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001142 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001143 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001144 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001145 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001146 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001147 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001148 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001149 }
1150
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001151 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001152 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001153 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001154 // If we have a prior definition that is not visible, treat this as
1155 // simply making that previous definition visible.
1156 NamedDecl *Hidden = nullptr;
1157 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001158 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001159 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1160 assert(Tmpl && "original definition of a class template is not a "
1161 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001162 makeMergedDefinitionVisible(Hidden, KWLoc);
1163 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001164 return Def;
1165 }
1166
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001167 Diag(NameLoc, diag::err_redefinition) << Name;
1168 Diag(Def->getLocation(), diag::note_previous_definition);
1169 // FIXME: Would it make sense to try to "forget" the previous
1170 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001171 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001172 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001173 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001174 } else if (PrevDecl) {
1175 // C++ [temp]p5:
1176 // A class template shall not have the same name as any other
1177 // template, class, function, object, enumeration, enumerator,
1178 // namespace, or type in the same scope (3.3), except as specified
1179 // in (14.5.4).
1180 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1181 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001182 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001183 }
1184
Douglas Gregordba32632009-02-10 19:49:53 +00001185 // Check the template parameter list of this declaration, possibly
1186 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001187 // template declaration. Skip this check for a friend in a dependent
1188 // context, because the template parameter list might be dependent.
1189 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001190 CheckTemplateParameterList(
1191 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001192 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1193 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001194 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1195 SemanticContext->isDependentContext())
1196 ? TPC_ClassTemplateMember
1197 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1198 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001199 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001200
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001201 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001203 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001204 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1205 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001206 : diag::err_member_decl_does_not_match)
1207 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001208 Invalid = true;
1209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001210 }
1211
Mike Stump11289f42009-09-09 15:08:12 +00001212 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001213 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001214 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001215 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001216 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001217 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001218 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001219 NewClass->setTemplateParameterListsInfo(
1220 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1221 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001222
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001223 // Add alignment attributes if necessary; these attributes are checked when
1224 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001225 if (TUK == TUK_Definition) {
1226 AddAlignmentAttributesForRecord(NewClass);
1227 AddMsStructLayoutForRecord(NewClass);
1228 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001229
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001230 ClassTemplateDecl *NewTemplate
1231 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1232 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001233 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001234 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001235
Douglas Gregor21823bf2011-12-20 18:11:52 +00001236 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001237 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001238
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001239 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001240 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001241 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001242 assert(T->isDependentType() && "Class template type is not dependent?");
1243 (void)T;
1244
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001245 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001246 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001247 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001248 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1249 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250
Anders Carlsson137108d2009-03-26 01:24:28 +00001251 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001252 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001253 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001254
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001255 // Set the lexical context of these templates
1256 NewClass->setLexicalDeclContext(CurContext);
1257 NewTemplate->setLexicalDeclContext(CurContext);
1258
John McCall9bb74a52009-07-31 02:45:11 +00001259 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001260 NewClass->startDefinition();
1261
1262 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001263 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001264
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001265 if (PrevClassTemplate)
1266 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1267
Rafael Espindola385c0422012-07-13 18:04:45 +00001268 AddPushedVisibilityAttribute(NewClass);
1269
Richard Smith234ff472014-08-23 00:49:01 +00001270 if (TUK != TUK_Friend) {
1271 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1272 Scope *Outer = S;
1273 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1274 Outer = Outer->getParent();
1275 PushOnScopeChains(NewTemplate, Outer);
1276 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001277 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001278 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001279 NewClass->setAccess(PrevClassTemplate->getAccess());
1280 }
John McCall27b5c252009-09-14 21:59:20 +00001281
Richard Smith64017682013-07-17 23:53:16 +00001282 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283
John McCall27b5c252009-09-14 21:59:20 +00001284 // Friend templates are visible in fairly strange ways.
1285 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001286 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001287 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001288 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1289 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001290 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001293 FriendDecl *Friend = FriendDecl::Create(
1294 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001295 Friend->setAccess(AS_public);
1296 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001297 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001298
Douglas Gregordba32632009-02-10 19:49:53 +00001299 if (Invalid) {
1300 NewTemplate->setInvalidDecl();
1301 NewClass->setInvalidDecl();
1302 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001303
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001304 ActOnDocumentableDecl(NewTemplate);
1305
John McCall48871652010-08-21 09:40:31 +00001306 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001307}
1308
Douglas Gregored5731f2009-11-25 17:50:39 +00001309/// \brief Diagnose the presence of a default template argument on a
1310/// template parameter, which is ill-formed in certain contexts.
1311///
1312/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001314 Sema::TemplateParamListContext TPC,
1315 SourceLocation ParamLoc,
1316 SourceRange DefArgRange) {
1317 switch (TPC) {
1318 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001319 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001320 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001321 return false;
1322
1323 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001324 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001326 // A default template-argument shall not be specified in a
1327 // function template declaration or a function template
1328 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001329 // If a friend function template declaration specifies a default
1330 // template-argument, that declaration shall be a definition and shall be
1331 // the only declaration of the function template in the translation unit.
1332 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001333 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001334 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1335 : diag::ext_template_parameter_default_in_function_template)
1336 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001337 return false;
1338
1339 case Sema::TPC_ClassTemplateMember:
1340 // C++0x [temp.param]p9:
1341 // A default template-argument shall not be specified in the
1342 // template-parameter-lists of the definition of a member of a
1343 // class template that appears outside of the member's class.
1344 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1345 << DefArgRange;
1346 return true;
1347
David Majnemerba8f17a2013-06-25 22:08:55 +00001348 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001349 case Sema::TPC_FriendFunctionTemplate:
1350 // C++ [temp.param]p9:
1351 // A default template-argument shall not be specified in a
1352 // friend template declaration.
1353 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1354 << DefArgRange;
1355 return true;
1356
1357 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1358 // for friend function templates if there is only a single
1359 // declaration (and it is a definition). Strange!
1360 }
1361
David Blaikie8a40f702012-01-17 06:56:22 +00001362 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001363}
1364
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001365/// \brief Check for unexpanded parameter packs within the template parameters
1366/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001367static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1368 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001369 // A template template parameter which is a parameter pack is also a pack
1370 // expansion.
1371 if (TTP->isParameterPack())
1372 return false;
1373
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001374 TemplateParameterList *Params = TTP->getTemplateParameters();
1375 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1376 NamedDecl *P = Params->getParam(I);
1377 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001378 if (!NTTP->isParameterPack() &&
1379 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001380 NTTP->getTypeSourceInfo(),
1381 Sema::UPPC_NonTypeTemplateParameterType))
1382 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001384 continue;
1385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386
1387 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001388 = dyn_cast<TemplateTemplateParmDecl>(P))
1389 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1390 return true;
1391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001393 return false;
1394}
1395
Douglas Gregordba32632009-02-10 19:49:53 +00001396/// \brief Checks the validity of a template parameter list, possibly
1397/// considering the template parameter list from a previous
1398/// declaration.
1399///
1400/// If an "old" template parameter list is provided, it must be
1401/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1402/// template parameter list.
1403///
1404/// \param NewParams Template parameter list for a new template
1405/// declaration. This template parameter list will be updated with any
1406/// default arguments that are carried through from the previous
1407/// template parameter list.
1408///
1409/// \param OldParams If provided, template parameter list from a
1410/// previous declaration of the same template. Default template
1411/// arguments will be merged from the old template parameter list to
1412/// the new template parameter list.
1413///
Douglas Gregored5731f2009-11-25 17:50:39 +00001414/// \param TPC Describes the context in which we are checking the given
1415/// template parameter list.
1416///
Douglas Gregordba32632009-02-10 19:49:53 +00001417/// \returns true if an error occurred, false otherwise.
1418bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001419 TemplateParameterList *OldParams,
1420 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001421 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001422
Douglas Gregordba32632009-02-10 19:49:53 +00001423 // C++ [temp.param]p10:
1424 // The set of default template-arguments available for use with a
1425 // template declaration or definition is obtained by merging the
1426 // default arguments from the definition (if in scope) and all
1427 // declarations in scope in the same way default function
1428 // arguments are (8.3.6).
1429 bool SawDefaultArgument = false;
1430 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001431
Mike Stumpc89c8e32009-02-11 23:03:27 +00001432 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001433 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001434 if (OldParams)
1435 OldParam = OldParams->begin();
1436
Douglas Gregor0693def2011-01-27 01:40:17 +00001437 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001438 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1439 NewParamEnd = NewParams->end();
1440 NewParam != NewParamEnd; ++NewParam) {
1441 // Variables used to diagnose redundant default arguments
1442 bool RedundantDefaultArg = false;
1443 SourceLocation OldDefaultLoc;
1444 SourceLocation NewDefaultLoc;
1445
David Blaikie651c73c2011-10-19 05:19:50 +00001446 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001447 bool MissingDefaultArg = false;
1448
David Blaikie651c73c2011-10-19 05:19:50 +00001449 // Variable used to diagnose non-final parameter packs
1450 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001451
Douglas Gregordba32632009-02-10 19:49:53 +00001452 if (TemplateTypeParmDecl *NewTypeParm
1453 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001454 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455 if (NewTypeParm->hasDefaultArgument() &&
1456 DiagnoseDefaultTemplateArgument(*this, TPC,
1457 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001458 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001459 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001460 NewTypeParm->removeDefaultArgument();
1461
1462 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001463 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001464 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001465 if (NewTypeParm->isParameterPack()) {
1466 assert(!NewTypeParm->hasDefaultArgument() &&
1467 "Parameter packs can't have a default argument!");
1468 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001469 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001470 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001471 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1472 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1473 SawDefaultArgument = true;
1474 RedundantDefaultArg = true;
1475 PreviousDefaultArgLoc = NewDefaultLoc;
1476 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1477 // Merge the default argument from the old declaration to the
1478 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001479 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001480 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1481 } else if (NewTypeParm->hasDefaultArgument()) {
1482 SawDefaultArgument = true;
1483 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1484 } else if (SawDefaultArgument)
1485 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001486 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001487 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001488 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001489 if (!NewNonTypeParm->isParameterPack() &&
1490 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001492 UPPC_NonTypeTemplateParameterType)) {
1493 Invalid = true;
1494 continue;
1495 }
1496
Douglas Gregored5731f2009-11-25 17:50:39 +00001497 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001498 if (NewNonTypeParm->hasDefaultArgument() &&
1499 DiagnoseDefaultTemplateArgument(*this, TPC,
1500 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001501 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001502 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001503 }
1504
Mike Stump12b8ce12009-08-04 21:02:39 +00001505 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001506 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001507 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001508 if (NewNonTypeParm->isParameterPack()) {
1509 assert(!NewNonTypeParm->hasDefaultArgument() &&
1510 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001511 if (!NewNonTypeParm->isPackExpansion())
1512 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001513 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001514 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001515 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1516 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1517 SawDefaultArgument = true;
1518 RedundantDefaultArg = true;
1519 PreviousDefaultArgLoc = NewDefaultLoc;
1520 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1521 // Merge the default argument from the old declaration to the
1522 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001523 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001524 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1525 } else if (NewNonTypeParm->hasDefaultArgument()) {
1526 SawDefaultArgument = true;
1527 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1528 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001529 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001530 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001531 TemplateTemplateParmDecl *NewTemplateParm
1532 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001533
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001534 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001535 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001536 Invalid = true;
1537 continue;
1538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001539
David Blaikie651c73c2011-10-19 05:19:50 +00001540 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541 if (NewTemplateParm->hasDefaultArgument() &&
1542 DiagnoseDefaultTemplateArgument(*this, TPC,
1543 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001544 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001545 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001546
1547 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001548 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001549 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001550 if (NewTemplateParm->isParameterPack()) {
1551 assert(!NewTemplateParm->hasDefaultArgument() &&
1552 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001553 if (!NewTemplateParm->isPackExpansion())
1554 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001555 } else if (OldTemplateParm &&
1556 hasVisibleDefaultArgument(OldTemplateParm) &&
1557 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001558 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1559 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001560 SawDefaultArgument = true;
1561 RedundantDefaultArg = true;
1562 PreviousDefaultArgLoc = NewDefaultLoc;
1563 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1564 // Merge the default argument from the old declaration to the
1565 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001566 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001567 PreviousDefaultArgLoc
1568 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001569 } else if (NewTemplateParm->hasDefaultArgument()) {
1570 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001571 PreviousDefaultArgLoc
1572 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001573 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001574 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001575 }
1576
Richard Smith1fde8ec2012-09-07 02:06:42 +00001577 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001578 // If a template parameter of a primary class template or alias template
1579 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001580 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001581 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1582 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001583 Diag((*NewParam)->getLocation(),
1584 diag::err_template_param_pack_must_be_last_template_parameter);
1585 Invalid = true;
1586 }
1587
Douglas Gregordba32632009-02-10 19:49:53 +00001588 if (RedundantDefaultArg) {
1589 // C++ [temp.param]p12:
1590 // A template-parameter shall not be given default arguments
1591 // by two different declarations in the same scope.
1592 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1593 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1594 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001595 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001596 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597 // If a template-parameter of a class template has a default
1598 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001599 // have a default template-argument supplied or be a template parameter
1600 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001601 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001602 diag::err_template_param_default_arg_missing);
1603 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1604 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001605 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001606 }
1607
1608 // If we have an old template parameter list that we're merging
1609 // in, move on to the next parameter.
1610 if (OldParams)
1611 ++OldParam;
1612 }
1613
Douglas Gregor0693def2011-01-27 01:40:17 +00001614 // We were missing some default arguments at the end of the list, so remove
1615 // all of the default arguments.
1616 if (RemoveDefaultArguments) {
1617 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1618 NewParamEnd = NewParams->end();
1619 NewParam != NewParamEnd; ++NewParam) {
1620 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1621 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001623 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1624 NTTP->removeDefaultArgument();
1625 else
1626 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1627 }
1628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629
Douglas Gregordba32632009-02-10 19:49:53 +00001630 return Invalid;
1631}
Douglas Gregord32e0282009-02-09 23:23:08 +00001632
John McCalla020a012010-10-20 05:44:58 +00001633namespace {
1634
1635/// A class which looks for a use of a certain level of template
1636/// parameter.
1637struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1638 typedef RecursiveASTVisitor<DependencyChecker> super;
1639
1640 unsigned Depth;
1641 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001642 SourceLocation MatchLoc;
1643
1644 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001645
1646 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1647 NamedDecl *ND = Params->getParam(0);
1648 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1649 Depth = PD->getDepth();
1650 } else if (NonTypeTemplateParmDecl *PD =
1651 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1652 Depth = PD->getDepth();
1653 } else {
1654 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1655 }
1656 }
1657
Richard Smith6056d5e2014-02-09 00:54:43 +00001658 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001659 if (ParmDepth >= Depth) {
1660 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001661 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001662 return true;
1663 }
1664 return false;
1665 }
1666
Richard Smith6056d5e2014-02-09 00:54:43 +00001667 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1668 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1669 }
1670
John McCalla020a012010-10-20 05:44:58 +00001671 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1672 return !Matches(T->getDepth());
1673 }
1674
1675 bool TraverseTemplateName(TemplateName N) {
1676 if (TemplateTemplateParmDecl *PD =
1677 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001678 if (Matches(PD->getDepth()))
1679 return false;
John McCalla020a012010-10-20 05:44:58 +00001680 return super::TraverseTemplateName(N);
1681 }
1682
1683 bool VisitDeclRefExpr(DeclRefExpr *E) {
1684 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001685 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1686 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001687 return false;
John McCalla020a012010-10-20 05:44:58 +00001688 return super::VisitDeclRefExpr(E);
1689 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001690
1691 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1692 return TraverseType(T->getReplacementType());
1693 }
1694
1695 bool
1696 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1697 return TraverseTemplateArgument(T->getArgumentPack());
1698 }
1699
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001700 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1701 return TraverseType(T->getInjectedSpecializationType());
1702 }
John McCalla020a012010-10-20 05:44:58 +00001703};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001704} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001705
Douglas Gregor972fe532011-05-10 18:27:06 +00001706/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001707/// list.
1708static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001709DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001710 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001711 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001712 return Checker.Match;
1713}
1714
Douglas Gregor972fe532011-05-10 18:27:06 +00001715// Find the source range corresponding to the named type in the given
1716// nested-name-specifier, if any.
1717static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1718 QualType T,
1719 const CXXScopeSpec &SS) {
1720 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1721 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1722 if (const Type *CurType = NNS->getAsType()) {
1723 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1724 return NNSLoc.getTypeLoc().getSourceRange();
1725 } else
1726 break;
1727
1728 NNSLoc = NNSLoc.getPrefix();
1729 }
1730
1731 return SourceRange();
1732}
1733
Mike Stump11289f42009-09-09 15:08:12 +00001734/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001735/// specifier, returning the template parameter list that applies to the
1736/// name.
1737///
1738/// \param DeclStartLoc the start of the declaration that has a scope
1739/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001740///
Douglas Gregor972fe532011-05-10 18:27:06 +00001741/// \param DeclLoc The location of the declaration itself.
1742///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001743/// \param SS the scope specifier that will be matched to the given template
1744/// parameter lists. This scope specifier precedes a qualified name that is
1745/// being declared.
1746///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001747/// \param TemplateId The template-id following the scope specifier, if there
1748/// is one. Used to check for a missing 'template<>'.
1749///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001750/// \param ParamLists the template parameter lists, from the outermost to the
1751/// innermost template parameter lists.
1752///
John McCalle820e5e2010-04-13 20:37:33 +00001753/// \param IsFriend Whether to apply the slightly different rules for
1754/// matching template parameters to scope specifiers in friend
1755/// declarations.
1756///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001757/// \param IsExplicitSpecialization will be set true if the entity being
1758/// declared is an explicit specialization, false otherwise.
1759///
Mike Stump11289f42009-09-09 15:08:12 +00001760/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001761/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001762/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001763/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001764/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001765/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001766TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1767 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001768 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001769 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1770 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001771 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001772 Invalid = false;
1773
1774 // The sequence of nested types to which we will match up the template
1775 // parameter lists. We first build this list by starting with the type named
1776 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001777 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001778 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001779 if (SS.getScopeRep()) {
1780 if (CXXRecordDecl *Record
1781 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1782 T = Context.getTypeDeclType(Record);
1783 else
1784 T = QualType(SS.getScopeRep()->getAsType(), 0);
1785 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001786
1787 // If we found an explicit specialization that prevents us from needing
1788 // 'template<>' headers, this will be set to the location of that
1789 // explicit specialization.
1790 SourceLocation ExplicitSpecLoc;
1791
1792 while (!T.isNull()) {
1793 NestedTypes.push_back(T);
1794
1795 // Retrieve the parent of a record type.
1796 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1797 // If this type is an explicit specialization, we're done.
1798 if (ClassTemplateSpecializationDecl *Spec
1799 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1800 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1801 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1802 ExplicitSpecLoc = Spec->getLocation();
1803 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001804 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001805 } else if (Record->getTemplateSpecializationKind()
1806 == TSK_ExplicitSpecialization) {
1807 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001808 break;
1809 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001810
1811 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1812 T = Context.getTypeDeclType(Parent);
1813 else
1814 T = QualType();
1815 continue;
1816 }
1817
1818 if (const TemplateSpecializationType *TST
1819 = T->getAs<TemplateSpecializationType>()) {
1820 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1821 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1822 T = Context.getTypeDeclType(Parent);
1823 else
1824 T = QualType();
1825 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001826 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001827 }
1828
1829 // Look one step prior in a dependent template specialization type.
1830 if (const DependentTemplateSpecializationType *DependentTST
1831 = T->getAs<DependentTemplateSpecializationType>()) {
1832 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1833 T = QualType(NNS->getAsType(), 0);
1834 else
1835 T = QualType();
1836 continue;
1837 }
1838
1839 // Look one step prior in a dependent name type.
1840 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1841 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1842 T = QualType(NNS->getAsType(), 0);
1843 else
1844 T = QualType();
1845 continue;
1846 }
1847
1848 // Retrieve the parent of an enumeration type.
1849 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1850 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1851 // check here.
1852 EnumDecl *Enum = EnumT->getDecl();
1853
1854 // Get to the parent type.
1855 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1856 T = Context.getTypeDeclType(Parent);
1857 else
1858 T = QualType();
1859 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregor972fe532011-05-10 18:27:06 +00001862 T = QualType();
1863 }
1864 // Reverse the nested types list, since we want to traverse from the outermost
1865 // to the innermost while checking template-parameter-lists.
1866 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001867
Douglas Gregor972fe532011-05-10 18:27:06 +00001868 // C++0x [temp.expl.spec]p17:
1869 // A member or a member template may be nested within many
1870 // enclosing class templates. In an explicit specialization for
1871 // such a member, the member declaration shall be preceded by a
1872 // template<> for each enclosing class template that is
1873 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001874 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001875
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001876 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001877 if (SawNonEmptyTemplateParameterList) {
1878 Diag(DeclLoc, diag::err_specialize_member_of_template)
1879 << !Recovery << Range;
1880 Invalid = true;
1881 IsExplicitSpecialization = false;
1882 return true;
1883 }
1884
1885 return false;
1886 };
1887
1888 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1889 // Check that we can have an explicit specialization here.
1890 if (CheckExplicitSpecialization(Range, true))
1891 return true;
1892
1893 // We don't have a template header, but we should.
1894 SourceLocation ExpectedTemplateLoc;
1895 if (!ParamLists.empty())
1896 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1897 else
1898 ExpectedTemplateLoc = DeclStartLoc;
1899
1900 Diag(DeclLoc, diag::err_template_spec_needs_header)
1901 << Range
1902 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1903 return false;
1904 };
1905
Douglas Gregor972fe532011-05-10 18:27:06 +00001906 unsigned ParamIdx = 0;
1907 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1908 ++TypeIdx) {
1909 T = NestedTypes[TypeIdx];
1910
1911 // Whether we expect a 'template<>' header.
1912 bool NeedEmptyTemplateHeader = false;
1913
1914 // Whether we expect a template header with parameters.
1915 bool NeedNonemptyTemplateHeader = false;
1916
1917 // For a dependent type, the set of template parameters that we
1918 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001919 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001920
Douglas Gregor373af9b2011-05-11 23:26:17 +00001921 // C++0x [temp.expl.spec]p15:
1922 // A member or a member template may be nested within many enclosing
1923 // class templates. In an explicit specialization for such a member, the
1924 // member declaration shall be preceded by a template<> for each
1925 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001926 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1927 if (ClassTemplatePartialSpecializationDecl *Partial
1928 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1929 ExpectedTemplateParams = Partial->getTemplateParameters();
1930 NeedNonemptyTemplateHeader = true;
1931 } else if (Record->isDependentType()) {
1932 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001933 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001934 ->getTemplateParameters();
1935 NeedNonemptyTemplateHeader = true;
1936 }
1937 } else if (ClassTemplateSpecializationDecl *Spec
1938 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1939 // C++0x [temp.expl.spec]p4:
1940 // Members of an explicitly specialized class template are defined
1941 // in the same manner as members of normal classes, and not using
1942 // the template<> syntax.
1943 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1944 NeedEmptyTemplateHeader = true;
1945 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001946 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001947 } else if (Record->getTemplateSpecializationKind()) {
1948 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001949 != TSK_ExplicitSpecialization &&
1950 TypeIdx == NumTypes - 1)
1951 IsExplicitSpecialization = true;
1952
1953 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001954 }
1955 } else if (const TemplateSpecializationType *TST
1956 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001957 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001958 ExpectedTemplateParams = Template->getTemplateParameters();
1959 NeedNonemptyTemplateHeader = true;
1960 }
1961 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1962 // FIXME: We actually could/should check the template arguments here
1963 // against the corresponding template parameter list.
1964 NeedNonemptyTemplateHeader = false;
1965 }
1966
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001967 // C++ [temp.expl.spec]p16:
1968 // In an explicit specialization declaration for a member of a class
1969 // template or a member template that ap- pears in namespace scope, the
1970 // member template and some of its enclosing class templates may remain
1971 // unspecialized, except that the declaration shall not explicitly
1972 // specialize a class member template if its en- closing class templates
1973 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001974 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001975 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001976 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1977 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001978 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001979 } else
1980 SawNonEmptyTemplateParameterList = true;
1981 }
1982
Douglas Gregor972fe532011-05-10 18:27:06 +00001983 if (NeedEmptyTemplateHeader) {
1984 // If we're on the last of the types, and we need a 'template<>' header
1985 // here, then it's an explicit specialization.
1986 if (TypeIdx == NumTypes - 1)
1987 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001988
1989 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001990 if (ParamLists[ParamIdx]->size() > 0) {
1991 // The header has template parameters when it shouldn't. Complain.
1992 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1993 diag::err_template_param_list_matches_nontemplate)
1994 << T
1995 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1996 ParamLists[ParamIdx]->getRAngleLoc())
1997 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1998 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001999 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002000 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002001
Douglas Gregor972fe532011-05-10 18:27:06 +00002002 // Consume this template header.
2003 ++ParamIdx;
2004 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00002005 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002006
2007 if (!IsFriend)
2008 if (DiagnoseMissingExplicitSpecialization(
2009 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00002010 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002011
Douglas Gregor972fe532011-05-10 18:27:06 +00002012 continue;
2013 }
Richard Smith11a80dc2014-04-17 03:52:20 +00002014
Douglas Gregor972fe532011-05-10 18:27:06 +00002015 if (NeedNonemptyTemplateHeader) {
2016 // In friend declarations we can have template-ids which don't
2017 // depend on the corresponding template parameter lists. But
2018 // assume that empty parameter lists are supposed to match this
2019 // template-id.
2020 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002021 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00002022 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00002023 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00002024 else
2025 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002026 }
Douglas Gregored5731f2009-11-25 17:50:39 +00002027
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002028 if (ParamIdx < ParamLists.size()) {
2029 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00002030 if (ExpectedTemplateParams &&
2031 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2032 ExpectedTemplateParams,
2033 true, TPL_TemplateMatch))
2034 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002035
Douglas Gregor972fe532011-05-10 18:27:06 +00002036 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00002037 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00002038 TPC_ClassTemplateMember))
2039 Invalid = true;
2040
2041 ++ParamIdx;
2042 continue;
2043 }
2044
2045 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2046 << T
2047 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2048 Invalid = true;
2049 continue;
2050 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002051 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002052
Douglas Gregord8d297c2009-07-21 23:53:31 +00002053 // If there were at least as many template-ids as there were template
2054 // parameter lists, then there are no template parameter lists remaining for
2055 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002056 if (ParamIdx >= ParamLists.size()) {
2057 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002058 // We don't have a template header for the declaration itself, but we
2059 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002060 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00002061 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2062 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002063
2064 // Fabricate an empty template parameter list for the invented header.
2065 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002066 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002067 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002068 }
2069
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregord8d297c2009-07-21 23:53:31 +00002073 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002074 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002075 bool HasAnyExplicitSpecHeader = false;
2076 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002077 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002078 if (ParamLists[I]->size() == 0)
2079 HasAnyExplicitSpecHeader = true;
2080 else
2081 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002082 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002083
Douglas Gregor972fe532011-05-10 18:27:06 +00002084 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002085 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2086 : diag::err_template_spec_extra_headers)
2087 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2088 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002089
2090 // If there was a specialization somewhere, such that 'template<>' is
2091 // not required, and there were any 'template<>' headers, note where the
2092 // specialization occurred.
2093 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2094 Diag(ExplicitSpecLoc,
2095 diag::note_explicit_template_spec_does_not_need_header)
2096 << NestedTypes.back();
2097
2098 // We have a template parameter list with no corresponding scope, which
2099 // means that the resulting template declaration can't be instantiated
2100 // properly (we'll end up with dependent nodes when we shouldn't).
2101 if (!AllExplicitSpecHeaders)
2102 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002103 }
Mike Stump11289f42009-09-09 15:08:12 +00002104
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002105 // C++ [temp.expl.spec]p16:
2106 // In an explicit specialization declaration for a member of a class
2107 // template or a member template that ap- pears in namespace scope, the
2108 // member template and some of its enclosing class templates may remain
2109 // unspecialized, except that the declaration shall not explicitly
2110 // specialize a class member template if its en- closing class templates
2111 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002112 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002113 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2114 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002115 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002116
Douglas Gregord8d297c2009-07-21 23:53:31 +00002117 // Return the last template parameter list, which corresponds to the
2118 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002119 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002120}
2121
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002122void Sema::NoteAllFoundTemplates(TemplateName Name) {
2123 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2124 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002125 << (isa<FunctionTemplateDecl>(Template)
2126 ? 0
2127 : isa<ClassTemplateDecl>(Template)
2128 ? 1
2129 : isa<VarTemplateDecl>(Template)
2130 ? 2
2131 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2132 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002133 return;
2134 }
2135
2136 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2137 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2138 IEnd = OST->end();
2139 I != IEnd; ++I)
2140 Diag((*I)->getLocation(), diag::note_template_declared_here)
2141 << 0 << (*I)->getDeclName();
2142
2143 return;
2144 }
2145}
2146
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002147static QualType
2148checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2149 const SmallVectorImpl<TemplateArgument> &Converted,
2150 SourceLocation TemplateLoc,
2151 TemplateArgumentListInfo &TemplateArgs) {
2152 ASTContext &Context = SemaRef.getASTContext();
2153 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002154 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002155 // Specializations of __make_integer_seq<S, T, N> are treated like
2156 // S<T, 0, ..., N-1>.
2157
2158 // C++14 [inteseq.intseq]p1:
2159 // T shall be an integer type.
2160 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2161 SemaRef.Diag(TemplateArgs[1].getLocation(),
2162 diag::err_integer_sequence_integral_element_type);
2163 return QualType();
2164 }
2165
2166 // C++14 [inteseq.make]p1:
2167 // If N is negative the program is ill-formed.
2168 TemplateArgument NumArgsArg = Converted[2];
2169 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2170 if (NumArgs < 0) {
2171 SemaRef.Diag(TemplateArgs[2].getLocation(),
2172 diag::err_integer_sequence_negative_length);
2173 return QualType();
2174 }
2175
2176 QualType ArgTy = NumArgsArg.getIntegralType();
2177 TemplateArgumentListInfo SyntheticTemplateArgs;
2178 // The type argument gets reused as the first template argument in the
2179 // synthetic template argument list.
2180 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2181 // Expand N into 0 ... N-1.
2182 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2183 I < NumArgs; ++I) {
2184 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002185 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2186 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002187 }
2188 // The first template argument will be reused as the template decl that
2189 // our synthetic template arguments will be applied to.
2190 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2191 TemplateLoc, SyntheticTemplateArgs);
2192 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002193
2194 case BTK__type_pack_element:
2195 // Specializations of
2196 // __type_pack_element<Index, T_1, ..., T_N>
2197 // are treated like T_Index.
2198 assert(Converted.size() == 2 &&
2199 "__type_pack_element should be given an index and a parameter pack");
2200
2201 // If the Index is out of bounds, the program is ill-formed.
2202 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2203 llvm::APSInt Index = IndexArg.getAsIntegral();
2204 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2205 "type std::size_t, and hence be non-negative");
2206 if (Index >= Ts.pack_size()) {
2207 SemaRef.Diag(TemplateArgs[0].getLocation(),
2208 diag::err_type_pack_element_out_of_bounds);
2209 return QualType();
2210 }
2211
2212 // We simply return the type at index `Index`.
2213 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2214 return Nth->getAsType();
2215 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002216 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2217}
2218
Douglas Gregordc572a32009-03-30 22:58:21 +00002219QualType Sema::CheckTemplateIdType(TemplateName Name,
2220 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002221 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002222 DependentTemplateName *DTN
2223 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002224 if (DTN && DTN->isIdentifier())
2225 // When building a template-id where the template-name is dependent,
2226 // assume the template is a type template. Either our assumption is
2227 // correct, or the code is ill-formed and will be diagnosed when the
2228 // dependent name is substituted.
2229 return Context.getDependentTemplateSpecializationType(ETK_None,
2230 DTN->getQualifier(),
2231 DTN->getIdentifier(),
2232 TemplateArgs);
2233
Douglas Gregordc572a32009-03-30 22:58:21 +00002234 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002235 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2236 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002237 // We might have a substituted template template parameter pack. If so,
2238 // build a template specialization type for it.
2239 if (Name.getAsSubstTemplateTemplateParmPack())
2240 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002241
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002242 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2243 << Name;
2244 NoteAllFoundTemplates(Name);
2245 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002246 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002247
Douglas Gregorc40290e2009-03-09 23:48:35 +00002248 // Check that the template argument list is well-formed for this
2249 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002250 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002251 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002252 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002253 return QualType();
2254
Douglas Gregorc40290e2009-03-09 23:48:35 +00002255 QualType CanonType;
2256
Douglas Gregor678d76c2011-07-01 01:22:09 +00002257 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002258 if (TypeAliasTemplateDecl *AliasTemplate =
2259 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002260 // Find the canonical type for this type alias template specialization.
2261 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2262 if (Pattern->isInvalidDecl())
2263 return QualType();
2264
2265 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002266 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002267
2268 // Only substitute for the innermost template argument list.
2269 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002270 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002271 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2272 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002273 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002274
Richard Smith802c4b72012-08-23 06:16:52 +00002275 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002276 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002277 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002278 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002279
Richard Smith3f1b5d02011-05-05 21:57:07 +00002280 CanonType = SubstType(Pattern->getUnderlyingType(),
2281 TemplateArgLists, AliasTemplate->getLocation(),
2282 AliasTemplate->getDeclName());
2283 if (CanonType.isNull())
2284 return QualType();
2285 } else if (Name.isDependent() ||
2286 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002287 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002288 // This class template specialization is a dependent
2289 // type. Therefore, its canonical type is another class template
2290 // specialization type that contains all of the converted
2291 // arguments in canonical form. This ensures that, e.g., A<T> and
2292 // A<T, T> have identical types when A is declared as:
2293 //
2294 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002295 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002296 CanonType = Context.getTemplateSpecializationType(CanonName,
David Majnemer6fbeee32016-07-07 04:43:07 +00002297 Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002298
Douglas Gregora8e02e72009-07-28 23:00:59 +00002299 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002300 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002301 // In the future, we need to teach getTemplateSpecializationType to only
2302 // build the canonical type and return that to us.
2303 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002304
2305 // This might work out to be a current instantiation, in which
2306 // case the canonical type needs to be the InjectedClassNameType.
2307 //
2308 // TODO: in theory this could be a simple hashtable lookup; most
2309 // changes to CurContext don't change the set of current
2310 // instantiations.
2311 if (isa<ClassTemplateDecl>(Template)) {
2312 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2313 // If we get out to a namespace, we're done.
2314 if (Ctx->isFileContext()) break;
2315
2316 // If this isn't a record, keep looking.
2317 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2318 if (!Record) continue;
2319
2320 // Look for one of the two cases with InjectedClassNameTypes
2321 // and check whether it's the same template.
2322 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2323 !Record->getDescribedClassTemplate())
2324 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325
John McCall2408e322010-04-27 00:57:59 +00002326 // Fetch the injected class name type and check whether its
2327 // injected type is equal to the type we just built.
2328 QualType ICNT = Context.getTypeDeclType(Record);
2329 QualType Injected = cast<InjectedClassNameType>(ICNT)
2330 ->getInjectedSpecializationType();
2331
2332 if (CanonType != Injected->getCanonicalTypeInternal())
2333 continue;
2334
2335 // If so, the canonical type of this TST is the injected
2336 // class name type of the record we just found.
2337 assert(ICNT.isCanonical());
2338 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002339 break;
2340 }
2341 }
Mike Stump11289f42009-09-09 15:08:12 +00002342 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002343 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002344 // Find the class template specialization declaration that
2345 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002346 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002347 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002348 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002349 if (!Decl) {
2350 // This is the first time we have referenced this class template
2351 // specialization. Create the canonical declaration and add it to
2352 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002353 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002354 ClassTemplate->getTemplatedDecl()->getTagKind(),
2355 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002356 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002357 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002358 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002359 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002360 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002361 if (ClassTemplate->isOutOfLine())
2362 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002363 }
2364
Chandler Carruth2acfb222013-09-27 22:14:40 +00002365 // Diagnose uses of this specialization.
2366 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2367
Douglas Gregorc40290e2009-03-09 23:48:35 +00002368 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002369 assert(isa<RecordType>(CanonType) &&
2370 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002371 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2372 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2373 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002374 }
Mike Stump11289f42009-09-09 15:08:12 +00002375
Douglas Gregorc40290e2009-03-09 23:48:35 +00002376 // Build the fully-sugared type for this class template
2377 // specialization, which refers back to the class template
2378 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002379 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002380}
2381
John McCallfaf5fb42010-08-26 23:41:50 +00002382TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002383Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002384 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002385 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002386 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002387 SourceLocation RAngleLoc,
2388 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002389 if (SS.isInvalid())
2390 return true;
2391
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002392 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002393
Douglas Gregorc40290e2009-03-09 23:48:35 +00002394 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002395 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002396 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002397
Douglas Gregor5a064722011-02-28 17:23:35 +00002398 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002399 QualType T
2400 = Context.getDependentTemplateSpecializationType(ETK_None,
2401 DTN->getQualifier(),
2402 DTN->getIdentifier(),
2403 TemplateArgs);
2404 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002405 TypeLocBuilder TLB;
2406 DependentTemplateSpecializationTypeLoc SpecTL
2407 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002408 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2409 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002410 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002411 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002412 SpecTL.setLAngleLoc(LAngleLoc);
2413 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002414 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2415 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2416 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2417 }
2418
John McCall6b51f282009-11-23 01:53:49 +00002419 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002420
2421 if (Result.isNull())
2422 return true;
2423
Douglas Gregore7c20652011-03-02 00:47:37 +00002424 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002425 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002426 TemplateSpecializationTypeLoc SpecTL
2427 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002428 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002429 SpecTL.setTemplateNameLoc(TemplateLoc);
2430 SpecTL.setLAngleLoc(LAngleLoc);
2431 SpecTL.setRAngleLoc(RAngleLoc);
2432 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2433 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002434
Abramo Bagnara4244b432012-01-27 08:46:19 +00002435 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2436 // constructor or destructor name (in such a case, the scope specifier
2437 // will be attached to the enclosing Decl or Expr node).
2438 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002439 // Create an elaborated-type-specifier containing the nested-name-specifier.
2440 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2441 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002442 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002443 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2444 }
2445
2446 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002447}
John McCall06f6fe8d2009-09-04 01:14:41 +00002448
Douglas Gregore7c20652011-03-02 00:47:37 +00002449TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002450 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002451 SourceLocation TagLoc,
2452 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002453 SourceLocation TemplateKWLoc,
2454 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002455 SourceLocation TemplateLoc,
2456 SourceLocation LAngleLoc,
2457 ASTTemplateArgsPtr TemplateArgsIn,
2458 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002459 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002460
2461 // Translate the parser's template argument list in our AST format.
2462 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2463 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2464
2465 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002466 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002467 ElaboratedTypeKeyword Keyword
2468 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002469
Douglas Gregore7c20652011-03-02 00:47:37 +00002470 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2471 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2472 DTN->getQualifier(),
2473 DTN->getIdentifier(),
2474 TemplateArgs);
2475
2476 // Build type-source information.
2477 TypeLocBuilder TLB;
2478 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002479 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2480 SpecTL.setElaboratedKeywordLoc(TagLoc);
2481 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002482 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002483 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002484 SpecTL.setLAngleLoc(LAngleLoc);
2485 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002486 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2487 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2488 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2489 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002490
2491 if (TypeAliasTemplateDecl *TAT =
2492 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2493 // C++0x [dcl.type.elab]p2:
2494 // If the identifier resolves to a typedef-name or the simple-template-id
2495 // resolves to an alias template specialization, the
2496 // elaborated-type-specifier is ill-formed.
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00002497 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
2498 << TAT << NTK_TypeAliasTemplate << TagKind;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002499 Diag(TAT->getLocation(), diag::note_declared_at);
2500 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002501
2502 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2503 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002504 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002505
2506 // Check the tag kind
2507 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002508 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002509
John McCalld8fe9af2009-09-08 17:47:29 +00002510 IdentifierInfo *Id = D->getIdentifier();
2511 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002512
Richard Trieucaa33d32011-06-10 03:11:26 +00002513 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002514 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002515 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002516 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002517 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002518 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002519 }
2520 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002521
Douglas Gregore7c20652011-03-02 00:47:37 +00002522 // Provide source-location information for the template specialization.
2523 TypeLocBuilder TLB;
2524 TemplateSpecializationTypeLoc SpecTL
2525 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002526 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002527 SpecTL.setTemplateNameLoc(TemplateLoc);
2528 SpecTL.setLAngleLoc(LAngleLoc);
2529 SpecTL.setRAngleLoc(RAngleLoc);
2530 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2531 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002532
Douglas Gregore7c20652011-03-02 00:47:37 +00002533 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002534 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002535 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2536 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002537 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002538 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2539 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002540}
2541
Larisse Voufo39a1e502013-08-06 01:03:05 +00002542static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002543 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2544 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002545
2546static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2547 NamedDecl *PrevDecl,
2548 SourceLocation Loc,
2549 bool IsPartialSpecialization);
2550
2551static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002552
Richard Smith300e0c32013-09-24 04:49:23 +00002553static bool isTemplateArgumentTemplateParameter(
2554 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2555 switch (Arg.getKind()) {
2556 case TemplateArgument::Null:
2557 case TemplateArgument::NullPtr:
2558 case TemplateArgument::Integral:
2559 case TemplateArgument::Declaration:
2560 case TemplateArgument::Pack:
2561 case TemplateArgument::TemplateExpansion:
2562 return false;
2563
2564 case TemplateArgument::Type: {
2565 QualType Type = Arg.getAsType();
2566 const TemplateTypeParmType *TPT =
2567 Arg.getAsType()->getAs<TemplateTypeParmType>();
2568 return TPT && !Type.hasQualifiers() &&
2569 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2570 }
2571
2572 case TemplateArgument::Expression: {
2573 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2574 if (!DRE || !DRE->getDecl())
2575 return false;
2576 const NonTypeTemplateParmDecl *NTTP =
2577 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2578 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2579 }
2580
2581 case TemplateArgument::Template:
2582 const TemplateTemplateParmDecl *TTP =
2583 dyn_cast_or_null<TemplateTemplateParmDecl>(
2584 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2585 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2586 }
2587 llvm_unreachable("unexpected kind of template argument");
2588}
2589
2590static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2591 ArrayRef<TemplateArgument> Args) {
2592 if (Params->size() != Args.size())
2593 return false;
2594
2595 unsigned Depth = Params->getDepth();
2596
2597 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2598 TemplateArgument Arg = Args[I];
2599
2600 // If the parameter is a pack expansion, the argument must be a pack
2601 // whose only element is a pack expansion.
2602 if (Params->getParam(I)->isParameterPack()) {
2603 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2604 !Arg.pack_begin()->isPackExpansion())
2605 return false;
2606 Arg = Arg.pack_begin()->getPackExpansionPattern();
2607 }
2608
2609 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2610 return false;
2611 }
2612
2613 return true;
2614}
2615
Richard Smith4b55a9c2014-04-17 03:29:33 +00002616/// Convert the parser's template argument list representation into our form.
2617static TemplateArgumentListInfo
2618makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2619 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2620 TemplateId.RAngleLoc);
2621 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2622 TemplateId.NumArgs);
2623 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2624 return TemplateArgs;
2625}
2626
Richard Smith0e617ec2016-12-27 07:56:27 +00002627template<typename PartialSpecDecl>
2628static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
2629 if (Partial->getDeclContext()->isDependentContext())
2630 return;
2631
2632 // FIXME: Get the TDK from deduction in order to provide better diagnostics
2633 // for non-substitution-failure issues?
2634 TemplateDeductionInfo Info(Partial->getLocation());
2635 if (S.isMoreSpecializedThanPrimary(Partial, Info))
2636 return;
2637
2638 auto *Template = Partial->getSpecializedTemplate();
2639 S.Diag(Partial->getLocation(),
2640 diag::err_partial_spec_not_more_specialized_than_primary)
2641 << /*variable template*/isa<VarTemplateDecl>(Template);
2642
2643 if (Info.hasSFINAEDiagnostic()) {
2644 PartialDiagnosticAt Diag = {SourceLocation(),
2645 PartialDiagnostic::NullDiagnostic()};
2646 Info.takeSFINAEDiagnostic(Diag);
2647 SmallString<128> SFINAEArgString;
2648 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
2649 S.Diag(Diag.first,
2650 diag::note_partial_spec_not_more_specialized_than_primary)
2651 << SFINAEArgString;
2652 }
2653
2654 S.Diag(Template->getLocation(), diag::note_template_decl_here);
2655}
2656
Larisse Voufo39a1e502013-08-06 01:03:05 +00002657DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002658 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002659 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002660 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002661 // D must be variable template id.
2662 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2663 "Variable template specialization is declared with a template it.");
2664
2665 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002666 TemplateArgumentListInfo TemplateArgs =
2667 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002668 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2669 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2670 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002671
Richard Smithbeef3452014-01-16 23:39:20 +00002672 TemplateName Name = TemplateId->Template.get();
2673
2674 // The template-id must name a variable template.
2675 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002676 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2677 if (!VarTemplate) {
2678 NamedDecl *FnTemplate;
2679 if (auto *OTS = Name.getAsOverloadedTemplate())
2680 FnTemplate = *OTS->begin();
2681 else
2682 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2683 if (FnTemplate)
2684 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2685 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002686 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2687 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002688 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002689
2690 // Check for unexpanded parameter packs in any of the template arguments.
2691 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2692 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2693 UPPC_PartialSpecialization))
2694 return true;
2695
2696 // Check that the template argument list is well-formed for this
2697 // template.
2698 SmallVector<TemplateArgument, 4> Converted;
2699 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2700 false, Converted))
2701 return true;
2702
Larisse Voufo39a1e502013-08-06 01:03:05 +00002703 // Find the variable template (partial) specialization declaration that
2704 // corresponds to these arguments.
2705 if (IsPartialSpecialization) {
2706 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002707 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2708 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002709 return true;
2710
2711 bool InstantiationDependent;
2712 if (!Name.isDependent() &&
2713 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002714 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002715 InstantiationDependent)) {
2716 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2717 << VarTemplate->getDeclName();
2718 IsPartialSpecialization = false;
2719 }
Richard Smith300e0c32013-09-24 04:49:23 +00002720
2721 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2722 Converted)) {
2723 // C++ [temp.class.spec]p9b3:
2724 //
2725 // -- The argument list of the specialization shall not be identical
2726 // to the implicit argument list of the primary template.
2727 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2728 << /*variable template*/ 1
2729 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2730 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2731 // FIXME: Recover from this by treating the declaration as a redeclaration
2732 // of the primary template.
2733 return true;
2734 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002735 }
2736
Craig Topperc3ec1492014-05-26 06:22:03 +00002737 void *InsertPos = nullptr;
2738 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002739
2740 if (IsPartialSpecialization)
2741 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002742 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002743 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002744 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002745
Craig Topperc3ec1492014-05-26 06:22:03 +00002746 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002747
2748 // Check whether we can declare a variable template specialization in
2749 // the current scope.
2750 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2751 TemplateNameLoc,
2752 IsPartialSpecialization))
2753 return true;
2754
2755 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2756 // Since the only prior variable template specialization with these
2757 // arguments was referenced but not declared, reuse that
2758 // declaration node as our own, updating its source location and
2759 // the list of outer template parameters to reflect our new declaration.
2760 Specialization = PrevDecl;
2761 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002762 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002763 } else if (IsPartialSpecialization) {
2764 // Create a new class template partial specialization declaration node.
2765 VarTemplatePartialSpecializationDecl *PrevPartial =
2766 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002767 VarTemplatePartialSpecializationDecl *Partial =
2768 VarTemplatePartialSpecializationDecl::Create(
2769 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2770 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002771 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002772
2773 if (!PrevPartial)
2774 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2775 Specialization = Partial;
2776
2777 // If we are providing an explicit specialization of a member variable
2778 // template specialization, make a note of that.
2779 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002780 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002781
Richard Smith0e617ec2016-12-27 07:56:27 +00002782 // C++1z [temp.class.spec]p8: (DR1495)
2783 // - The specialization shall be more specialized than the primary
2784 // template (14.5.5.2).
2785 checkMoreSpecializedThanPrimary(*this, Partial);
2786
Larisse Voufo39a1e502013-08-06 01:03:05 +00002787 // Check that all of the template parameters of the variable template
2788 // partial specialization are deducible from the template
2789 // arguments. If not, this variable template partial specialization
2790 // will never be used.
2791 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2792 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2793 TemplateParams->getDepth(), DeducibleParams);
2794
2795 if (!DeducibleParams.all()) {
2796 unsigned NumNonDeducible =
2797 DeducibleParams.size() - DeducibleParams.count();
2798 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002799 << /*variable template*/ 1 << (NumNonDeducible > 1)
2800 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002801 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2802 if (!DeducibleParams[I]) {
2803 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2804 if (Param->getDeclName())
2805 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2806 << Param->getDeclName();
2807 else
2808 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002809 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002810 }
2811 }
2812 }
2813 } else {
2814 // Create a new class template specialization declaration node for
2815 // this explicit specialization or friend declaration.
2816 Specialization = VarTemplateSpecializationDecl::Create(
2817 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002818 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002819 Specialization->setTemplateArgsInfo(TemplateArgs);
2820
2821 if (!PrevDecl)
2822 VarTemplate->AddSpecialization(Specialization, InsertPos);
2823 }
2824
2825 // C++ [temp.expl.spec]p6:
2826 // If a template, a member template or the member of a class template is
2827 // explicitly specialized then that specialization shall be declared
2828 // before the first use of that specialization that would cause an implicit
2829 // instantiation to take place, in every translation unit in which such a
2830 // use occurs; no diagnostic is required.
2831 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2832 bool Okay = false;
2833 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2834 // Is there any previous explicit specialization declaration?
2835 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2836 Okay = true;
2837 break;
2838 }
2839 }
2840
2841 if (!Okay) {
2842 SourceRange Range(TemplateNameLoc, RAngleLoc);
2843 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2844 << Name << Range;
2845
2846 Diag(PrevDecl->getPointOfInstantiation(),
2847 diag::note_instantiation_required_here)
2848 << (PrevDecl->getTemplateSpecializationKind() !=
2849 TSK_ImplicitInstantiation);
2850 return true;
2851 }
2852 }
2853
2854 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2855 Specialization->setLexicalDeclContext(CurContext);
2856
2857 // Add the specialization into its lexical context, so that it can
2858 // be seen when iterating through the list of declarations in that
2859 // context. However, specializations are not found by name lookup.
2860 CurContext->addDecl(Specialization);
2861
2862 // Note that this is an explicit specialization.
2863 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2864
2865 if (PrevDecl) {
2866 // Check that this isn't a redefinition of this specialization,
2867 // merging with previous declarations.
2868 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2869 ForRedeclaration);
2870 PrevSpec.addDecl(PrevDecl);
2871 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002872 } else if (Specialization->isStaticDataMember() &&
2873 Specialization->isOutOfLine()) {
2874 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002875 }
2876
2877 // Link instantiations of static data members back to the template from
2878 // which they were instantiated.
2879 if (Specialization->isStaticDataMember())
2880 Specialization->setInstantiationOfStaticDataMember(
2881 VarTemplate->getTemplatedDecl(),
2882 Specialization->getSpecializationKind());
2883
2884 return Specialization;
2885}
2886
2887namespace {
2888/// \brief A partial specialization whose template arguments have matched
2889/// a given template-id.
2890struct PartialSpecMatchResult {
2891 VarTemplatePartialSpecializationDecl *Partial;
2892 TemplateArgumentList *Args;
2893};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002894} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002895
2896DeclResult
2897Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2898 SourceLocation TemplateNameLoc,
2899 const TemplateArgumentListInfo &TemplateArgs) {
2900 assert(Template && "A variable template id without template?");
2901
2902 // Check that the template argument list is well-formed for this template.
2903 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002904 if (CheckTemplateArgumentList(
2905 Template, TemplateNameLoc,
2906 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002907 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002908 return true;
2909
2910 // Find the variable template specialization declaration that
2911 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002912 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002913 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002914 Converted, InsertPos)) {
2915 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002916 // If we already have a variable template specialization, return it.
2917 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002918 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002919
2920 // This is the first time we have referenced this variable template
2921 // specialization. Create the canonical declaration and add it to
2922 // the set of specializations, based on the closest partial specialization
2923 // that it represents. That is,
2924 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2925 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002926 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002927 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2928 bool AmbiguousPartialSpec = false;
2929 typedef PartialSpecMatchResult MatchResult;
2930 SmallVector<MatchResult, 4> Matched;
2931 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002932 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2933 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002934
2935 // 1. Attempt to find the closest partial specialization that this
2936 // specializes, if any.
2937 // If any of the template arguments is dependent, then this is probably
2938 // a placeholder for an incomplete declarative context; which must be
2939 // complete by instantiation time. Thus, do not search through the partial
2940 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002941 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2942 // Perhaps better after unification of DeduceTemplateArguments() and
2943 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002944 bool InstantiationDependent = false;
2945 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2946 TemplateArgs, InstantiationDependent)) {
2947
2948 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2949 Template->getPartialSpecializations(PartialSpecs);
2950
2951 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2952 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2953 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2954
2955 if (TemplateDeductionResult Result =
2956 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2957 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002958 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002959 FailedCandidates.addCandidate().set(
2960 DeclAccessPair::make(Template, AS_public), Partial,
2961 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002962 (void)Result;
2963 } else {
2964 Matched.push_back(PartialSpecMatchResult());
2965 Matched.back().Partial = Partial;
2966 Matched.back().Args = Info.take();
2967 }
2968 }
2969
Larisse Voufo39a1e502013-08-06 01:03:05 +00002970 if (Matched.size() >= 1) {
2971 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2972 if (Matched.size() == 1) {
2973 // -- If exactly one matching specialization is found, the
2974 // instantiation is generated from that specialization.
2975 // We don't need to do anything for this.
2976 } else {
2977 // -- If more than one matching specialization is found, the
2978 // partial order rules (14.5.4.2) are used to determine
2979 // whether one of the specializations is more specialized
2980 // than the others. If none of the specializations is more
2981 // specialized than all of the other matching
2982 // specializations, then the use of the variable template is
2983 // ambiguous and the program is ill-formed.
2984 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2985 PEnd = Matched.end();
2986 P != PEnd; ++P) {
2987 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2988 PointOfInstantiation) ==
2989 P->Partial)
2990 Best = P;
2991 }
2992
2993 // Determine if the best partial specialization is more specialized than
2994 // the others.
2995 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2996 PEnd = Matched.end();
2997 P != PEnd; ++P) {
2998 if (P != Best && getMoreSpecializedPartialSpecialization(
2999 P->Partial, Best->Partial,
3000 PointOfInstantiation) != Best->Partial) {
3001 AmbiguousPartialSpec = true;
3002 break;
3003 }
3004 }
3005 }
3006
3007 // Instantiate using the best variable template partial specialization.
3008 InstantiationPattern = Best->Partial;
3009 InstantiationArgs = Best->Args;
3010 } else {
3011 // -- If no match is found, the instantiation is generated
3012 // from the primary template.
3013 // InstantiationPattern = Template->getTemplatedDecl();
3014 }
3015 }
3016
Larisse Voufo39a1e502013-08-06 01:03:05 +00003017 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00003018 // Note that we do not instantiate a definition until we see an odr-use
3019 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00003020 // FIXME: LateAttrs et al.?
3021 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3022 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3023 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3024 if (!Decl)
3025 return true;
3026
3027 if (AmbiguousPartialSpec) {
3028 // Partial ordering did not produce a clear winner. Complain.
3029 Decl->setInvalidDecl();
3030 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3031 << Decl;
3032
3033 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00003034 for (MatchResult P : Matched)
3035 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3036 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3037 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003038 return true;
3039 }
3040
3041 if (VarTemplatePartialSpecializationDecl *D =
3042 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3043 Decl->setInstantiationOf(D, InstantiationArgs);
3044
Richard Smith6739a102016-05-05 00:56:12 +00003045 checkSpecializationVisibility(TemplateNameLoc, Decl);
3046
Larisse Voufo39a1e502013-08-06 01:03:05 +00003047 assert(Decl && "No variable template specialization?");
3048 return Decl;
3049}
3050
3051ExprResult
3052Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3053 const DeclarationNameInfo &NameInfo,
3054 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3055 const TemplateArgumentListInfo *TemplateArgs) {
3056
3057 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3058 *TemplateArgs);
3059 if (Decl.isInvalid())
3060 return ExprError();
3061
3062 VarDecl *Var = cast<VarDecl>(Decl.get());
3063 if (!Var->getTemplateSpecializationKind())
3064 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3065 NameInfo.getLoc());
3066
3067 // Build an ordinary singleton decl ref.
3068 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003069 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003070}
3071
John McCalldadc5752010-08-24 06:29:42 +00003072ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003073 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003074 LookupResult &R,
3075 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003076 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003077 // FIXME: Can we do any checking at this point? I guess we could check the
3078 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003079 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003080 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003081 // foo<int> could identify a single function unambiguously
3082 // This approach does NOT work, since f<int>(1);
3083 // gets resolved prior to resorting to overload resolution
3084 // i.e., template<class T> void f(double);
3085 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003086
3087 // These should be filtered out by our callers.
3088 assert(!R.empty() && "empty lookup results when building templateid");
3089 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3090
Larisse Voufo39a1e502013-08-06 01:03:05 +00003091 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003092 bool InstantiationDependent;
3093 if (R.getAsSingle<VarTemplateDecl>() &&
3094 !TemplateSpecializationType::anyDependentTemplateArguments(
3095 *TemplateArgs, InstantiationDependent)) {
3096 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3097 R.getAsSingle<VarTemplateDecl>(),
3098 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003099 }
3100
John McCall58cc69d2010-01-27 01:50:18 +00003101 // We don't want lookup warnings at this point.
3102 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003103
John McCalle66edc12009-11-24 19:00:30 +00003104 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003105 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003106 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003107 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003108 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003109 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003110 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003111
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003112 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003113}
3114
John McCalle66edc12009-11-24 19:00:30 +00003115// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003116ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003117Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003118 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003119 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003120 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003121
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003122 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003123 DeclContext *DC;
3124 if (!(DC = computeDeclContext(SS, false)) ||
3125 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003126 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003127 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003128
Douglas Gregor786123d2010-05-21 23:18:07 +00003129 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003130 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003131 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003132 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003133
John McCalle66edc12009-11-24 19:00:30 +00003134 if (R.isAmbiguous())
3135 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136
John McCalle66edc12009-11-24 19:00:30 +00003137 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003138 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3139 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003140 return ExprError();
3141 }
3142
3143 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003144 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003145 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003146 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003147 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3148 return ExprError();
3149 }
3150
Abramo Bagnara7945c982012-01-27 09:46:47 +00003151 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003152}
3153
Douglas Gregorb67535d2009-03-31 00:43:58 +00003154/// \brief Form a dependent template name.
3155///
3156/// This action forms a dependent template name given the template
3157/// name and its (presumably dependent) scope specifier. For
3158/// example, given "MetaFun::template apply", the scope specifier \p
3159/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3160/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003162 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003163 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003164 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003165 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003166 bool EnteringContext,
3167 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003168 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3169 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003170 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003171 diag::warn_cxx98_compat_template_outside_of_template :
3172 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173 << FixItHint::CreateRemoval(TemplateKWLoc);
3174
Craig Topperc3ec1492014-05-26 06:22:03 +00003175 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003176 if (SS.isSet())
3177 LookupCtx = computeDeclContext(SS, EnteringContext);
3178 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003179 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003180 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003181 // C++0x [temp.names]p5:
3182 // If a name prefixed by the keyword template is not the name of
3183 // a template, the program is ill-formed. [Note: the keyword
3184 // template may not be applied to non-template members of class
3185 // templates. -end note ] [ Note: as is the case with the
3186 // typename prefix, the template prefix is allowed in cases
3187 // where it is not strictly necessary; i.e., when the
3188 // nested-name-specifier or the expression on the left of the ->
3189 // or . is not dependent on a template-parameter, or the use
3190 // does not appear in the scope of a template. -end note]
3191 //
3192 // Note: C++03 was more strict here, because it banned the use of
3193 // the "template" keyword prior to a template-name that was not a
3194 // dependent name. C++ DR468 relaxed this requirement (the
3195 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003196 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003197 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003198 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003199 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003200 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003201 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3202 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003203 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3204 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003205 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003206 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003207 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003208 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003209 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003210 << Name.getSourceRange()
3211 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003212 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003213 } else {
3214 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003215 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003216 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003217 }
3218
Aaron Ballman4a979672014-01-03 13:56:08 +00003219 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220
Douglas Gregor3cf81312009-11-03 23:16:33 +00003221 switch (Name.getKind()) {
3222 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003223 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003224 Name.Identifier));
3225 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003226
Douglas Gregor71395fa2009-11-04 00:56:37 +00003227 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003228 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003229 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003230 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003231
3232 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003233 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003234
Douglas Gregor3cf81312009-11-03 23:16:33 +00003235 default:
3236 break;
3237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003239 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003240 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003241 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003242 << Name.getSourceRange()
3243 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003244 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003245}
3246
Mike Stump11289f42009-09-09 15:08:12 +00003247bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003248 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003249 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003250 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003251 QualType ArgType;
3252 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003253
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003254 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003255 switch(Arg.getKind()) {
3256 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003257 // C++ [temp.arg.type]p1:
3258 // A template-argument for a template-parameter which is a
3259 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003260 ArgType = Arg.getAsType();
3261 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003262 break;
3263 case TemplateArgument::Template: {
3264 // We have a template type parameter but the template argument
3265 // is a template without any arguments.
3266 SourceRange SR = AL.getSourceRange();
3267 TemplateName Name = Arg.getAsTemplate();
3268 Diag(SR.getBegin(), diag::err_template_missing_args)
3269 << Name << SR;
3270 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3271 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003272
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003273 return true;
3274 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003275 case TemplateArgument::Expression: {
3276 // We have a template type parameter but the template argument is an
3277 // expression; see if maybe it is missing the "typename" keyword.
3278 CXXScopeSpec SS;
3279 DeclarationNameInfo NameInfo;
3280
3281 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3282 SS.Adopt(ArgExpr->getQualifierLoc());
3283 NameInfo = ArgExpr->getNameInfo();
3284 } else if (DependentScopeDeclRefExpr *ArgExpr =
3285 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3286 SS.Adopt(ArgExpr->getQualifierLoc());
3287 NameInfo = ArgExpr->getNameInfo();
3288 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3289 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003290 if (ArgExpr->isImplicitAccess()) {
3291 SS.Adopt(ArgExpr->getQualifierLoc());
3292 NameInfo = ArgExpr->getMemberNameInfo();
3293 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003294 }
3295
Reid Kleckner377c1592014-06-10 23:29:48 +00003296 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003297 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3298 LookupParsedName(Result, CurScope, &SS);
3299
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003300 if (Result.getAsSingle<TypeDecl>() ||
3301 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003302 LookupResult::NotFoundInCurrentInstantiation) {
3303 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003304 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003305 Diag(Loc, getLangOpts().MSVCCompat
3306 ? diag::ext_ms_template_type_arg_missing_typename
3307 : diag::err_template_arg_must_be_type_suggest)
3308 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003309 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003310
3311 // Recover by synthesizing a type using the location information that we
3312 // already have.
3313 ArgType =
3314 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3315 TypeLocBuilder TLB;
3316 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3317 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3318 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3319 TL.setNameLoc(NameInfo.getLoc());
3320 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3321
3322 // Overwrite our input TemplateArgumentLoc so that we can recover
3323 // properly.
3324 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3325 TemplateArgumentLocInfo(TSI));
3326
3327 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003328 }
3329 }
3330 // fallthrough
3331 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003332 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003333 // We have a template type parameter but the template argument
3334 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003335 SourceRange SR = AL.getSourceRange();
3336 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003337 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003338
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003339 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003340 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003341 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003342
Reid Kleckner377c1592014-06-10 23:29:48 +00003343 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003344 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003345
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003346 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003347 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003348
3349 // Objective-C ARC:
3350 // If an explicitly-specified template argument type is a lifetime type
3351 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003352 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003353 ArgType->isObjCLifetimeType() &&
3354 !ArgType.getObjCLifetime()) {
3355 Qualifiers Qs;
3356 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3357 ArgType = Context.getQualifiedType(ArgType, Qs);
3358 }
3359
3360 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003361 return false;
3362}
3363
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003364/// \brief Substitute template arguments into the default template argument for
3365/// the given template type parameter.
3366///
3367/// \param SemaRef the semantic analysis object for which we are performing
3368/// the substitution.
3369///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003370/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003371/// for.
3372///
3373/// \param TemplateLoc the location of the template name that started the
3374/// template-id we are checking.
3375///
3376/// \param RAngleLoc the location of the right angle bracket ('>') that
3377/// terminates the template-id.
3378///
3379/// \param Param the template template parameter whose default we are
3380/// substituting into.
3381///
3382/// \param Converted the list of template arguments provided for template
3383/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003384/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003385static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003386SubstDefaultTemplateArgument(Sema &SemaRef,
3387 TemplateDecl *Template,
3388 SourceLocation TemplateLoc,
3389 SourceLocation RAngleLoc,
3390 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003391 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003392 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003393
3394 // If the argument type is dependent, instantiate it now based
3395 // on the previously-computed template arguments.
3396 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003397 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003398 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003399 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003400 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003401 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402
David Majnemer8b622692016-07-03 21:17:51 +00003403 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003404
3405 // Only substitute for the innermost template argument list.
3406 MultiLevelTemplateArgumentList TemplateArgLists;
3407 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3408 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3409 TemplateArgLists.addOuterTemplateArguments(None);
3410
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003411 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003412 ArgType =
3413 SemaRef.SubstType(ArgType, TemplateArgLists,
3414 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003415 }
3416
3417 return ArgType;
3418}
3419
3420/// \brief Substitute template arguments into the default template argument for
3421/// the given non-type template parameter.
3422///
3423/// \param SemaRef the semantic analysis object for which we are performing
3424/// the substitution.
3425///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003427/// for.
3428///
3429/// \param TemplateLoc the location of the template name that started the
3430/// template-id we are checking.
3431///
3432/// \param RAngleLoc the location of the right angle bracket ('>') that
3433/// terminates the template-id.
3434///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003435/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003436/// substituting into.
3437///
3438/// \param Converted the list of template arguments provided for template
3439/// parameters that precede \p Param in the template parameter list.
3440///
3441/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003442static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003443SubstDefaultTemplateArgument(Sema &SemaRef,
3444 TemplateDecl *Template,
3445 SourceLocation TemplateLoc,
3446 SourceLocation RAngleLoc,
3447 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003448 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003449 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003450 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003451 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003452 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003453 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003454
David Majnemer8b622692016-07-03 21:17:51 +00003455 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003456
3457 // Only substitute for the innermost template argument list.
3458 MultiLevelTemplateArgumentList TemplateArgLists;
3459 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3460 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3461 TemplateArgLists.addOuterTemplateArguments(None);
3462
Faisal Vali48401eb2015-11-19 19:20:17 +00003463 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3464 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003465 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003466}
3467
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003468/// \brief Substitute template arguments into the default template argument for
3469/// the given template template parameter.
3470///
3471/// \param SemaRef the semantic analysis object for which we are performing
3472/// the substitution.
3473///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003474/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003475/// for.
3476///
3477/// \param TemplateLoc the location of the template name that started the
3478/// template-id we are checking.
3479///
3480/// \param RAngleLoc the location of the right angle bracket ('>') that
3481/// terminates the template-id.
3482///
3483/// \param Param the template template parameter whose default we are
3484/// substituting into.
3485///
3486/// \param Converted the list of template arguments provided for template
3487/// parameters that precede \p Param in the template parameter list.
3488///
Douglas Gregordf846d12011-03-02 18:46:51 +00003489/// \param QualifierLoc Will be set to the nested-name-specifier (with
3490/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003491///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003492/// \returns the substituted template argument, or NULL if an error occurred.
3493static TemplateName
3494SubstDefaultTemplateArgument(Sema &SemaRef,
3495 TemplateDecl *Template,
3496 SourceLocation TemplateLoc,
3497 SourceLocation RAngleLoc,
3498 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003499 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003500 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003501 Sema::InstantiatingTemplate Inst(
3502 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3503 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003504 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003505 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
David Majnemer8b622692016-07-03 21:17:51 +00003507 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003508
3509 // Only substitute for the innermost template argument list.
3510 MultiLevelTemplateArgumentList TemplateArgLists;
3511 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3512 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3513 TemplateArgLists.addOuterTemplateArguments(None);
3514
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003515 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003516 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003517 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003518 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003519 QualifierLoc =
3520 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003521 if (!QualifierLoc)
3522 return TemplateName();
3523 }
David Majnemer89189202013-08-28 23:48:32 +00003524
3525 return SemaRef.SubstTemplateName(
3526 QualifierLoc,
3527 Param->getDefaultArgument().getArgument().getAsTemplate(),
3528 Param->getDefaultArgument().getTemplateNameLoc(),
3529 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003530}
3531
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003532/// \brief If the given template parameter has a default template
3533/// argument, substitute into that default template argument and
3534/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003536Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3537 SourceLocation TemplateLoc,
3538 SourceLocation RAngleLoc,
3539 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003540 SmallVectorImpl<TemplateArgument>
3541 &Converted,
3542 bool &HasDefaultArg) {
3543 HasDefaultArg = false;
3544
3545 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003546 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003547 return TemplateArgumentLoc();
3548
Richard Smithc87b9382013-07-04 01:01:24 +00003549 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003550 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003551 TemplateLoc,
3552 RAngleLoc,
3553 TypeParm,
3554 Converted);
3555 if (DI)
3556 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3557
3558 return TemplateArgumentLoc();
3559 }
3560
3561 if (NonTypeTemplateParmDecl *NonTypeParm
3562 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003563 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003564 return TemplateArgumentLoc();
3565
Richard Smithc87b9382013-07-04 01:01:24 +00003566 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003567 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003568 TemplateLoc,
3569 RAngleLoc,
3570 NonTypeParm,
3571 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003572 if (Arg.isInvalid())
3573 return TemplateArgumentLoc();
3574
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003575 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003576 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3577 }
3578
3579 TemplateTemplateParmDecl *TempTempParm
3580 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003581 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003582 return TemplateArgumentLoc();
3583
Richard Smithc87b9382013-07-04 01:01:24 +00003584 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003585 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003586 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003587 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003588 RAngleLoc,
3589 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003590 Converted,
3591 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003592 if (TName.isNull())
3593 return TemplateArgumentLoc();
3594
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003596 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003597 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3598}
3599
Douglas Gregorda0fb532009-11-11 19:31:23 +00003600/// \brief Check that the given template argument corresponds to the given
3601/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003602///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003604/// checked.
3605///
Richard Trieu15b66532015-01-24 02:48:32 +00003606/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003607///
3608/// \param Template The template in which the template argument resides.
3609///
3610/// \param TemplateLoc The location of the template name for the template
3611/// whose argument list we're matching.
3612///
3613/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3614/// the template argument list.
3615///
3616/// \param ArgumentPackIndex The index into the argument pack where this
3617/// argument will be placed. Only valid if the parameter is a parameter pack.
3618///
3619/// \param Converted The checked, converted argument will be added to the
3620/// end of this small vector.
3621///
3622/// \param CTAK Describes how we arrived at this particular template argument:
3623/// explicitly written, deduced, etc.
3624///
3625/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003626bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003627 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003628 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003629 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003630 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003631 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003632 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003633 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003634 // Check template type parameters.
3635 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003636 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637
Douglas Gregoreebed722009-11-11 19:41:09 +00003638 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003640 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003641 // with the template arguments we've seen thus far. But if the
3642 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003643 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003644 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3645 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Peter Collingbourne01687632010-12-10 17:08:53 +00003647 if (NTTPType->isDependentType() &&
3648 !isa<TemplateTemplateParmDecl>(Template) &&
3649 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003650 // Do substitution on the type of the non-type template parameter.
3651 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003652 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003653 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003654 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003655 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
3657 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003658 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003659 NTTPType = SubstType(NTTPType,
3660 MultiLevelTemplateArgumentList(TemplateArgs),
3661 NTTP->getLocation(),
3662 NTTP->getDeclName());
3663 // If that worked, check the non-type template parameter type
3664 // for validity.
3665 if (!NTTPType.isNull())
3666 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3667 NTTP->getLocation());
3668 if (NTTPType.isNull())
3669 return true;
3670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregorda0fb532009-11-11 19:31:23 +00003672 switch (Arg.getArgument().getKind()) {
3673 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003674 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675
Douglas Gregorda0fb532009-11-11 19:31:23 +00003676 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003677 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003678 ExprResult Res =
3679 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3680 Result, CTAK);
3681 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003682 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683
Richard Trieu15b66532015-01-24 02:48:32 +00003684 // If the resulting expression is new, then use it in place of the
3685 // old expression in the template argument.
3686 if (Res.get() != Arg.getArgument().getAsExpr()) {
3687 TemplateArgument TA(Res.get());
3688 Arg = TemplateArgumentLoc(TA, Res.get());
3689 }
3690
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003691 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003692 break;
3693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694
Douglas Gregorda0fb532009-11-11 19:31:23 +00003695 case TemplateArgument::Declaration:
3696 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003697 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003698 // We've already checked this template argument, so just copy
3699 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003700 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003701 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702
Douglas Gregorda0fb532009-11-11 19:31:23 +00003703 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003704 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003705 // We were given a template template argument. It may not be ill-formed;
3706 // see below.
3707 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003708 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3709 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003710 // We have a template argument such as \c T::template X, which we
3711 // parsed as a template template argument. However, since we now
3712 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003713 // template name into an expression.
3714
3715 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3716 Arg.getTemplateNameLoc());
3717
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003718 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003719 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003720 // FIXME: the template-template arg was a DependentTemplateName,
3721 // so it was provided with a template keyword. However, its source
3722 // location is not stored in the template argument structure.
3723 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003724 ExprResult E = DependentScopeDeclRefExpr::Create(
3725 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3726 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003728 // If we parsed the template argument as a pack expansion, create a
3729 // pack expansion expression.
3730 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003731 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003732 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003733 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
Douglas Gregorda0fb532009-11-11 19:31:23 +00003736 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003737 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003738 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003739 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003740
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003741 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003742 break;
3743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744
Douglas Gregorda0fb532009-11-11 19:31:23 +00003745 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003746 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003747 // therefore cannot be a non-type template argument.
3748 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3749 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Douglas Gregorda0fb532009-11-11 19:31:23 +00003751 Diag(Param->getLocation(), diag::note_template_param_here);
3752 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753
Douglas Gregorda0fb532009-11-11 19:31:23 +00003754 case TemplateArgument::Type: {
3755 // We have a non-type template parameter but the template
3756 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757
Douglas Gregorda0fb532009-11-11 19:31:23 +00003758 // C++ [temp.arg]p2:
3759 // In a template-argument, an ambiguity between a type-id and
3760 // an expression is resolved to a type-id, regardless of the
3761 // form of the corresponding template-parameter.
3762 //
3763 // We warn specifically about this case, since it can be rather
3764 // confusing for users.
3765 QualType T = Arg.getArgument().getAsType();
3766 SourceRange SR = Arg.getSourceRange();
3767 if (T->isFunctionType())
3768 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3769 else
3770 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3771 Diag(Param->getLocation(), diag::note_template_param_here);
3772 return true;
3773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Douglas Gregorda0fb532009-11-11 19:31:23 +00003775 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003776 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778
Douglas Gregorda0fb532009-11-11 19:31:23 +00003779 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780 }
3781
3782
Douglas Gregorda0fb532009-11-11 19:31:23 +00003783 // Check template template parameters.
3784 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785
Douglas Gregorda0fb532009-11-11 19:31:23 +00003786 // Substitute into the template parameter list of the template
3787 // template parameter, since previously-supplied template arguments
3788 // may appear within the template template parameter.
3789 {
3790 // Set up a template instantiation context.
3791 LocalInstantiationScope Scope(*this);
3792 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003793 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003794 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003795 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003796 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797
David Majnemer8b622692016-07-03 21:17:51 +00003798 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003799 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003801 MultiLevelTemplateArgumentList(TemplateArgs)));
3802 if (!TempParm)
3803 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805
Douglas Gregorda0fb532009-11-11 19:31:23 +00003806 switch (Arg.getArgument().getKind()) {
3807 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003808 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Douglas Gregorda0fb532009-11-11 19:31:23 +00003810 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003811 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003812 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003813 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003815 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003816 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817
Douglas Gregorda0fb532009-11-11 19:31:23 +00003818 case TemplateArgument::Expression:
3819 case TemplateArgument::Type:
3820 // We have a template template parameter but the template
3821 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003822 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003823 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003824 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825
Douglas Gregorda0fb532009-11-11 19:31:23 +00003826 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003827 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003828 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003829 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003830 case TemplateArgument::NullPtr:
3831 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832
Douglas Gregorda0fb532009-11-11 19:31:23 +00003833 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003834 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836
Douglas Gregorda0fb532009-11-11 19:31:23 +00003837 return false;
3838}
3839
Douglas Gregor8e072612012-02-03 07:34:46 +00003840/// \brief Diagnose an arity mismatch in the
3841static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3842 SourceLocation TemplateLoc,
3843 TemplateArgumentListInfo &TemplateArgs) {
3844 TemplateParameterList *Params = Template->getTemplateParameters();
3845 unsigned NumParams = Params->size();
3846 unsigned NumArgs = TemplateArgs.size();
3847
3848 SourceRange Range;
3849 if (NumArgs > NumParams)
3850 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3851 TemplateArgs.getRAngleLoc());
3852 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3853 << (NumArgs > NumParams)
3854 << (isa<ClassTemplateDecl>(Template)? 0 :
3855 isa<FunctionTemplateDecl>(Template)? 1 :
3856 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3857 << Template << Range;
3858 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3859 << Params->getSourceRange();
3860 return true;
3861}
3862
Richard Smith1fde8ec2012-09-07 02:06:42 +00003863/// \brief Check whether the template parameter is a pack expansion, and if so,
3864/// determine the number of parameters produced by that expansion. For instance:
3865///
3866/// \code
3867/// template<typename ...Ts> struct A {
3868/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3869/// };
3870/// \endcode
3871///
3872/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3873/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003874static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003875 if (NonTypeTemplateParmDecl *NTTP
3876 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3877 if (NTTP->isExpandedParameterPack())
3878 return NTTP->getNumExpansionTypes();
3879 }
3880
3881 if (TemplateTemplateParmDecl *TTP
3882 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3883 if (TTP->isExpandedParameterPack())
3884 return TTP->getNumExpansionTemplateParameters();
3885 }
3886
David Blaikie7a30dc52013-02-21 01:47:18 +00003887 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003888}
3889
Richard Smith35c1df52015-06-17 20:16:32 +00003890/// Diagnose a missing template argument.
3891template<typename TemplateParmDecl>
3892static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3893 TemplateDecl *TD,
3894 const TemplateParmDecl *D,
3895 TemplateArgumentListInfo &Args) {
3896 // Dig out the most recent declaration of the template parameter; there may be
3897 // declarations of the template that are more recent than TD.
3898 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3899 ->getTemplateParameters()
3900 ->getParam(D->getIndex()));
3901
3902 // If there's a default argument that's not visible, diagnose that we're
3903 // missing a module import.
3904 llvm::SmallVector<Module*, 8> Modules;
3905 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3906 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3907 D->getDefaultArgumentLoc(), Modules,
3908 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003909 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003910 return true;
3911 }
3912
3913 // FIXME: If there's a more recent default argument that *is* visible,
3914 // diagnose that it was declared too late.
3915
3916 return diagnoseArityMismatch(S, TD, Loc, Args);
3917}
3918
Douglas Gregord32e0282009-02-09 23:23:08 +00003919/// \brief Check that the given template argument list is well-formed
3920/// for specializing the given template.
3921bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3922 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003923 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003924 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003925 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003926 // Make a copy of the template arguments for processing. Only make the
3927 // changes at the end when successful in matching the arguments to the
3928 // template.
3929 TemplateArgumentListInfo NewArgs = TemplateArgs;
3930
Douglas Gregord32e0282009-02-09 23:23:08 +00003931 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003932
Richard Trieu15b66532015-01-24 02:48:32 +00003933 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003934
Mike Stump11289f42009-09-09 15:08:12 +00003935 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003936 // [...] The type and form of each template-argument specified in
3937 // a template-id shall match the type and form specified for the
3938 // corresponding parameter declared by the template in its
3939 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003940 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003941 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003942 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003943 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003944 for (TemplateParameterList::iterator Param = Params->begin(),
3945 ParamEnd = Params->end();
3946 Param != ParamEnd; /* increment in loop */) {
3947 // If we have an expanded parameter pack, make sure we don't have too
3948 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003949 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003950 if (*Expansions == ArgumentPack.size()) {
3951 // We're done with this parameter pack. Pack up its arguments and add
3952 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003953 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003954 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003955 ArgumentPack.clear();
3956
Richard Smith1fde8ec2012-09-07 02:06:42 +00003957 // This argument is assigned to the next parameter.
3958 ++Param;
3959 continue;
3960 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3961 // Not enough arguments for this parameter pack.
3962 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3963 << false
3964 << (isa<ClassTemplateDecl>(Template)? 0 :
3965 isa<FunctionTemplateDecl>(Template)? 1 :
3966 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3967 << Template;
3968 Diag(Template->getLocation(), diag::note_template_decl_here)
3969 << Params->getSourceRange();
3970 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003971 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Richard Smith1fde8ec2012-09-07 02:06:42 +00003974 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003975 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003976 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003978 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003979 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980
Richard Smith96d71c32014-11-12 23:38:38 +00003981 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003982 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003983 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3984 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003985 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003986 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003987 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003988 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003989 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003990 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003991 Diag((*Param)->getLocation(), diag::note_template_param_here);
3992 return true;
3993 }
3994
Richard Smith1fde8ec2012-09-07 02:06:42 +00003995 // We're now done with this argument.
3996 ++ArgIdx;
3997
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003998 if ((*Param)->isTemplateParameterPack()) {
3999 // The template parameter was a template parameter pack, so take the
4000 // deduced argument and place it on the argument pack. Note that we
4001 // stay on the same template parameter so that we can deduce more
4002 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004003 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004004 } else {
4005 // Move to the next template parameter.
4006 ++Param;
4007 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004008
Richard Smith96d71c32014-11-12 23:38:38 +00004009 // If we just saw a pack expansion into a non-pack, then directly convert
4010 // the remaining arguments, because we don't know what parameters they'll
4011 // match up with.
4012 if (PackExpansionIntoNonPack) {
4013 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00004014 // If we were part way through filling in an expanded parameter pack,
4015 // fall back to just producing individual arguments.
4016 Converted.insert(Converted.end(),
4017 ArgumentPack.begin(), ArgumentPack.end());
4018 ArgumentPack.clear();
4019 }
4020
4021 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00004022 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00004023 ++ArgIdx;
4024 }
4025
Richard Smith1fde8ec2012-09-07 02:06:42 +00004026 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00004027 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00004028
Douglas Gregor84d49a22009-11-11 21:54:23 +00004029 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031
Douglas Gregor2f157c92011-06-03 02:59:40 +00004032 // If we're checking a partial template argument list, we're done.
4033 if (PartialTemplateArgs) {
4034 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004035 Converted.push_back(
4036 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4037
Richard Smith1fde8ec2012-09-07 02:06:42 +00004038 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004039 }
4040
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004041 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004042 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004043 if ((*Param)->isTemplateParameterPack()) {
4044 assert(!getExpandedPackSize(*Param) &&
4045 "Should have dealt with this already");
4046
4047 // A non-expanded parameter pack before the end of the parameter list
4048 // only occurs for an ill-formed template parameter list, unless we've
4049 // got a partial argument list for a function template, so just bail out.
4050 if (Param + 1 != ParamEnd)
4051 return true;
4052
Benjamin Kramercce63472015-08-05 09:40:22 +00004053 Converted.push_back(
4054 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004055 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004056
4057 ++Param;
4058 continue;
4059 }
4060
Douglas Gregor8e072612012-02-03 07:34:46 +00004061 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004062 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063
Douglas Gregor84d49a22009-11-11 21:54:23 +00004064 // Retrieve the default template argument from the template
4065 // parameter. For each kind of template parameter, we substitute the
4066 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004068 // the default argument.
4069 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004070 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004071 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4072 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004073
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004075 Template,
4076 TemplateLoc,
4077 RAngleLoc,
4078 TTP,
4079 Converted);
4080 if (!ArgType)
4081 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082
Douglas Gregor84d49a22009-11-11 21:54:23 +00004083 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4084 ArgType);
4085 } else if (NonTypeTemplateParmDecl *NTTP
4086 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004087 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004088 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4089 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004090
John McCalldadc5752010-08-24 06:29:42 +00004091 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092 TemplateLoc,
4093 RAngleLoc,
4094 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004095 Converted);
4096 if (E.isInvalid())
4097 return true;
4098
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004099 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004100 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4101 } else {
4102 TemplateTemplateParmDecl *TempParm
4103 = cast<TemplateTemplateParmDecl>(*Param);
4104
Richard Smith95d83952015-06-10 20:36:34 +00004105 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004106 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4107 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004108
Douglas Gregordf846d12011-03-02 18:46:51 +00004109 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004110 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111 TemplateLoc,
4112 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004113 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004114 Converted,
4115 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004116 if (Name.isNull())
4117 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004118
Douglas Gregor9d802122011-03-02 17:09:35 +00004119 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4120 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
Douglas Gregor84d49a22009-11-11 21:54:23 +00004123 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004124 // the default template argument. We're not actually instantiating a
4125 // template here, we just create this object to put a note into the
4126 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004127 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4128 SourceRange(TemplateLoc, RAngleLoc));
4129 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004130 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131
Douglas Gregor84d49a22009-11-11 21:54:23 +00004132 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004133 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004134 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004135 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136
Richard Trieu15b66532015-01-24 02:48:32 +00004137 // Core issue 150 (assumed resolution): if this is a template template
4138 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004139 // template definition.
4140 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004141 NewArgs.addArgument(Arg);
4142
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004143 // Move to the next template parameter and argument.
4144 ++Param;
4145 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147
Richard Smith07f79912014-06-06 16:00:50 +00004148 // If we're performing a partial argument substitution, allow any trailing
4149 // pack expansions; they might be empty. This can happen even if
4150 // PartialTemplateArgs is false (the list of arguments is complete but
4151 // still dependent).
4152 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4153 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004154 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4155 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004156 }
4157
Douglas Gregor8e072612012-02-03 07:34:46 +00004158 // If we have any leftover arguments, then there were too many arguments.
4159 // Complain and fail.
4160 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004161 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4162
4163 // No problems found with the new argument list, propagate changes back
4164 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004165 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166
Richard Smith1fde8ec2012-09-07 02:06:42 +00004167 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004168}
4169
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004170namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171 class UnnamedLocalNoLinkageFinder
4172 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004173 {
4174 Sema &S;
4175 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004177 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004179 public:
4180 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4181
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182 bool Visit(QualType T) {
4183 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004185
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004186#define TYPE(Class, Parent) \
4187 bool Visit##Class##Type(const Class##Type *);
4188#define ABSTRACT_TYPE(Class, Parent) \
4189 bool Visit##Class##Type(const Class##Type *) { return false; }
4190#define NON_CANONICAL_TYPE(Class, Parent) \
4191 bool Visit##Class##Type(const Class##Type *) { return false; }
4192#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004194 bool VisitTagDecl(const TagDecl *Tag);
4195 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4196 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004197} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004198
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004199bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004200 return false;
4201}
4202
4203bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4204 return Visit(T->getElementType());
4205}
4206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004208 return Visit(T->getPointeeType());
4209}
4210
4211bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004213 return Visit(T->getPointeeType());
4214}
4215
4216bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004218 return Visit(T->getPointeeType());
4219}
4220
4221bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004223 return Visit(T->getPointeeType());
4224}
4225
4226bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004228 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4229}
4230
4231bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004233 return Visit(T->getElementType());
4234}
4235
4236bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004238 return Visit(T->getElementType());
4239}
4240
4241bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004243 return Visit(T->getElementType());
4244}
4245
4246bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004248 return Visit(T->getElementType());
4249}
4250
4251bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004253 return Visit(T->getElementType());
4254}
4255
4256bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4257 return Visit(T->getElementType());
4258}
4259
4260bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4261 return Visit(T->getElementType());
4262}
4263
4264bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4265 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004266 for (const auto &A : T->param_types()) {
4267 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004268 return true;
4269 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Alp Toker314cc812014-01-25 16:55:45 +00004271 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004272}
4273
4274bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4275 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004276 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004277}
4278
4279bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4280 const UnresolvedUsingType*) {
4281 return false;
4282}
4283
4284bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4285 return false;
4286}
4287
4288bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4289 return Visit(T->getUnderlyingType());
4290}
4291
4292bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4293 return false;
4294}
4295
Alexis Hunte852b102011-05-24 22:41:36 +00004296bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4297 const UnaryTransformType*) {
4298 return false;
4299}
4300
Richard Smith30482bc2011-02-20 03:19:35 +00004301bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4302 return Visit(T->getDeducedType());
4303}
4304
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004305bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4306 return VisitTagDecl(T->getDecl());
4307}
4308
4309bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4310 return VisitTagDecl(T->getDecl());
4311}
4312
4313bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4314 const TemplateTypeParmType*) {
4315 return false;
4316}
4317
Douglas Gregorada4b792011-01-14 02:55:32 +00004318bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4319 const SubstTemplateTypeParmPackType *) {
4320 return false;
4321}
4322
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004323bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4324 const TemplateSpecializationType*) {
4325 return false;
4326}
4327
4328bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4329 const InjectedClassNameType* T) {
4330 return VisitTagDecl(T->getDecl());
4331}
4332
4333bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4334 const DependentNameType* T) {
4335 return VisitNestedNameSpecifier(T->getQualifier());
4336}
4337
4338bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4339 const DependentTemplateSpecializationType* T) {
4340 return VisitNestedNameSpecifier(T->getQualifier());
4341}
4342
Douglas Gregord2fa7662010-12-20 02:24:11 +00004343bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4344 const PackExpansionType* T) {
4345 return Visit(T->getPattern());
4346}
4347
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004348bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4349 return false;
4350}
4351
4352bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4353 const ObjCInterfaceType *) {
4354 return false;
4355}
4356
4357bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4358 const ObjCObjectPointerType *) {
4359 return false;
4360}
4361
Eli Friedman0dfb8892011-10-06 23:00:33 +00004362bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4363 return Visit(T->getValueType());
4364}
4365
Xiuli Pan9c14e282016-01-09 12:53:17 +00004366bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4367 return false;
4368}
4369
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004370bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4371 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004372 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004373 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004374 diag::warn_cxx98_compat_template_arg_local_type :
4375 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004376 << S.Context.getTypeDeclType(Tag) << SR;
4377 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378 }
4379
John McCall5ea95772013-03-09 00:54:27 +00004380 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004381 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004382 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004383 diag::warn_cxx98_compat_template_arg_unnamed_type :
4384 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004385 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4386 return true;
4387 }
4388
4389 return false;
4390}
4391
4392bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4393 NestedNameSpecifier *NNS) {
4394 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4395 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004397 switch (NNS->getKind()) {
4398 case NestedNameSpecifier::Identifier:
4399 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004400 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004401 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004402 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004403 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004405 case NestedNameSpecifier::TypeSpec:
4406 case NestedNameSpecifier::TypeSpecWithTemplate:
4407 return Visit(QualType(NNS->getAsType(), 0));
4408 }
David Blaikie8a40f702012-01-17 06:56:22 +00004409 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004410}
4411
Douglas Gregord32e0282009-02-09 23:23:08 +00004412/// \brief Check a template argument against its corresponding
4413/// template type parameter.
4414///
4415/// This routine implements the semantics of C++ [temp.arg.type]. It
4416/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004417bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004418 TypeSourceInfo *ArgInfo) {
4419 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004420 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004421 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004422
4423 if (Arg->isVariablyModifiedType()) {
4424 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004425 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004426 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004427 }
4428
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004429 // C++03 [temp.arg.type]p2:
4430 // A local type, a type with no linkage, an unnamed type or a type
4431 // compounded from any of these types shall not be used as a
4432 // template-argument for a template type-parameter.
4433 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004434 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004435 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004436 bool NeedsCheck;
4437 if (LangOpts.CPlusPlus11)
4438 NeedsCheck =
4439 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4440 SR.getBegin()) ||
4441 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4442 SR.getBegin());
4443 else
4444 NeedsCheck = Arg->hasUnnamedOrLocalType();
4445
4446 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004447 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4448 (void)Finder.Visit(Context.getCanonicalType(Arg));
4449 }
4450
Douglas Gregord32e0282009-02-09 23:23:08 +00004451 return false;
4452}
4453
Douglas Gregor20fdef32012-04-10 17:08:25 +00004454enum NullPointerValueKind {
4455 NPV_NotNullPointer,
4456 NPV_NullPointer,
4457 NPV_Error
4458};
4459
4460/// \brief Determine whether the given template argument is a null pointer
4461/// value of the appropriate type.
4462static NullPointerValueKind
4463isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4464 QualType ParamType, Expr *Arg) {
4465 if (Arg->isValueDependent() || Arg->isTypeDependent())
4466 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004467
Richard Smithdb0ac552015-12-18 22:40:25 +00004468 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004469 llvm_unreachable(
4470 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004471
David Majnemer5c734ad2014-08-14 00:49:23 +00004472 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004473 return NPV_NotNullPointer;
4474
4475 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004476 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4477 if (ArgRV.isInvalid())
4478 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004479 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004480
Douglas Gregor20fdef32012-04-10 17:08:25 +00004481 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004482 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004483 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004484 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004485 EvalResult.HasSideEffects) {
4486 SourceLocation DiagLoc = Arg->getExprLoc();
4487
4488 // If our only note is the usual "invalid subexpression" note, just point
4489 // the caret at its location rather than producing an essentially
4490 // redundant note.
4491 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4492 diag::note_invalid_subexpr_in_const_expr) {
4493 DiagLoc = Notes[0].first;
4494 Notes.clear();
4495 }
4496
4497 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4498 << Arg->getType() << Arg->getSourceRange();
4499 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4500 S.Diag(Notes[I].first, Notes[I].second);
4501
4502 S.Diag(Param->getLocation(), diag::note_template_param_here);
4503 return NPV_Error;
4504 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004505
4506 // C++11 [temp.arg.nontype]p1:
4507 // - an address constant expression of type std::nullptr_t
4508 if (Arg->getType()->isNullPtrType())
4509 return NPV_NullPointer;
4510
4511 // - a constant expression that evaluates to a null pointer value (4.10); or
4512 // - a constant expression that evaluates to a null member pointer value
4513 // (4.11); or
4514 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4515 (EvalResult.Val.isMemberPointer() &&
4516 !EvalResult.Val.getMemberPointerDecl())) {
4517 // If our expression has an appropriate type, we've succeeded.
4518 bool ObjCLifetimeConversion;
4519 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4520 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4521 ObjCLifetimeConversion))
4522 return NPV_NullPointer;
4523
4524 // The types didn't match, but we know we got a null pointer; complain,
4525 // then recover as if the types were correct.
4526 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4527 << Arg->getType() << ParamType << Arg->getSourceRange();
4528 S.Diag(Param->getLocation(), diag::note_template_param_here);
4529 return NPV_NullPointer;
4530 }
4531
4532 // If we don't have a null pointer value, but we do have a NULL pointer
4533 // constant, suggest a cast to the appropriate type.
4534 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4535 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4536 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004537 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4538 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4539 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004540 S.Diag(Param->getLocation(), diag::note_template_param_here);
4541 return NPV_NullPointer;
4542 }
4543
4544 // FIXME: If we ever want to support general, address-constant expressions
4545 // as non-type template arguments, we should return the ExprResult here to
4546 // be interpreted by the caller.
4547 return NPV_NotNullPointer;
4548}
4549
David Majnemer61c39a12013-08-23 05:39:39 +00004550/// \brief Checks whether the given template argument is compatible with its
4551/// template parameter.
4552static bool CheckTemplateArgumentIsCompatibleWithParameter(
4553 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4554 Expr *Arg, QualType ArgType) {
4555 bool ObjCLifetimeConversion;
4556 if (ParamType->isPointerType() &&
4557 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4558 S.IsQualificationConversion(ArgType, ParamType, false,
4559 ObjCLifetimeConversion)) {
4560 // For pointer-to-object types, qualification conversions are
4561 // permitted.
4562 } else {
4563 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4564 if (!ParamRef->getPointeeType()->isFunctionType()) {
4565 // C++ [temp.arg.nontype]p5b3:
4566 // For a non-type template-parameter of type reference to
4567 // object, no conversions apply. The type referred to by the
4568 // reference may be more cv-qualified than the (otherwise
4569 // identical) type of the template- argument. The
4570 // template-parameter is bound directly to the
4571 // template-argument, which shall be an lvalue.
4572
4573 // FIXME: Other qualifiers?
4574 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4575 unsigned ArgQuals = ArgType.getCVRQualifiers();
4576
4577 if ((ParamQuals | ArgQuals) != ParamQuals) {
4578 S.Diag(Arg->getLocStart(),
4579 diag::err_template_arg_ref_bind_ignores_quals)
4580 << ParamType << Arg->getType() << Arg->getSourceRange();
4581 S.Diag(Param->getLocation(), diag::note_template_param_here);
4582 return true;
4583 }
4584 }
4585 }
4586
4587 // At this point, the template argument refers to an object or
4588 // function with external linkage. We now need to check whether the
4589 // argument and parameter types are compatible.
4590 if (!S.Context.hasSameUnqualifiedType(ArgType,
4591 ParamType.getNonReferenceType())) {
4592 // We can't perform this conversion or binding.
4593 if (ParamType->isReferenceType())
4594 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4595 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4596 else
4597 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4598 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4599 S.Diag(Param->getLocation(), diag::note_template_param_here);
4600 return true;
4601 }
4602 }
4603
4604 return false;
4605}
4606
Douglas Gregorccb07762009-02-11 19:52:55 +00004607/// \brief Checks whether the given template argument is the address
4608/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004610CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4611 NonTypeTemplateParmDecl *Param,
4612 QualType ParamType,
4613 Expr *ArgIn,
4614 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004615 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004616 Expr *Arg = ArgIn;
4617 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004618
Douglas Gregorb242683d2010-04-01 18:32:35 +00004619 bool AddressTaken = false;
4620 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004621 if (S.getLangOpts().MicrosoftExt) {
4622 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4623 // dereference and address-of operators.
4624 Arg = Arg->IgnoreParenCasts();
4625
4626 bool ExtWarnMSTemplateArg = false;
4627 UnaryOperatorKind FirstOpKind;
4628 SourceLocation FirstOpLoc;
4629 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4630 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4631 if (UnOpKind == UO_Deref)
4632 ExtWarnMSTemplateArg = true;
4633 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4634 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4635 if (!AddrOpLoc.isValid()) {
4636 FirstOpKind = UnOpKind;
4637 FirstOpLoc = UnOp->getOperatorLoc();
4638 }
4639 } else
4640 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004641 }
David Majnemer61c39a12013-08-23 05:39:39 +00004642 if (FirstOpLoc.isValid()) {
4643 if (ExtWarnMSTemplateArg)
4644 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4645 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004646
David Majnemer61c39a12013-08-23 05:39:39 +00004647 if (FirstOpKind == UO_AddrOf)
4648 AddressTaken = true;
4649 else if (Arg->getType()->isPointerType()) {
4650 // We cannot let pointers get dereferenced here, that is obviously not a
4651 // constant expression.
4652 assert(FirstOpKind == UO_Deref);
4653 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4654 << Arg->getSourceRange();
4655 }
4656 }
4657 } else {
4658 // See through any implicit casts we added to fix the type.
4659 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004660
David Majnemer61c39a12013-08-23 05:39:39 +00004661 // C++ [temp.arg.nontype]p1:
4662 //
4663 // A template-argument for a non-type, non-template
4664 // template-parameter shall be one of: [...]
4665 //
4666 // -- the address of an object or function with external
4667 // linkage, including function templates and function
4668 // template-ids but excluding non-static class members,
4669 // expressed as & id-expression where the & is optional if
4670 // the name refers to a function or array, or if the
4671 // corresponding template-parameter is a reference; or
4672
4673 // In C++98/03 mode, give an extension warning on any extra parentheses.
4674 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4675 bool ExtraParens = false;
4676 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4677 if (!Invalid && !ExtraParens) {
4678 S.Diag(Arg->getLocStart(),
4679 S.getLangOpts().CPlusPlus11
4680 ? diag::warn_cxx98_compat_template_arg_extra_parens
4681 : diag::ext_template_arg_extra_parens)
4682 << Arg->getSourceRange();
4683 ExtraParens = true;
4684 }
4685
4686 Arg = Parens->getSubExpr();
4687 }
4688
4689 while (SubstNonTypeTemplateParmExpr *subst =
4690 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4691 Arg = subst->getReplacement()->IgnoreImpCasts();
4692
4693 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4694 if (UnOp->getOpcode() == UO_AddrOf) {
4695 Arg = UnOp->getSubExpr();
4696 AddressTaken = true;
4697 AddrOpLoc = UnOp->getOperatorLoc();
4698 }
4699 }
4700
4701 while (SubstNonTypeTemplateParmExpr *subst =
4702 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4703 Arg = subst->getReplacement()->IgnoreImpCasts();
4704 }
John McCall7c454bb2011-07-15 05:09:51 +00004705
David Majnemer07910d62014-06-26 07:48:46 +00004706 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4707 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4708
4709 // If our parameter has pointer type, check for a null template value.
4710 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4711 NullPointerValueKind NPV;
4712 // dllimport'd entities aren't constant but are available inside of template
4713 // arguments.
4714 if (Entity && Entity->hasAttr<DLLImportAttr>())
4715 NPV = NPV_NotNullPointer;
4716 else
4717 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4718 switch (NPV) {
4719 case NPV_NullPointer:
4720 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004721 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4722 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004723 return false;
4724
4725 case NPV_Error:
4726 return true;
4727
4728 case NPV_NotNullPointer:
4729 break;
4730 }
4731 }
4732
Chandler Carruth724a8a12010-01-31 10:01:20 +00004733 // Stop checking the precise nature of the argument if it is value dependent,
4734 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004735 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004736 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004737 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004738 }
David Majnemer61c39a12013-08-23 05:39:39 +00004739
4740 if (isa<CXXUuidofExpr>(Arg)) {
4741 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4742 ArgIn, Arg, ArgType))
4743 return true;
4744
4745 Converted = TemplateArgument(ArgIn);
4746 return false;
4747 }
4748
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004749 if (!DRE) {
4750 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4751 << Arg->getSourceRange();
4752 S.Diag(Param->getLocation(), diag::note_template_param_here);
4753 return true;
4754 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004755
Douglas Gregorccb07762009-02-11 19:52:55 +00004756 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004757 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004758 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004759 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004760 S.Diag(Param->getLocation(), diag::note_template_param_here);
4761 return true;
4762 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004763
4764 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004765 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004766 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004767 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004768 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004769 S.Diag(Param->getLocation(), diag::note_template_param_here);
4770 return true;
4771 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004772 }
Mike Stump11289f42009-09-09 15:08:12 +00004773
Richard Smith9380e0e2012-04-04 21:11:30 +00004774 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4775 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004776
Richard Smith9380e0e2012-04-04 21:11:30 +00004777 // A non-type template argument must refer to an object or function.
4778 if (!Func && !Var) {
4779 // We found something, but we don't know specifically what it is.
4780 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4781 << Arg->getSourceRange();
4782 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4783 return true;
4784 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004785
Richard Smith9380e0e2012-04-04 21:11:30 +00004786 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004787 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004788 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004789 diag::warn_cxx98_compat_template_arg_object_internal :
4790 diag::ext_template_arg_object_internal)
4791 << !Func << Entity << Arg->getSourceRange();
4792 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4793 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004794 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004795 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4796 << !Func << Entity << Arg->getSourceRange();
4797 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4798 << !Func;
4799 return true;
4800 }
4801
4802 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004803 // If the template parameter has pointer type, the function decays.
4804 if (ParamType->isPointerType() && !AddressTaken)
4805 ArgType = S.Context.getPointerType(Func->getType());
4806 else if (AddressTaken && ParamType->isReferenceType()) {
4807 // If we originally had an address-of operator, but the
4808 // parameter has reference type, complain and (if things look
4809 // like they will work) drop the address-of operator.
4810 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4811 ParamType.getNonReferenceType())) {
4812 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4813 << ParamType;
4814 S.Diag(Param->getLocation(), diag::note_template_param_here);
4815 return true;
4816 }
4817
4818 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4819 << ParamType
4820 << FixItHint::CreateRemoval(AddrOpLoc);
4821 S.Diag(Param->getLocation(), diag::note_template_param_here);
4822
4823 ArgType = Func->getType();
4824 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004825 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004826 // A value of reference type is not an object.
4827 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004828 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004829 diag::err_template_arg_reference_var)
4830 << Var->getType() << Arg->getSourceRange();
4831 S.Diag(Param->getLocation(), diag::note_template_param_here);
4832 return true;
4833 }
4834
Richard Smith9380e0e2012-04-04 21:11:30 +00004835 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004836 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004837 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4838 << Arg->getSourceRange();
4839 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4840 return true;
4841 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004842
4843 // If the template parameter has pointer type, we must have taken
4844 // the address of this object.
4845 if (ParamType->isReferenceType()) {
4846 if (AddressTaken) {
4847 // If we originally had an address-of operator, but the
4848 // parameter has reference type, complain and (if things look
4849 // like they will work) drop the address-of operator.
4850 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4851 ParamType.getNonReferenceType())) {
4852 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4853 << ParamType;
4854 S.Diag(Param->getLocation(), diag::note_template_param_here);
4855 return true;
4856 }
4857
4858 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4859 << ParamType
4860 << FixItHint::CreateRemoval(AddrOpLoc);
4861 S.Diag(Param->getLocation(), diag::note_template_param_here);
4862
4863 ArgType = Var->getType();
4864 }
4865 } else if (!AddressTaken && ParamType->isPointerType()) {
4866 if (Var->getType()->isArrayType()) {
4867 // Array-to-pointer decay.
4868 ArgType = S.Context.getArrayDecayedType(Var->getType());
4869 } else {
4870 // If the template parameter has pointer type but the address of
4871 // this object was not taken, complain and (possibly) recover by
4872 // taking the address of the entity.
4873 ArgType = S.Context.getPointerType(Var->getType());
4874 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4875 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4876 << ParamType;
4877 S.Diag(Param->getLocation(), diag::note_template_param_here);
4878 return true;
4879 }
4880
4881 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4882 << ParamType
4883 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4884
4885 S.Diag(Param->getLocation(), diag::note_template_param_here);
4886 }
4887 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004888 }
Mike Stump11289f42009-09-09 15:08:12 +00004889
David Majnemer61c39a12013-08-23 05:39:39 +00004890 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4891 Arg, ArgType))
4892 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004893
4894 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004895 Converted =
4896 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004897 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004898 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004899}
4900
4901/// \brief Checks whether the given template argument is a pointer to
4902/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004903static bool CheckTemplateArgumentPointerToMember(Sema &S,
4904 NonTypeTemplateParmDecl *Param,
4905 QualType ParamType,
4906 Expr *&ResultArg,
4907 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004908 bool Invalid = false;
4909
Douglas Gregor20fdef32012-04-10 17:08:25 +00004910 // Check for a null pointer value.
4911 Expr *Arg = ResultArg;
4912 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4913 case NPV_Error:
4914 return true;
4915 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004916 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004917 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4918 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004919 return false;
4920 case NPV_NotNullPointer:
4921 break;
4922 }
4923
4924 bool ObjCLifetimeConversion;
4925 if (S.IsQualificationConversion(Arg->getType(),
4926 ParamType.getNonReferenceType(),
4927 false, ObjCLifetimeConversion)) {
4928 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004929 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004930 ResultArg = Arg;
4931 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4932 ParamType.getNonReferenceType())) {
4933 // We can't perform this conversion.
4934 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4935 << Arg->getType() << ParamType << Arg->getSourceRange();
4936 S.Diag(Param->getLocation(), diag::note_template_param_here);
4937 return true;
4938 }
4939
Douglas Gregorccb07762009-02-11 19:52:55 +00004940 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004941 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004942 Arg = Cast->getSubExpr();
4943
4944 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004945 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004946 // A template-argument for a non-type, non-template
4947 // template-parameter shall be one of: [...]
4948 //
4949 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004950 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004951
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004952 // In C++98/03 mode, give an extension warning on any extra parentheses.
4953 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4954 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004955 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004956 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004957 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004958 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004959 diag::warn_cxx98_compat_template_arg_extra_parens :
4960 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004961 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004962 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004963 }
4964
4965 Arg = Parens->getSubExpr();
4966 }
4967
John McCall7c454bb2011-07-15 05:09:51 +00004968 while (SubstNonTypeTemplateParmExpr *subst =
4969 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4970 Arg = subst->getReplacement()->IgnoreImpCasts();
4971
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004972 // A pointer-to-member constant written &Class::member.
4973 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004974 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004975 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4976 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004977 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004980 // A constant of pointer-to-member type.
4981 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4982 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4983 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004984 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004985 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004986 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004987 } else {
4988 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004989 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004990 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004991 return Invalid;
4992 }
4993 }
4994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004995
Craig Topperc3ec1492014-05-26 06:22:03 +00004996 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Douglas Gregorccb07762009-02-11 19:52:55 +00004999 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00005000 return S.Diag(Arg->getLocStart(),
5001 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00005002 << Arg->getSourceRange();
5003
David Majnemer3ac84e62013-10-22 21:56:38 +00005004 if (isa<FieldDecl>(DRE->getDecl()) ||
5005 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5006 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00005007 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00005008 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00005009 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5010 "Only non-static member pointers can make it here");
5011
5012 // Okay: this is the address of a non-static member, and therefore
5013 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00005014 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00005015 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00005016 } else {
5017 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00005018 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00005019 }
Douglas Gregorccb07762009-02-11 19:52:55 +00005020 return Invalid;
5021 }
5022
5023 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00005024 S.Diag(Arg->getLocStart(),
5025 diag::err_template_arg_not_pointer_to_member_form)
5026 << Arg->getSourceRange();
5027 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00005028 return true;
5029}
5030
Douglas Gregord32e0282009-02-09 23:23:08 +00005031/// \brief Check a template argument against its corresponding
5032/// non-type template parameter.
5033///
Douglas Gregor463421d2009-03-03 04:44:36 +00005034/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005035/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005036/// returns the converted template argument. \p ParamType is the
5037/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005038ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005039 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005040 TemplateArgument &Converted,
5041 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005042 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005043
Richard Smith5f274382016-09-28 23:55:27 +00005044 // If the parameter type somehow involves auto, deduce the type now.
5045 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
Richard Smith87d263e2016-12-25 08:05:23 +00005046 // When checking a deduced template argument, deduce from its type even if
5047 // the type is dependent, in order to check the types of non-type template
5048 // arguments line up properly in partial ordering.
5049 Optional<unsigned> Depth;
5050 if (CTAK != CTAK_Specified)
5051 Depth = Param->getDepth() + 1;
Richard Smith5f274382016-09-28 23:55:27 +00005052 if (DeduceAutoType(
5053 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
Richard Smith87d263e2016-12-25 08:05:23 +00005054 Arg, ParamType, Depth) == DAR_Failed) {
Richard Smith5f274382016-09-28 23:55:27 +00005055 Diag(Arg->getExprLoc(),
5056 diag::err_non_type_template_parm_type_deduction_failure)
5057 << Param->getDeclName() << Param->getType() << Arg->getType()
5058 << Arg->getSourceRange();
5059 Diag(Param->getLocation(), diag::note_template_param_here);
5060 return ExprError();
5061 }
5062 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5063 // an error. The error message normally references the parameter
5064 // declaration, but here we'll pass the argument location because that's
5065 // where the parameter type is deduced.
5066 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5067 if (ParamType.isNull()) {
5068 Diag(Param->getLocation(), diag::note_template_param_here);
5069 return ExprError();
5070 }
5071 }
5072
Richard Smithd663fdd2014-12-17 20:42:37 +00005073 // We should have already dropped all cv-qualifiers by now.
5074 assert(!ParamType.hasQualifiers() &&
5075 "non-type template parameter type cannot be qualified");
5076
5077 if (CTAK == CTAK_Deduced &&
Richard Smithd92eddf2016-12-27 06:14:37 +00005078 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
Richard Smith0e617ec2016-12-27 07:56:27 +00005079 Arg->getType())) {
Richard Smith4f9b3f42016-12-26 22:28:29 +00005080 // C++ [temp.deduct.type]p17: (DR1770)
5081 // If P has a form that contains <i>, and if the type of i differs from
5082 // the type of the corresponding template parameter of the template named
5083 // by the enclosing simple-template-id, deduction fails.
5084 //
5085 // Note that CTAK will be CTAK_DeducedFromArrayBound if the form was [i]
5086 // rather than <i>.
Richard Smithd92eddf2016-12-27 06:14:37 +00005087 //
5088 // FIXME: We interpret the 'i' here as referring to the expression
5089 // denoting the non-type template parameter rather than the parameter
5090 // itself, and so strip off references before comparing types. It's
5091 // not clear how this is supposed to work for references.
Richard Smithd663fdd2014-12-17 20:42:37 +00005092 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
Richard Smith0e617ec2016-12-27 07:56:27 +00005093 << Arg->getType()
Richard Smithd663fdd2014-12-17 20:42:37 +00005094 << ParamType.getUnqualifiedType();
5095 Diag(Param->getLocation(), diag::note_template_param_here);
5096 return ExprError();
5097 }
5098
Richard Smith87d263e2016-12-25 08:05:23 +00005099 // If either the parameter has a dependent type or the argument is
5100 // type-dependent, there's nothing we can check now.
5101 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5102 // FIXME: Produce a cloned, canonical expression?
5103 Converted = TemplateArgument(Arg);
5104 return Arg;
5105 }
5106
Richard Smith410cc892014-11-26 03:26:53 +00005107 if (getLangOpts().CPlusPlus1z) {
Richard Smith410cc892014-11-26 03:26:53 +00005108 // C++1z [temp.arg.nontype]p1:
5109 // A template-argument for a non-type template parameter shall be
5110 // a converted constant expression of the type of the template-parameter.
5111 APValue Value;
5112 ExprResult ArgResult = CheckConvertedConstantExpression(
5113 Arg, ParamType, Value, CCEK_TemplateArg);
5114 if (ArgResult.isInvalid())
5115 return ExprError();
5116
Richard Smith52e624f2016-12-21 21:42:57 +00005117 // For a value-dependent argument, CheckConvertedConstantExpression is
5118 // permitted (and expected) to be unable to determine a value.
5119 if (ArgResult.get()->isValueDependent()) {
Richard Smith01bfa682016-12-27 02:02:09 +00005120 Converted = TemplateArgument(ArgResult.get());
5121 return ArgResult;
Richard Smith52e624f2016-12-21 21:42:57 +00005122 }
5123
Richard Smithd663fdd2014-12-17 20:42:37 +00005124 QualType CanonParamType = Context.getCanonicalType(ParamType);
5125
Richard Smith410cc892014-11-26 03:26:53 +00005126 // Convert the APValue to a TemplateArgument.
5127 switch (Value.getKind()) {
5128 case APValue::Uninitialized:
5129 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005130 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005131 break;
5132 case APValue::Int:
5133 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005134 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005135 break;
5136 case APValue::MemberPointer: {
5137 assert(ParamType->isMemberPointerType());
5138
5139 // FIXME: We need TemplateArgument representation and mangling for these.
5140 if (!Value.getMemberPointerPath().empty()) {
5141 Diag(Arg->getLocStart(),
5142 diag::err_template_arg_member_ptr_base_derived_not_supported)
5143 << Value.getMemberPointerDecl() << ParamType
5144 << Arg->getSourceRange();
5145 return ExprError();
5146 }
5147
5148 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005149 Converted = VD ? TemplateArgument(VD, CanonParamType)
5150 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005151 break;
5152 }
5153 case APValue::LValue: {
5154 // For a non-type template-parameter of pointer or reference type,
5155 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005156 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5157 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005158 // -- a temporary object
5159 // -- a string literal
5160 // -- the result of a typeid expression, or
5161 // -- a predefind __func__ variable
5162 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5163 if (isa<CXXUuidofExpr>(E)) {
5164 Converted = TemplateArgument(const_cast<Expr*>(E));
5165 break;
5166 }
5167 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5168 << Arg->getSourceRange();
5169 return ExprError();
5170 }
5171 auto *VD = const_cast<ValueDecl *>(
5172 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5173 // -- a subobject
5174 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5175 VD && VD->getType()->isArrayType() &&
5176 Value.getLValuePath()[0].ArrayIndex == 0 &&
5177 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5178 // Per defect report (no number yet):
5179 // ... other than a pointer to the first element of a complete array
5180 // object.
5181 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5182 Value.isLValueOnePastTheEnd()) {
5183 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5184 << Value.getAsString(Context, ParamType);
5185 return ExprError();
5186 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005187 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005188 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005189 assert((!VD || !ParamType->isNullPtrType()) &&
5190 "non-null value of type nullptr_t?");
5191 Converted = VD ? TemplateArgument(VD, CanonParamType)
5192 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005193 break;
5194 }
5195 case APValue::AddrLabelDiff:
5196 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5197 case APValue::Float:
5198 case APValue::ComplexInt:
5199 case APValue::ComplexFloat:
5200 case APValue::Vector:
5201 case APValue::Array:
5202 case APValue::Struct:
5203 case APValue::Union:
5204 llvm_unreachable("invalid kind for template argument");
5205 }
5206
5207 return ArgResult.get();
5208 }
5209
Douglas Gregor86560402009-02-10 23:36:10 +00005210 // C++ [temp.arg.nontype]p5:
5211 // The following conversions are performed on each expression used
5212 // as a non-type template-argument. If a non-type
5213 // template-argument cannot be converted to the type of the
5214 // corresponding template-parameter then the program is
5215 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005216 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005217 // C++11:
5218 // -- for a non-type template-parameter of integral or
5219 // enumeration type, conversions permitted in a converted
5220 // constant expression are applied.
5221 //
5222 // C++98:
5223 // -- for a non-type template-parameter of integral or
5224 // enumeration type, integral promotions (4.5) and integral
5225 // conversions (4.7) are applied.
5226
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005227 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005228 // C++ [temp.arg.nontype]p1:
5229 // A template-argument for a non-type, non-template template-parameter
5230 // shall be one of:
5231 //
5232 // -- for a non-type template-parameter of integral or enumeration
5233 // type, a converted constant expression of the type of the
5234 // template-parameter; or
5235 llvm::APSInt Value;
5236 ExprResult ArgResult =
5237 CheckConvertedConstantExpression(Arg, ParamType, Value,
5238 CCEK_TemplateArg);
5239 if (ArgResult.isInvalid())
5240 return ExprError();
5241
Richard Smith01bfa682016-12-27 02:02:09 +00005242 // We can't check arbitrary value-dependent arguments.
5243 if (ArgResult.get()->isValueDependent()) {
5244 Converted = TemplateArgument(ArgResult.get());
5245 return ArgResult;
5246 }
5247
Richard Smithf8379a02012-01-18 23:55:52 +00005248 // Widen the argument value to sizeof(parameter type). This is almost
5249 // always a no-op, except when the parameter type is bool. In
5250 // that case, this may extend the argument from 1 bit to 8 bits.
5251 QualType IntegerType = ParamType;
5252 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5253 IntegerType = Enum->getDecl()->getIntegerType();
5254 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5255
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005256 Converted = TemplateArgument(Context, Value,
5257 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005258 return ArgResult;
5259 }
5260
Richard Smith08b12f12011-10-27 22:11:44 +00005261 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5262 if (ArgResult.isInvalid())
5263 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005264 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005265
5266 QualType ArgType = Arg->getType();
5267
Douglas Gregor86560402009-02-10 23:36:10 +00005268 // C++ [temp.arg.nontype]p1:
5269 // A template-argument for a non-type, non-template
5270 // template-parameter shall be one of:
5271 //
5272 // -- an integral constant-expression of integral or enumeration
5273 // type; or
5274 // -- the name of a non-type template-parameter; or
5275 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005276 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005277 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005278 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005279 diag::err_template_arg_not_integral_or_enumeral)
5280 << ArgType << Arg->getSourceRange();
5281 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005282 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005283 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005284 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5285 QualType T;
5286
5287 public:
5288 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005289
5290 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5291 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005292 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5293 }
5294 } Diagnoser(ArgType);
5295
5296 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005297 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005298 if (!Arg)
5299 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005300 }
5301
Richard Smithd663fdd2014-12-17 20:42:37 +00005302 // From here on out, all we care about is the unqualified form
5303 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005304 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005305
5306 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005307 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005308 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005309 } else if (ParamType->isBooleanType()) {
5310 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005311 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005312 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5313 !ParamType->isEnumeralType()) {
5314 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005315 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005316 } else {
5317 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005318 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005319 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005320 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005321 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005322 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005323 }
5324
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005325 // Add the value of this argument to the list of converted
5326 // arguments. We use the bitwidth and signedness of the template
5327 // parameter.
5328 if (Arg->isValueDependent()) {
5329 // The argument is value-dependent. Create a new
5330 // TemplateArgument with the converted expression.
5331 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005332 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005333 }
5334
Douglas Gregor52aba872009-03-14 00:20:21 +00005335 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005336 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005337 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005338
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005339 if (ParamType->isBooleanType()) {
5340 // Value must be zero or one.
5341 Value = Value != 0;
5342 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5343 if (Value.getBitWidth() != AllowedBits)
5344 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005345 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005346 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005347 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005350 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005351 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005352 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005353 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005354 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005355
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005356 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005357 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005358 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005359 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005360 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5361 << Arg->getSourceRange();
5362 Diag(Param->getLocation(), diag::note_template_param_here);
5363 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005364
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005365 // Complain if we overflowed the template parameter's type.
5366 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005367 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005368 RequiredBits = OldValue.getActiveBits();
5369 else if (OldValue.isUnsigned())
5370 RequiredBits = OldValue.getActiveBits() + 1;
5371 else
5372 RequiredBits = OldValue.getMinSignedBits();
5373 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005374 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005375 diag::warn_template_arg_too_large)
5376 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5377 << Arg->getSourceRange();
5378 Diag(Param->getLocation(), diag::note_template_param_here);
5379 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005380 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005381
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005382 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005383 ParamType->isEnumeralType()
5384 ? Context.getCanonicalType(ParamType)
5385 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005386 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005387 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005388
Richard Smith08b12f12011-10-27 22:11:44 +00005389 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005390 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5391
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005392 // Handle pointer-to-function, reference-to-function, and
5393 // pointer-to-member-function all in (roughly) the same way.
5394 if (// -- For a non-type template-parameter of type pointer to
5395 // function, only the function-to-pointer conversion (4.3) is
5396 // applied. If the template-argument represents a set of
5397 // overloaded functions (or a pointer to such), the matching
5398 // function is selected from the set (13.4).
5399 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005400 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005401 // -- For a non-type template-parameter of type reference to
5402 // function, no conversions apply. If the template-argument
5403 // represents a set of overloaded functions, the matching
5404 // function is selected from the set (13.4).
5405 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005406 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005407 // -- For a non-type template-parameter of type pointer to
5408 // member function, no conversions apply. If the
5409 // template-argument represents a set of overloaded member
5410 // functions, the matching member function is selected from
5411 // the set (13.4).
5412 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005413 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005414 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005415
Douglas Gregor064fdb22010-04-14 23:11:21 +00005416 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005417 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005418 true,
5419 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005420 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005421 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005422
5423 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5424 ArgType = Arg->getType();
5425 } else
John Wiegley01296292011-04-08 18:41:53 +00005426 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005428
John Wiegley01296292011-04-08 18:41:53 +00005429 if (!ParamType->isMemberPointerType()) {
5430 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5431 ParamType,
5432 Arg, Converted))
5433 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005434 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005435 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005436
Douglas Gregor20fdef32012-04-10 17:08:25 +00005437 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5438 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005439 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005440 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005441 }
5442
Chris Lattner696197c2009-02-20 21:37:53 +00005443 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005444 // -- for a non-type template-parameter of type pointer to
5445 // object, qualification conversions (4.4) and the
5446 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005447 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005448 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005449 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005450
John Wiegley01296292011-04-08 18:41:53 +00005451 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5452 ParamType,
5453 Arg, Converted))
5454 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005455 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005456 }
Mike Stump11289f42009-09-09 15:08:12 +00005457
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005458 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005459 // -- For a non-type template-parameter of type reference to
5460 // object, no conversions apply. The type referred to by the
5461 // reference may be more cv-qualified than the (otherwise
5462 // identical) type of the template-argument. The
5463 // template-parameter is bound directly to the
5464 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005465 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005466 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005467
Douglas Gregor064fdb22010-04-14 23:11:21 +00005468 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5470 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005471 true,
5472 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005473 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005474 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005475
5476 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5477 ArgType = Arg->getType();
5478 } else
John Wiegley01296292011-04-08 18:41:53 +00005479 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
John Wiegley01296292011-04-08 18:41:53 +00005482 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5483 ParamType,
5484 Arg, Converted))
5485 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005486 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005487 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005488
Douglas Gregor20fdef32012-04-10 17:08:25 +00005489 // Deal with parameters of type std::nullptr_t.
5490 if (ParamType->isNullPtrType()) {
5491 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5492 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005493 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005494 }
5495
5496 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5497 case NPV_NotNullPointer:
5498 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5499 << Arg->getType() << ParamType;
5500 Diag(Param->getLocation(), diag::note_template_param_here);
5501 return ExprError();
5502
5503 case NPV_Error:
5504 return ExprError();
5505
5506 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005507 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005508 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5509 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005510 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005511 }
5512 }
5513
Douglas Gregor0e558532009-02-11 16:16:59 +00005514 // -- For a non-type template-parameter of type pointer to data
5515 // member, qualification conversions (4.4) are applied.
5516 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5517
Douglas Gregor20fdef32012-04-10 17:08:25 +00005518 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5519 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005520 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005521 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005522}
5523
5524/// \brief Check a template argument against its corresponding
5525/// template template parameter.
5526///
5527/// This routine implements the semantics of C++ [temp.arg.template].
5528/// It returns true if an error occurred, and false otherwise.
5529bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005530 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005531 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005532 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005533 TemplateDecl *Template = Name.getAsTemplateDecl();
5534 if (!Template) {
5535 // Any dependent template name is fine.
5536 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5537 return false;
5538 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005539
Richard Smith3f1b5d02011-05-05 21:57:07 +00005540 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005541 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005542 // the name of a class template or an alias template, expressed as an
5543 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005544 // primary class templates are considered when matching the
5545 // template template argument with the corresponding parameter;
5546 // partial specializations are not considered even if their
5547 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005548 //
5549 // Note that we also allow template template parameters here, which
5550 // will happen when we are dealing with, e.g., class template
5551 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005552 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005553 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005554 !isa<TypeAliasTemplateDecl>(Template) &&
5555 !isa<BuiltinTemplateDecl>(Template)) {
5556 assert(isa<FunctionTemplateDecl>(Template) &&
5557 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005558 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005559 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5560 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005561 }
5562
Richard Smith1fde8ec2012-09-07 02:06:42 +00005563 TemplateParameterList *Params = Param->getTemplateParameters();
5564 if (Param->isExpandedParameterPack())
5565 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5566
Douglas Gregor85e0f662009-02-10 00:24:35 +00005567 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005568 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005570 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005571 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005572}
5573
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005574/// \brief Given a non-type template argument that refers to a
5575/// declaration and the type of its corresponding non-type template
5576/// parameter, produce an expression that properly refers to that
5577/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005579Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5580 QualType ParamType,
5581 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005582 // C++ [temp.param]p8:
5583 //
5584 // A non-type template-parameter of type "array of T" or
5585 // "function returning T" is adjusted to be of type "pointer to
5586 // T" or "pointer to function returning T", respectively.
5587 if (ParamType->isArrayType())
5588 ParamType = Context.getArrayDecayedType(ParamType);
5589 else if (ParamType->isFunctionType())
5590 ParamType = Context.getPointerType(ParamType);
5591
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005592 // For a NULL non-type template argument, return nullptr casted to the
5593 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005594 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005595 return ImpCastExprToType(
5596 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5597 ParamType,
5598 ParamType->getAs<MemberPointerType>()
5599 ? CK_NullToMemberPointer
5600 : CK_NullToPointer);
5601 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005602 assert(Arg.getKind() == TemplateArgument::Declaration &&
5603 "Only declaration template arguments permitted here");
5604
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005605 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5606
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005608 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5609 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005610 // If the value is a class member, we might have a pointer-to-member.
5611 // Determine whether the non-type template template parameter is of
5612 // pointer-to-member type. If so, we need to build an appropriate
5613 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5614 // would refer to the member itself.
5615 if (ParamType->isMemberPointerType()) {
5616 QualType ClassType
5617 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5618 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005619 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005620 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005621 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005622 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005623
5624 // The actual value-ness of this is unimportant, but for
5625 // internal consistency's sake, references to instance methods
5626 // are r-values.
5627 ExprValueKind VK = VK_LValue;
5628 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5629 VK = VK_RValue;
5630
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005631 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005632 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005633 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005634 Loc,
5635 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005636 if (RefExpr.isInvalid())
5637 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005638
John McCalle3027922010-08-25 11:45:40 +00005639 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005641 // We might need to perform a trailing qualification conversion, since
5642 // the element type on the parameter could be more qualified than the
5643 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005644 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005645 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005646 ParamType.getUnqualifiedType(), false,
5647 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005648 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005650 assert(!RefExpr.isInvalid() &&
5651 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005652 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005653 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005654 }
5655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005657 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005658
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005659 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005660 // When the non-type template parameter is a pointer, take the
5661 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005662 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005663 if (RefExpr.isInvalid())
5664 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005665
5666 if (T->isFunctionType() || T->isArrayType()) {
5667 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005668 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005669 if (RefExpr.isInvalid())
5670 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005671
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005672 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674
Douglas Gregorb242683d2010-04-01 18:32:35 +00005675 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005676 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005677 }
5678
John McCall7decc9e2010-11-18 06:31:45 +00005679 ExprValueKind VK = VK_RValue;
5680
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005681 // If the non-type template parameter has reference type, qualify the
5682 // resulting declaration reference with the extra qualifiers on the
5683 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005684 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5685 VK = VK_LValue;
5686 T = Context.getQualifiedType(T,
5687 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005688 } else if (isa<FunctionDecl>(VD)) {
5689 // References to functions are always lvalues.
5690 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005692
John McCall7decc9e2010-11-18 06:31:45 +00005693 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005694}
5695
5696/// \brief Construct a new expression that refers to the given
5697/// integral template argument with the given source-location
5698/// information.
5699///
5700/// This routine takes care of the mapping from an integral template
5701/// argument (which may have any integral type) to the appropriate
5702/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005704Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5705 SourceLocation Loc) {
5706 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005707 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005708 QualType OrigT = Arg.getIntegralType();
5709
5710 // If this is an enum type that we're instantiating, we need to use an integer
5711 // type the same size as the enumerator. We don't want to build an
5712 // IntegerLiteral with enum type. The integer type of an enum type can be of
5713 // any integral type with C++11 enum classes, make sure we create the right
5714 // type of literal for it.
5715 QualType T = OrigT;
5716 if (const EnumType *ET = OrigT->getAs<EnumType>())
5717 T = ET->getDecl()->getIntegerType();
5718
5719 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005720 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005721 // This does not need to handle u8 character literals because those are
5722 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005723 CharacterLiteral::CharacterKind Kind;
5724 if (T->isWideCharType())
5725 Kind = CharacterLiteral::Wide;
5726 else if (T->isChar16Type())
5727 Kind = CharacterLiteral::UTF16;
5728 else if (T->isChar32Type())
5729 Kind = CharacterLiteral::UTF32;
5730 else
5731 Kind = CharacterLiteral::Ascii;
5732
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005733 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5734 Kind, T, Loc);
5735 } else if (T->isBooleanType()) {
5736 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5737 T, Loc);
5738 } else if (T->isNullPtrType()) {
5739 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5740 } else {
5741 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005742 }
5743
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005744 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005745 // FIXME: This is a hack. We need a better way to handle substituted
5746 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005747 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5748 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005749 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005750 Loc, Loc);
5751 }
5752
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005753 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005754}
5755
Douglas Gregor641040a2011-01-12 23:45:44 +00005756/// \brief Match two template parameters within template parameter lists.
5757static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5758 bool Complain,
5759 Sema::TemplateParameterListEqualKind Kind,
5760 SourceLocation TemplateArgLoc) {
5761 // Check the actual kind (type, non-type, template).
5762 if (Old->getKind() != New->getKind()) {
5763 if (Complain) {
5764 unsigned NextDiag = diag::err_template_param_different_kind;
5765 if (TemplateArgLoc.isValid()) {
5766 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5767 NextDiag = diag::note_template_param_different_kind;
5768 }
5769 S.Diag(New->getLocation(), NextDiag)
5770 << (Kind != Sema::TPL_TemplateMatch);
5771 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5772 << (Kind != Sema::TPL_TemplateMatch);
5773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774
Douglas Gregor641040a2011-01-12 23:45:44 +00005775 return false;
5776 }
5777
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005778 // Check that both are parameter packs are neither are parameter packs.
5779 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005780 // template template parameter, the template template parameter can have
5781 // a parameter pack where the template template argument does not.
5782 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5783 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5784 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005785 if (Complain) {
5786 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5787 if (TemplateArgLoc.isValid()) {
5788 S.Diag(TemplateArgLoc,
5789 diag::err_template_arg_template_params_mismatch);
5790 NextDiag = diag::note_template_parameter_pack_non_pack;
5791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005792
Douglas Gregor641040a2011-01-12 23:45:44 +00005793 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5794 : isa<NonTypeTemplateParmDecl>(New)? 1
5795 : 2;
5796 S.Diag(New->getLocation(), NextDiag)
5797 << ParamKind << New->isParameterPack();
5798 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5799 << ParamKind << Old->isParameterPack();
5800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005801
Douglas Gregor641040a2011-01-12 23:45:44 +00005802 return false;
5803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005804
Douglas Gregor641040a2011-01-12 23:45:44 +00005805 // For non-type template parameters, check the type of the parameter.
5806 if (NonTypeTemplateParmDecl *OldNTTP
5807 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5808 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005809
Douglas Gregor641040a2011-01-12 23:45:44 +00005810 // If we are matching a template template argument to a template
5811 // template parameter and one of the non-type template parameter types
5812 // is dependent, then we must wait until template instantiation time
5813 // to actually compare the arguments.
5814 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5815 (OldNTTP->getType()->isDependentType() ||
5816 NewNTTP->getType()->isDependentType()))
5817 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005818
Douglas Gregor641040a2011-01-12 23:45:44 +00005819 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5820 if (Complain) {
5821 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5822 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005823 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005824 diag::err_template_arg_template_params_mismatch);
5825 NextDiag = diag::note_template_nontype_parm_different_type;
5826 }
5827 S.Diag(NewNTTP->getLocation(), NextDiag)
5828 << NewNTTP->getType()
5829 << (Kind != Sema::TPL_TemplateMatch);
5830 S.Diag(OldNTTP->getLocation(),
5831 diag::note_template_nontype_parm_prev_declaration)
5832 << OldNTTP->getType();
5833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005834
Douglas Gregor641040a2011-01-12 23:45:44 +00005835 return false;
5836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005837
Douglas Gregor641040a2011-01-12 23:45:44 +00005838 return true;
5839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005840
Douglas Gregor641040a2011-01-12 23:45:44 +00005841 // For template template parameters, check the template parameter types.
5842 // The template parameter lists of template template
5843 // parameters must agree.
5844 if (TemplateTemplateParmDecl *OldTTP
5845 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005846 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005847 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5848 OldTTP->getTemplateParameters(),
5849 Complain,
5850 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005851 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005852 : Kind),
5853 TemplateArgLoc);
5854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005855
Douglas Gregor641040a2011-01-12 23:45:44 +00005856 return true;
5857}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005858
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005859/// \brief Diagnose a known arity mismatch when comparing template argument
5860/// lists.
5861static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005863 TemplateParameterList *New,
5864 TemplateParameterList *Old,
5865 Sema::TemplateParameterListEqualKind Kind,
5866 SourceLocation TemplateArgLoc) {
5867 unsigned NextDiag = diag::err_template_param_list_different_arity;
5868 if (TemplateArgLoc.isValid()) {
5869 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5870 NextDiag = diag::note_template_param_list_different_arity;
5871 }
5872 S.Diag(New->getTemplateLoc(), NextDiag)
5873 << (New->size() > Old->size())
5874 << (Kind != Sema::TPL_TemplateMatch)
5875 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5876 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5877 << (Kind != Sema::TPL_TemplateMatch)
5878 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5879}
5880
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005881/// \brief Determine whether the given template parameter lists are
5882/// equivalent.
5883///
Mike Stump11289f42009-09-09 15:08:12 +00005884/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005885/// source code as part of a new template declaration.
5886///
5887/// \param Old The old template parameter list, typically found via
5888/// name lookup of the template declared with this template parameter
5889/// list.
5890///
5891/// \param Complain If true, this routine will produce a diagnostic if
5892/// the template parameter lists are not equivalent.
5893///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005894/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005895///
5896/// \param TemplateArgLoc If this source location is valid, then we
5897/// are actually checking the template parameter list of a template
5898/// argument (New) against the template parameter list of its
5899/// corresponding template template parameter (Old). We produce
5900/// slightly different diagnostics in this scenario.
5901///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005902/// \returns True if the template parameter lists are equal, false
5903/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005904bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005905Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5906 TemplateParameterList *Old,
5907 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005908 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005909 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005910 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5911 if (Complain)
5912 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5913 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005914
5915 return false;
5916 }
5917
Douglas Gregor641040a2011-01-12 23:45:44 +00005918 // C++0x [temp.arg.template]p3:
5919 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005920 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005921 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005922 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005923 // template-parameter-list of P. [...]
5924 TemplateParameterList::iterator NewParm = New->begin();
5925 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005926 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005927 OldParmEnd = Old->end();
5928 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005929 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5930 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005931 if (NewParm == NewParmEnd) {
5932 if (Complain)
5933 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5934 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005936 return false;
5937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005938
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005939 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5940 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005941 return false;
5942
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005943 ++NewParm;
5944 continue;
5945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005946
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005947 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005948 // [...] When P's template- parameter-list contains a template parameter
5949 // pack (14.5.3), the template parameter pack will match zero or more
5950 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005951 // template-parameter-list of A with the same type and form as the
5952 // template parameter pack in P (ignoring whether those template
5953 // parameters are template parameter packs).
5954 for (; NewParm != NewParmEnd; ++NewParm) {
5955 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5956 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005957 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005958 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005960
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005961 // Make sure we exhausted all of the arguments.
5962 if (NewParm != NewParmEnd) {
5963 if (Complain)
5964 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5965 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005966
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005967 return false;
5968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005969
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005970 return true;
5971}
5972
5973/// \brief Check whether a template can be declared within this scope.
5974///
5975/// If the template declaration is valid in this scope, returns
5976/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005977bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005978Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005979 if (!S)
5980 return false;
5981
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005982 // Find the nearest enclosing declaration scope.
5983 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5984 (S->getFlags() & Scope::TemplateParamScope) != 0)
5985 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005986
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005987 // C++ [temp]p4:
5988 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005989 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00005990 if (Ctx && Ctx->isExternCContext()) {
5991 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5992 << TemplateParams->getSourceRange();
5993 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
5994 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
5995 return true;
5996 }
Richard Smith8df390f2016-09-08 23:14:54 +00005997 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005998
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005999 // C++ [temp]p2:
6000 // A template-declaration can appear only as a namespace scope or
6001 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00006002 if (Ctx) {
6003 if (Ctx->isFileContext())
6004 return false;
6005 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6006 // C++ [temp.mem]p2:
6007 // A local class shall not have member templates.
6008 if (RD->isLocalClass())
6009 return Diag(TemplateParams->getTemplateLoc(),
6010 diag::err_template_inside_local_class)
6011 << TemplateParams->getSourceRange();
6012 else
6013 return false;
6014 }
6015 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006016
Mike Stump11289f42009-09-09 15:08:12 +00006017 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006018 diag::err_template_outside_namespace_or_class_scope)
6019 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00006020}
Douglas Gregor67a65642009-02-17 23:15:12 +00006021
Douglas Gregor54888652009-10-07 00:13:32 +00006022/// \brief Determine what kind of template specialization the given declaration
6023/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006024static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00006025 if (!D)
6026 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006027
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006028 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6029 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00006030 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6031 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006032 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6033 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006034
Douglas Gregor54888652009-10-07 00:13:32 +00006035 return TSK_Undeclared;
6036}
6037
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006038/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006039/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00006040///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006041/// This routine determines whether a template specialization can be declared
6042/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00006043///
6044/// \param S the semantic analysis object for which this check is being
6045/// performed.
6046///
6047/// \param Specialized the entity being specialized or instantiated, which
6048/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006049/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006050/// member class).
6051///
6052/// \param PrevDecl the previous declaration of this entity, if any.
6053///
6054/// \param Loc the location of the explicit specialization or instantiation of
6055/// this entity.
6056///
6057/// \param IsPartialSpecialization whether this is a partial specialization of
6058/// a class template.
6059///
Douglas Gregor54888652009-10-07 00:13:32 +00006060/// \returns true if there was an error that we cannot recover from, false
6061/// otherwise.
6062static bool CheckTemplateSpecializationScope(Sema &S,
6063 NamedDecl *Specialized,
6064 NamedDecl *PrevDecl,
6065 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006066 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006067 // Keep these "kind" numbers in sync with the %select statements in the
6068 // various diagnostics emitted by this routine.
6069 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006070 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006071 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006072 else if (isa<VarTemplateDecl>(Specialized))
6073 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006074 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006075 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006076 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006077 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006078 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006079 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006080 else if (isa<RecordDecl>(Specialized))
6081 EntityKind = 7;
6082 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6083 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006084 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006085 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006086 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006087 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006088 return true;
6089 }
6090
Douglas Gregorf47b9112009-02-25 22:02:03 +00006091 // C++ [temp.expl.spec]p2:
6092 // An explicit specialization shall be declared in the namespace
6093 // of which the template is a member, or, for member templates, in
6094 // the namespace of which the enclosing class or enclosing class
6095 // template is a member. An explicit specialization of a member
6096 // function, member class or static data member of a class
6097 // template shall be declared in the namespace of which the class
6098 // template is a member. Such a declaration may also be a
6099 // definition. If the declaration is not a definition, the
6100 // specialization may be defined later in the name- space in which
6101 // the explicit specialization was declared, or in a namespace
6102 // that encloses the one in which the explicit specialization was
6103 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006104 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006105 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006106 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006107 return true;
6108 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006109
Douglas Gregor40fb7442009-10-07 17:30:37 +00006110 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006111 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006112 // Do not warn for class scope explicit specialization during
6113 // instantiation, warning was already emitted during pattern
6114 // semantic analysis.
6115 if (!S.ActiveTemplateInstantiations.size())
6116 S.Diag(Loc, diag::ext_function_specialization_in_class)
6117 << Specialized;
6118 } else {
6119 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6120 << Specialized;
6121 return true;
6122 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006124
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006125 if (S.CurContext->isRecord() &&
6126 !S.CurContext->Equals(Specialized->getDeclContext())) {
6127 // Make sure that we're specializing in the right record context.
6128 // Otherwise, things can go horribly wrong.
6129 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6130 << Specialized;
6131 return true;
6132 }
6133
Douglas Gregore4b05162009-10-07 17:21:34 +00006134 // C++ [temp.class.spec]p6:
6135 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006136 // in any namespace scope in which its definition may be defined (14.5.1
6137 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006138 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006139 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006140 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006141
6142 // Make sure that this redeclaration (or definition) occurs in an enclosing
6143 // namespace.
6144 // Note that HandleDeclarator() performs this check for explicit
6145 // specializations of function templates, static data members, and member
6146 // functions, so we skip the check here for those kinds of entities.
6147 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6148 // Should we refactor that check, so that it occurs later?
6149 if (!DC->Encloses(SpecializedContext) &&
6150 !(isa<FunctionTemplateDecl>(Specialized) ||
6151 isa<FunctionDecl>(Specialized) ||
6152 isa<VarTemplateDecl>(Specialized) ||
6153 isa<VarDecl>(Specialized))) {
6154 if (isa<TranslationUnitDecl>(SpecializedContext))
6155 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6156 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006157 else if (isa<NamespaceDecl>(SpecializedContext)) {
6158 int Diag = diag::err_template_spec_redecl_out_of_scope;
6159 if (S.getLangOpts().MicrosoftExt)
6160 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6161 S.Diag(Loc, Diag) << EntityKind << Specialized
6162 << cast<NamedDecl>(SpecializedContext);
6163 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006164 llvm_unreachable("unexpected namespace context for specialization");
6165
6166 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6167 } else if ((!PrevDecl ||
6168 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6169 getTemplateSpecializationKind(PrevDecl) ==
6170 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006171 // C++ [temp.exp.spec]p2:
6172 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006173 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006174 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006175 // An explicit specialization of a member function, member class or
6176 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006177 // namespace of which the class template is a member.
6178 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006179 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006180 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006181 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006182 // C++11 [temp.explicit]p3:
6183 // An explicit instantiation shall appear in an enclosing namespace of its
6184 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006185 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006186 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006187 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006188 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006189 "DC encloses TU but isn't in enclosing namespace set");
6190 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006191 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006192 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6193 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006194 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006195 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006196 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006197 Diag = diag::ext_template_spec_decl_out_of_scope;
6198 else
6199 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6200 S.Diag(Loc, Diag)
6201 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006203
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006204 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006205 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006207
Douglas Gregorf47b9112009-02-25 22:02:03 +00006208 return false;
6209}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006210
Richard Smith6056d5e2014-02-09 00:54:43 +00006211static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6212 if (!E->isInstantiationDependent())
6213 return SourceLocation();
6214 DependencyChecker Checker(Depth);
6215 Checker.TraverseStmt(E);
6216 if (Checker.Match && Checker.MatchLoc.isInvalid())
6217 return E->getSourceRange();
6218 return Checker.MatchLoc;
6219}
6220
6221static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6222 if (!TL.getType()->isDependentType())
6223 return SourceLocation();
6224 DependencyChecker Checker(Depth);
6225 Checker.TraverseTypeLoc(TL);
6226 if (Checker.Match && Checker.MatchLoc.isInvalid())
6227 return TL.getSourceRange();
6228 return Checker.MatchLoc;
6229}
6230
Larisse Voufo39a1e502013-08-06 01:03:05 +00006231/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006232/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006233static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006234 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6235 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006236 for (unsigned I = 0; I != NumArgs; ++I) {
6237 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006238 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006239 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6240 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006241 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006242
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006243 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006244 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006245
Eli Friedmanb826a002012-09-26 02:36:12 +00006246 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006247 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006248
6249 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006250
Douglas Gregor98318c22011-01-03 21:37:45 +00006251 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006252 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6253 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006254
6255 // Strip off any implicit casts we added as part of type checking.
6256 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6257 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006258
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006259 // C++ [temp.class.spec]p8:
6260 // A non-type argument is non-specialized if it is the name of a
6261 // non-type parameter. All other non-type arguments are
6262 // specialized.
6263 //
6264 // Below, we check the two conditions that only apply to
6265 // specialized non-type arguments, so skip any non-specialized
6266 // arguments.
6267 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006268 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006269 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006270
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006271 // C++ [temp.class.spec]p9:
6272 // Within the argument list of a class template partial
6273 // specialization, the following restrictions apply:
6274 // -- A partially specialized non-type argument expression
6275 // shall not involve a template parameter of the partial
6276 // specialization except when the argument expression is a
6277 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006278 SourceRange ParamUseRange =
6279 findTemplateParameter(Param->getDepth(), ArgExpr);
6280 if (ParamUseRange.isValid()) {
6281 if (IsDefaultArgument) {
6282 S.Diag(TemplateNameLoc,
6283 diag::err_dependent_non_type_arg_in_partial_spec);
6284 S.Diag(ParamUseRange.getBegin(),
6285 diag::note_dependent_non_type_default_arg_in_partial_spec)
6286 << ParamUseRange;
6287 } else {
6288 S.Diag(ParamUseRange.getBegin(),
6289 diag::err_dependent_non_type_arg_in_partial_spec)
6290 << ParamUseRange;
6291 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006292 return true;
6293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006294
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006295 // -- The type of a template parameter corresponding to a
6296 // specialized non-type argument shall not be dependent on a
6297 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006298 //
6299 // FIXME: We need to delay this check until instantiation in some cases:
6300 //
6301 // template<template<typename> class X> struct A {
6302 // template<typename T, X<T> N> struct B;
6303 // template<typename T> struct B<T, 0>;
6304 // };
6305 // template<typename> using X = int;
6306 // A<X>::B<int, 0> b;
6307 ParamUseRange = findTemplateParameter(
6308 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6309 if (ParamUseRange.isValid()) {
6310 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6311 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6312 << Param->getType() << ParamUseRange;
6313 S.Diag(Param->getLocation(), diag::note_template_param_here)
6314 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006315 return true;
6316 }
6317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006318
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006319 return false;
6320}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006321
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006322/// \brief Check the non-type template arguments of a class template
6323/// partial specialization according to C++ [temp.class.spec]p9.
6324///
Richard Smith6056d5e2014-02-09 00:54:43 +00006325/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006326/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006327/// template.
6328/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006329/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006330/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006331///
Richard Smith6056d5e2014-02-09 00:54:43 +00006332/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006333static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006334 Sema &S, SourceLocation TemplateNameLoc,
6335 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006336 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006337 const TemplateArgument *ArgList = TemplateArgs.data();
6338
6339 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6340 NonTypeTemplateParmDecl *Param
6341 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6342 if (!Param)
6343 continue;
6344
Richard Smith6056d5e2014-02-09 00:54:43 +00006345 if (CheckNonTypeTemplatePartialSpecializationArgs(
6346 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006347 return true;
6348 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006349
6350 return false;
6351}
6352
John McCall48871652010-08-21 09:40:31 +00006353DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006354Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6355 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006356 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006357 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006358 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006359 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006360 MultiTemplateParamsArg
6361 TemplateParameterLists,
6362 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006363 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006364
Richard Smith4b55a9c2014-04-17 03:29:33 +00006365 CXXScopeSpec &SS = TemplateId.SS;
6366
Abramo Bagnara60804e12011-03-18 15:16:37 +00006367 // NOTE: KWLoc is the location of the tag keyword. This will instead
6368 // store the location of the outermost template keyword in the declaration.
6369 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006370 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6371 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6372 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6373 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006374
Douglas Gregor67a65642009-02-17 23:15:12 +00006375 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006376 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006377 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006378 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6379
6380 if (!ClassTemplate) {
6381 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006382 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006383 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6384 return true;
6385 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006386
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006387 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006388 bool isPartialSpecialization = false;
6389
Douglas Gregorf47b9112009-02-25 22:02:03 +00006390 // Check the validity of the template headers that introduce this
6391 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006392 // FIXME: We probably shouldn't complain about these headers for
6393 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006394 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006395 TemplateParameterList *TemplateParams =
6396 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006397 KWLoc, TemplateNameLoc, SS, &TemplateId,
6398 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6399 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006400 if (Invalid)
6401 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006402
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006403 if (TemplateParams && TemplateParams->size() > 0) {
6404 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006405
Douglas Gregorec9518b2010-12-21 08:14:57 +00006406 if (TUK == TUK_Friend) {
6407 Diag(KWLoc, diag::err_partial_specialization_friend)
6408 << SourceRange(LAngleLoc, RAngleLoc);
6409 return true;
6410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006411
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006412 // C++ [temp.class.spec]p10:
6413 // The template parameter list of a specialization shall not
6414 // contain default template argument values.
6415 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6416 Decl *Param = TemplateParams->getParam(I);
6417 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6418 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006419 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006420 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006421 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006422 }
6423 } else if (NonTypeTemplateParmDecl *NTTP
6424 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6425 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006426 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006427 diag::err_default_arg_in_partial_spec)
6428 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006429 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006430 }
6431 } else {
6432 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006433 if (TTP->hasDefaultArgument()) {
6434 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006435 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006436 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006437 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006438 }
6439 }
6440 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006441 } else if (TemplateParams) {
6442 if (TUK == TUK_Friend)
6443 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006444 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006445 SourceRange(TemplateParams->getTemplateLoc(),
6446 TemplateParams->getRAngleLoc()))
6447 << SourceRange(LAngleLoc, RAngleLoc);
6448 else
6449 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006450 } else {
6451 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006452 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006453
Douglas Gregor67a65642009-02-17 23:15:12 +00006454 // Check that the specialization uses the same tag kind as the
6455 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006456 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6457 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006458 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006459 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006460 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006461 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006462 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006463 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006464 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006465 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006466 diag::note_previous_use);
6467 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6468 }
6469
Douglas Gregorc40290e2009-03-09 23:48:35 +00006470 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006471 TemplateArgumentListInfo TemplateArgs =
6472 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006473
Douglas Gregor14406932011-01-03 20:35:03 +00006474 // Check for unexpanded parameter packs in any of the template arguments.
6475 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006477 UPPC_PartialSpecialization))
6478 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479
Douglas Gregor67a65642009-02-17 23:15:12 +00006480 // Check that the template argument list is well-formed for this
6481 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006482 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006483 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6484 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006485 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006486
Douglas Gregor2373c592009-05-31 09:31:02 +00006487 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006488 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006489 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006490 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006491 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6492 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006493 return true;
6494
Douglas Gregor678d76c2011-07-01 01:22:09 +00006495 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006496 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006497 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006498 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006499 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6500 << ClassTemplate->getDeclName();
6501 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006502 }
6503 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006504
Craig Topperc3ec1492014-05-26 06:22:03 +00006505 void *InsertPos = nullptr;
6506 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006507
6508 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006509 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006510 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006511 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006512 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006513
Craig Topperc3ec1492014-05-26 06:22:03 +00006514 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006515
Douglas Gregorf47b9112009-02-25 22:02:03 +00006516 // Check whether we can declare a class template specialization in
6517 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006518 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6520 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006521 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006522 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006523
Douglas Gregor15301382009-07-30 17:40:51 +00006524 // The canonical type
6525 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006526 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006527 // Build the canonical type that describes the converted template
6528 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006529 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6530 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006531 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532
6533 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006534 ClassTemplate->getInjectedClassNameSpecialization())) {
6535 // C++ [temp.class.spec]p9b3:
6536 //
6537 // -- The argument list of the specialization shall not be identical
6538 // to the implicit argument list of the primary template.
Richard Smith0e617ec2016-12-27 07:56:27 +00006539 //
6540 // This rule has since been removed, because it's redundant given DR1495,
6541 // but we keep it because it produces better diagnostics and recovery.
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006542 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006543 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006544 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006545 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6546 ClassTemplate->getIdentifier(),
6547 TemplateNameLoc,
6548 Attr,
6549 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006550 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006551 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006552 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006553 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006554 }
Douglas Gregor15301382009-07-30 17:40:51 +00006555
Douglas Gregor2373c592009-05-31 09:31:02 +00006556 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006557 ClassTemplatePartialSpecializationDecl *PrevPartial
6558 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006559 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006560 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006561 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006562 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006563 TemplateParams,
6564 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006565 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006566 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006567 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006568 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006569 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006570 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006571 Partial->setTemplateParameterListsInfo(
6572 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006573 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006574
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006575 if (!PrevPartial)
6576 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006577 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006578
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006579 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006580 // template specialization, make a note of that.
6581 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6582 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006583
Richard Smith0e617ec2016-12-27 07:56:27 +00006584 // C++1z [temp.class.spec]p8: (DR1495)
6585 // - The specialization shall be more specialized than the primary
6586 // template (14.5.5.2).
6587 checkMoreSpecializedThanPrimary(*this, Partial);
6588
Douglas Gregor91772d12009-06-13 00:26:55 +00006589 // Check that all of the template parameters of the class template
6590 // partial specialization are deducible from the template
6591 // arguments. If not, this class template partial specialization
6592 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006593 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006595 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006596 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006597
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006598 if (!DeducibleParams.all()) {
6599 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006600 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006601 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006602 << SourceRange(TemplateNameLoc, RAngleLoc);
6603 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6604 if (!DeducibleParams[I]) {
6605 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6606 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006607 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006608 diag::note_partial_spec_unused_parameter)
6609 << Param->getDeclName();
6610 else
Mike Stump11289f42009-09-09 15:08:12 +00006611 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006612 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006613 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006614 }
6615 }
6616 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006617 } else {
6618 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006619 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006620 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006621 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006622 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006623 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006624 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006625 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006626 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006627 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006628 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006629 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006630 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006631 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006632
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006633 if (!PrevDecl)
6634 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006635
David Majnemer678f50b2015-11-18 19:49:19 +00006636 if (CurContext->isDependentContext()) {
6637 // -fms-extensions permits specialization of nested classes without
6638 // fully specializing the outer class(es).
6639 assert(getLangOpts().MicrosoftExt &&
6640 "Only possible with -fms-extensions!");
6641 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6642 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006643 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006644 } else {
6645 CanonType = Context.getTypeDeclType(Specialization);
6646 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006647 }
6648
Douglas Gregor06db9f52009-10-12 20:18:28 +00006649 // C++ [temp.expl.spec]p6:
6650 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006652 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006653 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006654 // use occurs; no diagnostic is required.
6655 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006656 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006657 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006658 // Is there any previous explicit specialization declaration?
6659 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6660 Okay = true;
6661 break;
6662 }
6663 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006664
Douglas Gregorc854c662010-02-26 06:03:23 +00006665 if (!Okay) {
6666 SourceRange Range(TemplateNameLoc, RAngleLoc);
6667 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6668 << Context.getTypeDeclType(Specialization) << Range;
6669
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006670 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006671 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006672 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006673 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006674 return true;
6675 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677
Douglas Gregor2208a292009-09-26 20:57:03 +00006678 // If this is not a friend, note that this is an explicit specialization.
6679 if (TUK != TUK_Friend)
6680 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006681
6682 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006683 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006684 RecordDecl *Def = Specialization->getDefinition();
6685 NamedDecl *Hidden = nullptr;
6686 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6687 SkipBody->ShouldSkip = true;
6688 makeMergedDefinitionVisible(Hidden, KWLoc);
6689 // From here on out, treat this as just a redeclaration.
6690 TUK = TUK_Declaration;
6691 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006692 SourceRange Range(TemplateNameLoc, RAngleLoc);
Richard Smith792c22d2016-12-24 04:09:05 +00006693 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006694 Diag(Def->getLocation(), diag::note_previous_definition);
6695 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006696 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006697 }
6698 }
6699
John McCall659a3372010-12-18 03:30:47 +00006700 if (Attr)
6701 ProcessDeclAttributeList(S, Specialization, Attr);
6702
Richard Smith034b94a2012-08-17 03:20:55 +00006703 // Add alignment attributes if necessary; these attributes are checked when
6704 // the ASTContext lays out the structure.
6705 if (TUK == TUK_Definition) {
6706 AddAlignmentAttributesForRecord(Specialization);
6707 AddMsStructLayoutForRecord(Specialization);
6708 }
6709
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006710 if (ModulePrivateLoc.isValid())
6711 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6712 << (isPartialSpecialization? 1 : 0)
6713 << FixItHint::CreateRemoval(ModulePrivateLoc);
6714
Douglas Gregord56a91e2009-02-26 22:19:44 +00006715 // Build the fully-sugared type for this class template
6716 // specialization as the user wrote in the specialization
6717 // itself. This means that we'll pretty-print the type retrieved
6718 // from the specialization's declaration the way that the user
6719 // actually wrote the specialization, rather than formatting the
6720 // name based on the "canonical" representation used to store the
6721 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006722 TypeSourceInfo *WrittenTy
6723 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6724 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006725 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006726 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006727 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006728 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006729
Douglas Gregor1e249f82009-02-25 22:18:32 +00006730 // C++ [temp.expl.spec]p9:
6731 // A template explicit specialization is in the scope of the
6732 // namespace in which the template was defined.
6733 //
6734 // We actually implement this paragraph where we set the semantic
6735 // context (in the creation of the ClassTemplateSpecializationDecl),
6736 // but we also maintain the lexical context where the actual
6737 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006738 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006739
Douglas Gregor67a65642009-02-17 23:15:12 +00006740 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006741 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006742 Specialization->startDefinition();
6743
Douglas Gregor2208a292009-09-26 20:57:03 +00006744 if (TUK == TUK_Friend) {
6745 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6746 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006747 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006748 /*FIXME:*/KWLoc);
6749 Friend->setAccess(AS_public);
6750 CurContext->addDecl(Friend);
6751 } else {
6752 // Add the specialization into its lexical context, so that it can
6753 // be seen when iterating through the list of declarations in that
6754 // context. However, specializations are not found by name lookup.
6755 CurContext->addDecl(Specialization);
6756 }
John McCall48871652010-08-21 09:40:31 +00006757 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006758}
Douglas Gregor333489b2009-03-27 23:10:48 +00006759
John McCall48871652010-08-21 09:40:31 +00006760Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006761 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006762 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006763 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006764 ActOnDocumentableDecl(NewDecl);
6765 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006766}
6767
John McCall4f7ced62010-02-11 01:33:53 +00006768/// \brief Strips various properties off an implicit instantiation
6769/// that has just been explicitly specialized.
6770static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006771 D->dropAttr<DLLImportAttr>();
6772 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006773
Nico Webere4974382014-12-19 23:52:45 +00006774 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006775 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006776}
6777
Nico Webera8f80b32012-01-09 19:52:25 +00006778/// \brief Compute the diagnostic location for an explicit instantiation
6779// declaration or definition.
6780static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006781 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006782 // Explicit instantiations following a specialization have no effect and
6783 // hence no PointOfInstantiation. In that case, walk decl backwards
6784 // until a valid name loc is found.
6785 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006786 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6787 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006788 PrevDiagLoc = Prev->getLocation();
6789 }
6790 assert(PrevDiagLoc.isValid() &&
6791 "Explicit instantiation without point of instantiation?");
6792 return PrevDiagLoc;
6793}
6794
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006796/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006797/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006798/// new specialization/instantiation will have any effect.
6799///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006801/// instantiation.
6802///
6803/// \param NewTSK the kind of the new explicit specialization or instantiation.
6804///
6805/// \param PrevDecl the previous declaration of the entity.
6806///
6807/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6808///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006809/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006810/// declaration was instantiated (either implicitly or explicitly).
6811///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006812/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006813/// specialization or instantiation has no effect and should be ignored.
6814///
6815/// \returns true if there was an error that should prevent the introduction of
6816/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006817bool
6818Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6819 TemplateSpecializationKind NewTSK,
6820 NamedDecl *PrevDecl,
6821 TemplateSpecializationKind PrevTSK,
6822 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006823 bool &HasNoEffect) {
6824 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006825
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006826 switch (NewTSK) {
6827 case TSK_Undeclared:
6828 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006829 assert(
6830 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6831 "previous declaration must be implicit!");
6832 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006833
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006834 case TSK_ExplicitSpecialization:
6835 switch (PrevTSK) {
6836 case TSK_Undeclared:
6837 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006838 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006839 // explicitly specialized or has merely been mentioned without any
6840 // instantiation.
6841 return false;
6842
6843 case TSK_ImplicitInstantiation:
6844 if (PrevPointOfInstantiation.isInvalid()) {
6845 // The declaration itself has not actually been instantiated, so it is
6846 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006847 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006848 return false;
6849 }
6850 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006851
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006852 case TSK_ExplicitInstantiationDeclaration:
6853 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854 assert((PrevTSK == TSK_ImplicitInstantiation ||
6855 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006856 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006857
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006858 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006859 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006860 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006862 // implicit instantiation to take place, in every translation unit in
6863 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006864 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006865 // Is there any previous explicit specialization declaration?
6866 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6867 return false;
6868 }
6869
Douglas Gregor1d957a32009-10-27 18:42:08 +00006870 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006871 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006872 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006873 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006874
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006875 return true;
6876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006877
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006878 case TSK_ExplicitInstantiationDeclaration:
6879 switch (PrevTSK) {
6880 case TSK_ExplicitInstantiationDeclaration:
6881 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006882 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006883 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006884
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006885 case TSK_Undeclared:
6886 case TSK_ImplicitInstantiation:
6887 // We're explicitly instantiating something that may have already been
6888 // implicitly instantiated; that's fine.
6889 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006890
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006891 case TSK_ExplicitSpecialization:
6892 // C++0x [temp.explicit]p4:
6893 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006895 // specialization for that template, the explicit instantiation has no
6896 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006897 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006898 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006899
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006900 case TSK_ExplicitInstantiationDefinition:
6901 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006902 // If an entity is the subject of both an explicit instantiation
6903 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006904 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006906 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006907
6908 // Explicit instantiations following a specialization have no effect and
6909 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6910 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006911 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6912 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006913 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006914 return false;
6915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006917 case TSK_ExplicitInstantiationDefinition:
6918 switch (PrevTSK) {
6919 case TSK_Undeclared:
6920 case TSK_ImplicitInstantiation:
6921 // We're explicitly instantiating something that may have already been
6922 // implicitly instantiated; that's fine.
6923 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006925 case TSK_ExplicitSpecialization:
6926 // C++ DR 259, C++0x [temp.explicit]p4:
6927 // For a given set of template parameters, if an explicit
6928 // instantiation of a template appears after a declaration of
6929 // an explicit specialization for that template, the explicit
6930 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00006931 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006932 << PrevDecl;
6933 Diag(PrevDecl->getLocation(),
6934 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006935 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006936 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006938 case TSK_ExplicitInstantiationDeclaration:
6939 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006941
6942 // C++0x [temp.explicit]p4:
6943 // For a given set of template parameters, if an explicit instantiation
6944 // of a template appears after a declaration of an explicit
6945 // specialization for that template, the explicit instantiation has no
6946 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006947 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006948 // Is there any previous explicit specialization declaration?
6949 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6950 HasNoEffect = true;
6951 break;
6952 }
6953 }
6954
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006955 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006957 case TSK_ExplicitInstantiationDefinition:
6958 // C++0x [temp.spec]p5:
6959 // For a given template and a given set of template-arguments,
6960 // - an explicit instantiation definition shall appear at most once
6961 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006962
6963 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6964 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006965 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006966 : diag::err_explicit_instantiation_duplicate)
6967 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006968 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006969 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006970 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006971 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006972 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006974
David Blaikie83d382b2011-09-23 05:06:16 +00006975 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006976}
6977
John McCallb9c78482010-04-08 09:05:18 +00006978/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006979/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006980///
James Dennettf14a6e52012-06-15 22:23:43 +00006981/// The only possible way to get a dependent function template specialization
6982/// is with a friend declaration, like so:
6983///
6984/// \code
6985/// template \<class T> void foo(T);
6986/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006987/// friend void foo<>(T);
6988/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006989/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006990///
6991/// There really isn't any useful analysis we can do here, so we
6992/// just store the information.
6993bool
6994Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6995 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6996 LookupResult &Previous) {
6997 // Remove anything from Previous that isn't a function template in
6998 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006999 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00007000 LookupResult::Filter F = Previous.makeFilter();
7001 while (F.hasNext()) {
7002 NamedDecl *D = F.next()->getUnderlyingDecl();
7003 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00007004 !FDLookupContext->InEnclosingNamespaceSetOf(
7005 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00007006 F.erase();
7007 }
7008 F.done();
7009
7010 // Should this be diagnosed here?
7011 if (Previous.empty()) return true;
7012
7013 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7014 ExplicitTemplateArgs);
7015 return false;
7016}
7017
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007018/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007019/// specialization.
7020///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007021/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007022/// explicit function template specialization. On successful completion,
7023/// the function declaration \p FD will become a function template
7024/// specialization.
7025///
7026/// \param FD the function declaration, which will be updated to become a
7027/// function template specialization.
7028///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007029/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7030/// if any. Note that this may be valid info even when 0 arguments are
7031/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7032/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007033///
Francois Pichet3a44e432011-07-08 06:21:47 +00007034/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007035/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007036bool Sema::CheckFunctionTemplateSpecialization(
7037 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7038 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007039 // The set of function template specializations that could match this
7040 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00007041 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007042 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7043 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007044
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007045 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7046 ConvertedTemplateArgs;
7047
Sebastian Redl50c68252010-08-31 00:36:30 +00007048 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00007049 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7050 I != E; ++I) {
7051 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7052 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007054 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007055 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7056 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007057 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007058
Richard Smith574f4f62013-01-14 05:37:29 +00007059 // When matching a constexpr member function template specialization
7060 // against the primary template, we don't yet know whether the
7061 // specialization has an implicit 'const' (because we don't know whether
7062 // it will be a static member function until we know which template it
7063 // specializes), so adjust it now assuming it specializes this template.
7064 QualType FT = FD->getType();
7065 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007066 CXXMethodDecl *OldMD =
7067 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007068 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007069 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007070 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7071 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007072 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007073 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007074 }
7075 }
7076
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007077 TemplateArgumentListInfo Args;
7078 if (ExplicitTemplateArgs)
7079 Args = *ExplicitTemplateArgs;
7080
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007081 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007082 // A trailing template-argument can be left unspecified in the
7083 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007084 // provided it can be deduced from the function argument type.
7085 // Perform template argument deduction to determine whether we may be
7086 // specializing this template.
7087 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007088 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007089 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007090 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7091 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007092 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7093 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007094 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007095 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007096 FailedCandidates.addCandidate().set(
7097 I.getPair(), FunTmpl->getTemplatedDecl(),
7098 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007099 (void)TDK;
7100 continue;
7101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007102
Artem Belevich64135c32016-12-08 19:38:13 +00007103 // Target attributes are part of the cuda function signature, so
7104 // the deduced template's cuda target must match that of the
7105 // specialization. Given that C++ template deduction does not
7106 // take target attributes into account, we reject candidates
7107 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007108 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007109 IdentifyCUDATarget(Specialization,
7110 /* IgnoreImplicitHDAttributes = */ true) !=
7111 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007112 FailedCandidates.addCandidate().set(
7113 I.getPair(), FunTmpl->getTemplatedDecl(),
7114 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7115 continue;
7116 }
7117
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007118 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007119 if (ExplicitTemplateArgs)
7120 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007121 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007122 }
7123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007124
Douglas Gregor5de279c2009-09-26 03:41:46 +00007125 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007126 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007127 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007128 FD->getLocation(),
7129 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7130 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007131 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007132 PDiag(diag::note_function_template_spec_matched));
7133
John McCall58cc69d2010-01-27 01:50:18 +00007134 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007135 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007136
7137 // Ignore access information; it doesn't figure into redeclaration checking.
7138 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007139
Nathan Wilson83839122016-04-09 02:55:27 +00007140 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7141 // an explicit specialization (14.8.3) [...] of a concept definition.
7142 if (Specialization->getPrimaryTemplate()->isConcept()) {
7143 Diag(FD->getLocation(), diag::err_concept_specialized)
7144 << 0 /*function*/ << 1 /*explicitly specialized*/;
7145 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7146 return true;
7147 }
7148
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007149 FunctionTemplateSpecializationInfo *SpecInfo
7150 = Specialization->getTemplateSpecializationInfo();
7151 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007152
7153 // Note: do not overwrite location info if previous template
7154 // specialization kind was explicit.
7155 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007156 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007157 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007158 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7159 // function can differ from the template declaration with respect to
7160 // the constexpr specifier.
7161 Specialization->setConstexpr(FD->isConstexpr());
7162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007163
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007164 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007165 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007166
7167 // If this is a friend declaration, then we're not really declaring
7168 // an explicit specialization.
7169 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007170
Douglas Gregor54888652009-10-07 00:13:32 +00007171 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007172 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007173 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007174 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007175 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007176 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007177 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007178
7179 // C++ [temp.expl.spec]p6:
7180 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007181 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007182 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007184 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007185 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007186 if (!isFriend &&
7187 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007188 TSK_ExplicitSpecialization,
7189 Specialization,
7190 SpecInfo->getTemplateSpecializationKind(),
7191 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007192 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007193 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007194
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007195 // Mark the prior declaration as an explicit specialization, so that later
7196 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007197 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007198 // Since explicit specializations do not inherit '=delete' from their
7199 // primary function template - check if the 'specialization' that was
7200 // implicitly generated (during template argument deduction for partial
7201 // ordering) from the most specialized of all the function templates that
7202 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7203 // first check that it was implicitly generated during template argument
7204 // deduction by making sure it wasn't referenced, and then reset the deleted
7205 // flag to not-deleted, so that we can inherit that information from 'FD'.
7206 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7207 !Specialization->getCanonicalDecl()->isReferenced()) {
7208 assert(
7209 Specialization->getCanonicalDecl() == Specialization &&
7210 "This must be the only existing declaration of this specialization");
7211 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007212 }
John McCall816d75b2010-03-24 07:46:06 +00007213 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007214 MarkUnusedFileScopedDecl(Specialization);
7215 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007216
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007217 // Turn the given function declaration into a function template
7218 // specialization, with the template arguments from the previous
7219 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007220 // Take copies of (semantic and syntactic) template argument lists.
7221 const TemplateArgumentList* TemplArgs = new (Context)
7222 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007223 FD->setFunctionTemplateSpecialization(
7224 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7225 SpecInfo->getTemplateSpecializationKind(),
7226 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007227
Artem Belevich64135c32016-12-08 19:38:13 +00007228 // A function template specialization inherits the target attributes
7229 // of its template. (We require the attributes explicitly in the
7230 // code to match, but a template may have implicit attributes by
7231 // virtue e.g. of being constexpr, and it passes these implicit
7232 // attributes on to its specializations.)
7233 if (LangOpts.CUDA)
7234 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7235
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007236 // The "previous declaration" for this function template specialization is
7237 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007238 Previous.clear();
7239 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007240 return false;
7241}
7242
Douglas Gregor86d142a2009-10-08 07:24:58 +00007243/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007244/// specialization.
7245///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007246/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007247/// explicit member function specialization. On successful completion,
7248/// the function declaration \p FD will become a member function
7249/// specialization.
7250///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007251/// \param Member the member declaration, which will be updated to become a
7252/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007253///
John McCall1f82f242009-11-18 22:49:29 +00007254/// \param Previous the set of declarations, one of which may be specialized
7255/// by this function specialization; the set will be modified to contain the
7256/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007257bool
John McCall1f82f242009-11-18 22:49:29 +00007258Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007259 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007260
Douglas Gregor86d142a2009-10-08 07:24:58 +00007261 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007262 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007263 NamedDecl *Instantiation = nullptr;
7264 NamedDecl *InstantiatedFrom = nullptr;
7265 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007266
John McCall1f82f242009-11-18 22:49:29 +00007267 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007268 // Nowhere to look anyway.
7269 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007270 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7271 I != E; ++I) {
7272 NamedDecl *D = (*I)->getUnderlyingDecl();
7273 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007274 QualType Adjusted = Function->getType();
7275 if (!hasExplicitCallingConv(Adjusted))
7276 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7277 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007278 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007279 Instantiation = Method;
7280 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007281 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007282 break;
7283 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007284 }
7285 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007286 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007287 VarDecl *PrevVar;
7288 if (Previous.isSingleResult() &&
7289 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007290 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007291 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007292 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007293 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007294 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007295 }
7296 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007297 CXXRecordDecl *PrevRecord;
7298 if (Previous.isSingleResult() &&
7299 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007300 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007301 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007302 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007303 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007304 }
Richard Smith7d137e32012-03-23 03:33:32 +00007305 } else if (isa<EnumDecl>(Member)) {
7306 EnumDecl *PrevEnum;
7307 if (Previous.isSingleResult() &&
7308 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007309 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007310 Instantiation = PrevEnum;
7311 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7312 MSInfo = PrevEnum->getMemberSpecializationInfo();
7313 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007315
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007316 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007317 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007318 // specializations are always out-of-line, the caller will complain about
7319 // this mismatch later.
7320 return false;
7321 }
John McCalle820e5e2010-04-13 20:37:33 +00007322
7323 // If this is a friend, just bail out here before we start turning
7324 // things into explicit specializations.
7325 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7326 // Preserve instantiation information.
7327 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7328 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7329 cast<CXXMethodDecl>(InstantiatedFrom),
7330 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7331 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7332 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7333 cast<CXXRecordDecl>(InstantiatedFrom),
7334 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7335 }
7336
7337 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007338 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007339 return false;
7340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007341
Douglas Gregor86d142a2009-10-08 07:24:58 +00007342 // Make sure that this is a specialization of a member.
7343 if (!InstantiatedFrom) {
7344 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7345 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007346 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7347 return true;
7348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007349
Douglas Gregor06db9f52009-10-12 20:18:28 +00007350 // C++ [temp.expl.spec]p6:
7351 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007352 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007353 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007354 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007355 // use occurs; no diagnostic is required.
7356 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007357
Abramo Bagnara8075c852010-06-12 07:44:57 +00007358 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007359 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7360 TSK_ExplicitSpecialization,
7361 Instantiation,
7362 MSInfo->getTemplateSpecializationKind(),
7363 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007364 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007365 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007366
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007367 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007368 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007369 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007370 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007371 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007372 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007373
Douglas Gregor86d142a2009-10-08 07:24:58 +00007374 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007375 // the original declaration to note that it is an explicit specialization
7376 // (if it was previously an implicit instantiation). This latter step
7377 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007378 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007379 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7380 if (InstantiationFunction->getTemplateSpecializationKind() ==
7381 TSK_ImplicitInstantiation) {
7382 InstantiationFunction->setTemplateSpecializationKind(
7383 TSK_ExplicitSpecialization);
7384 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007385 // Explicit specializations of member functions of class templates do not
7386 // inherit '=delete' from the member function they are specializing.
7387 if (InstantiationFunction->isDeleted()) {
7388 assert(InstantiationFunction->getCanonicalDecl() ==
7389 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007390 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007391 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007393
Douglas Gregor86d142a2009-10-08 07:24:58 +00007394 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7395 cast<CXXMethodDecl>(InstantiatedFrom),
7396 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007397 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007398 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007399 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7400 if (InstantiationVar->getTemplateSpecializationKind() ==
7401 TSK_ImplicitInstantiation) {
7402 InstantiationVar->setTemplateSpecializationKind(
7403 TSK_ExplicitSpecialization);
7404 InstantiationVar->setLocation(Member->getLocation());
7405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007406
Larisse Voufo39a1e502013-08-06 01:03:05 +00007407 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7408 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007409 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007410 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007411 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7412 if (InstantiationClass->getTemplateSpecializationKind() ==
7413 TSK_ImplicitInstantiation) {
7414 InstantiationClass->setTemplateSpecializationKind(
7415 TSK_ExplicitSpecialization);
7416 InstantiationClass->setLocation(Member->getLocation());
7417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007418
Douglas Gregor86d142a2009-10-08 07:24:58 +00007419 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007420 cast<CXXRecordDecl>(InstantiatedFrom),
7421 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007422 } else {
7423 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7424 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7425 if (InstantiationEnum->getTemplateSpecializationKind() ==
7426 TSK_ImplicitInstantiation) {
7427 InstantiationEnum->setTemplateSpecializationKind(
7428 TSK_ExplicitSpecialization);
7429 InstantiationEnum->setLocation(Member->getLocation());
7430 }
7431
7432 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7433 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007435
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007436 // Save the caller the trouble of having to figure out which declaration
7437 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007438 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007439 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007440 return false;
7441}
7442
Douglas Gregore47f5a72009-10-14 23:41:34 +00007443/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007444///
7445/// \returns true if a serious error occurs, false otherwise.
7446static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007447 SourceLocation InstLoc,
7448 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007449 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7450 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007451
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007452 if (CurContext->isRecord()) {
7453 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7454 << D;
7455 return true;
7456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007457
Richard Smith050d2612011-10-18 02:28:33 +00007458 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007459 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007460 // template. If the name declared in the explicit instantiation is an
7461 // unqualified name, the explicit instantiation shall appear in the
7462 // namespace where its template is declared or, if that namespace is inline
7463 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007464 //
7465 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007466 if (WasQualifiedName) {
7467 if (CurContext->Encloses(OrigContext))
7468 return false;
7469 } else {
7470 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7471 return false;
7472 }
7473
7474 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7475 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007476 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007477 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007478 diag::err_explicit_instantiation_out_of_scope :
7479 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007480 << D << NS;
7481 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007482 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007483 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007484 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7485 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7486 << D << NS;
7487 } else
7488 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007489 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007490 diag::err_explicit_instantiation_must_be_global :
7491 diag::warn_explicit_instantiation_must_be_global_0x)
7492 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007493 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007494 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007495}
7496
7497/// \brief Determine whether the given scope specifier has a template-id in it.
7498static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7499 if (!SS.isSet())
7500 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007501
Richard Smith050d2612011-10-18 02:28:33 +00007502 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007503 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007504 // or a static data member of a class template specialization, the name of
7505 // the class template specialization in the qualified-id for the member
7506 // name shall be a simple-template-id.
7507 //
7508 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007509 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7510 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007511 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007512 if (isa<TemplateSpecializationType>(T))
7513 return true;
7514
7515 return false;
7516}
7517
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007518/// Make a dllexport or dllimport attr on a class template specialization take
7519/// effect.
7520static void dllExportImportClassTemplateSpecialization(
7521 Sema &S, ClassTemplateSpecializationDecl *Def) {
7522 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
7523 assert(A && "dllExportImportClassTemplateSpecialization called "
7524 "on Def without dllexport or dllimport");
7525
7526 // We reject explicit instantiations in class scope, so there should
7527 // never be any delayed exported classes to worry about.
7528 assert(S.DelayedDllExportClasses.empty() &&
7529 "delayed exports present at explicit instantiation");
7530 S.checkClassLevelDLLAttribute(Def);
7531
7532 // Propagate attribute to base class templates.
7533 for (auto &B : Def->bases()) {
7534 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7535 B.getType()->getAsCXXRecordDecl()))
7536 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7537 }
7538
7539 S.referenceDLLExportedClassMethods();
7540}
7541
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007542// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007543DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007544Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007545 SourceLocation ExternLoc,
7546 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007547 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007548 SourceLocation KWLoc,
7549 const CXXScopeSpec &SS,
7550 TemplateTy TemplateD,
7551 SourceLocation TemplateNameLoc,
7552 SourceLocation LAngleLoc,
7553 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007554 SourceLocation RAngleLoc,
7555 AttributeList *Attr) {
7556 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007557 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007558 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007559 // Check that the specialization uses the same tag kind as the
7560 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007561 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7562 assert(Kind != TTK_Enum &&
7563 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007564
Richard Trieu265c3442016-04-05 21:13:54 +00007565 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7566
7567 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00007568 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
7569 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00007570 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007571 return true;
7572 }
7573
Douglas Gregord9034f02009-05-14 16:41:31 +00007574 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007575 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007576 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007577 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007578 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007579 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007580 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007581 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007582 diag::note_previous_use);
7583 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7584 }
7585
Douglas Gregore47f5a72009-10-14 23:41:34 +00007586 // C++0x [temp.explicit]p2:
7587 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007588 // definition and an explicit instantiation declaration. An explicit
7589 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007590 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7591 ? TSK_ExplicitInstantiationDefinition
7592 : TSK_ExplicitInstantiationDeclaration;
7593
7594 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7595 // Check for dllexport class template instantiation declarations.
7596 for (AttributeList *A = Attr; A; A = A->getNext()) {
7597 if (A->getKind() == AttributeList::AT_DLLExport) {
7598 Diag(ExternLoc,
7599 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7600 Diag(A->getLoc(), diag::note_attribute);
7601 break;
7602 }
7603 }
7604
7605 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7606 Diag(ExternLoc,
7607 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7608 Diag(A->getLocation(), diag::note_attribute);
7609 }
7610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007611
Hans Wennborga86a83b2016-05-26 19:42:56 +00007612 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7613 // instantiation declarations for most purposes.
7614 bool DLLImportExplicitInstantiationDef = false;
7615 if (TSK == TSK_ExplicitInstantiationDefinition &&
7616 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7617 // Check for dllimport class template instantiation definitions.
7618 bool DLLImport =
7619 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7620 for (AttributeList *A = Attr; A; A = A->getNext()) {
7621 if (A->getKind() == AttributeList::AT_DLLImport)
7622 DLLImport = true;
7623 if (A->getKind() == AttributeList::AT_DLLExport) {
7624 // dllexport trumps dllimport here.
7625 DLLImport = false;
7626 break;
7627 }
7628 }
7629 if (DLLImport) {
7630 TSK = TSK_ExplicitInstantiationDeclaration;
7631 DLLImportExplicitInstantiationDef = true;
7632 }
7633 }
7634
Douglas Gregora1f49972009-05-13 00:25:59 +00007635 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007636 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007637 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007638
7639 // Check that the template argument list is well-formed for this
7640 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007641 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007642 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7643 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007644 return true;
7645
Douglas Gregora1f49972009-05-13 00:25:59 +00007646 // Find the class template specialization declaration that
7647 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007648 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007649 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007650 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007651
Abramo Bagnara8075c852010-06-12 07:44:57 +00007652 TemplateSpecializationKind PrevDecl_TSK
7653 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7654
Douglas Gregor54888652009-10-07 00:13:32 +00007655 // C++0x [temp.explicit]p2:
7656 // [...] An explicit instantiation shall appear in an enclosing
7657 // namespace of its template. [...]
7658 //
7659 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007660 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7661 SS.isSet()))
7662 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007663
Craig Topperc3ec1492014-05-26 06:22:03 +00007664 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007665
Abramo Bagnara8075c852010-06-12 07:44:57 +00007666 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007667 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007668 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007669 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007670 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007671 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007672 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007673
Abramo Bagnara8075c852010-06-12 07:44:57 +00007674 // Even though HasNoEffect == true means that this explicit instantiation
7675 // has no effect on semantics, we go on to put its syntax in the AST.
7676
7677 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7678 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007679 // Since the only prior class template specialization with these
7680 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007681 // declaration node as our own, updating the source location
7682 // for the template name to reflect our new declaration.
7683 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007684 Specialization = PrevDecl;
7685 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007686 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007687 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007688
7689 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7690 DLLImportExplicitInstantiationDef) {
7691 // The new specialization might add a dllimport attribute.
7692 HasNoEffect = false;
7693 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007694 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007695
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007696 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007697 // Create a new class template specialization declaration node for
7698 // this explicit specialization.
7699 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007700 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007701 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007702 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007703 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007704 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007705 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007706 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007707
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007708 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007709 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007710 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007711 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007712 }
7713
7714 // Build the fully-sugared type for this explicit instantiation as
7715 // the user wrote in the explicit instantiation itself. This means
7716 // that we'll pretty-print the type retrieved from the
7717 // specialization's declaration the way that the user actually wrote
7718 // the explicit instantiation, rather than formatting the name based
7719 // on the "canonical" representation used to store the template
7720 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007721 TypeSourceInfo *WrittenTy
7722 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7723 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007724 Context.getTypeDeclType(Specialization));
7725 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007726
Abramo Bagnara8075c852010-06-12 07:44:57 +00007727 // Set source locations for keywords.
7728 Specialization->setExternLoc(ExternLoc);
7729 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007730 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007731
Rafael Espindola0b062072012-01-03 06:04:21 +00007732 if (Attr)
7733 ProcessDeclAttributeList(S, Specialization, Attr);
7734
Abramo Bagnara8075c852010-06-12 07:44:57 +00007735 // Add the explicit instantiation into its lexical context. However,
7736 // since explicit instantiations are never found by name lookup, we
7737 // just put it into the declaration context directly.
7738 Specialization->setLexicalDeclContext(CurContext);
7739 CurContext->addDecl(Specialization);
7740
7741 // Syntax is now OK, so return if it has no other effect on semantics.
7742 if (HasNoEffect) {
7743 // Set the template specialization kind.
7744 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007745 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007746 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007747
7748 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007749 // A definition of a class template or class member template
7750 // shall be in scope at the point of the explicit instantiation of
7751 // the class template or class member template.
7752 //
7753 // This check comes when we actually try to perform the
7754 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007755 ClassTemplateSpecializationDecl *Def
7756 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007757 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007758 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007759 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007760 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007761 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007762 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7763 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007764
Douglas Gregor1d957a32009-10-27 18:42:08 +00007765 // Instantiate the members of this class template specialization.
7766 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007767 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007768 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007769 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007770 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7771 // TSK_ExplicitInstantiationDefinition
7772 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007773 (TSK == TSK_ExplicitInstantiationDefinition ||
7774 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007775 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007776 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007777
Hans Wennborgc0875502015-06-09 00:39:05 +00007778 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00007779 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7780 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00007781 // In the MS ABI, an explicit instantiation definition can add a dll
7782 // attribute to a template with a previous instantiation declaration.
7783 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007784 auto *A = cast<InheritableAttr>(
7785 getDLLAttr(Specialization)->clone(getASTContext()));
7786 A->setInherited(true);
7787 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007788 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00007789 }
7790 }
7791
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007792 // Fix a TSK_ImplicitInstantiation followed by a
7793 // TSK_ExplicitInstantiationDefinition
7794 if (Old_TSK == TSK_ImplicitInstantiation &&
7795 Specialization->hasAttr<DLLExportAttr>() &&
7796 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7797 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
7798 // In the MS ABI, an explicit instantiation definition can add a dll
7799 // attribute to a template with a previous implicit instantiation.
7800 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
7801 // avoid potentially strange codegen behavior. For example, if we extend
7802 // this conditional to dllimport, and we have a source file calling a
7803 // method on an implicitly instantiated template class instance and then
7804 // declaring a dllimport explicit instantiation definition for the same
7805 // template class, the codegen for the method call will not respect the
7806 // dllimport, while it will with cl. The Def will already have the DLL
7807 // attribute, since the Def and Specialization will be the same in the
7808 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
7809 // attribute to the Specialization; we just need to make it take effect.
7810 assert(Def == Specialization &&
7811 "Def and Specialization should match for implicit instantiation");
7812 dllExportImportClassTemplateSpecialization(*this, Def);
7813 }
7814
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007815 // Set the template specialization kind. Make sure it is set before
7816 // instantiating the members which will trigger ASTConsumer callbacks.
7817 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007818 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007819 } else {
7820
7821 // Set the template specialization kind.
7822 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007823 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007824
John McCall48871652010-08-21 09:40:31 +00007825 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007826}
7827
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007828// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007829DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007830Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007831 SourceLocation ExternLoc,
7832 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007833 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007834 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007835 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007836 IdentifierInfo *Name,
7837 SourceLocation NameLoc,
7838 AttributeList *Attr) {
7839
Douglas Gregord6ab8742009-05-28 23:31:59 +00007840 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007841 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007842 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007843 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007844 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007845 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007846 SourceLocation(), false, TypeResult(),
7847 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007848 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7849
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007850 if (!TagD)
7851 return true;
7852
John McCall48871652010-08-21 09:40:31 +00007853 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007854 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007855
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007856 if (Tag->isInvalidDecl())
7857 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007858
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007859 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7860 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7861 if (!Pattern) {
7862 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7863 << Context.getTypeDeclType(Record);
7864 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7865 return true;
7866 }
7867
Douglas Gregore47f5a72009-10-14 23:41:34 +00007868 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007869 // If the explicit instantiation is for a class or member class, the
7870 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007871 // simple-template-id.
7872 //
7873 // C++98 has the same restriction, just worded differently.
7874 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007875 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007876 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007877
Douglas Gregore47f5a72009-10-14 23:41:34 +00007878 // C++0x [temp.explicit]p2:
7879 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007880 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007881 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007882 TemplateSpecializationKind TSK
7883 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7884 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007885
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007886 // C++0x [temp.explicit]p2:
7887 // [...] An explicit instantiation shall appear in an enclosing
7888 // namespace of its template. [...]
7889 //
7890 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007891 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007893 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007894 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007895 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007896 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007897 PrevDecl = Record;
7898 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007899 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007900 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007901 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007903 PrevDecl,
7904 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007905 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007906 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007907 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007908 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007909 return TagD;
7910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911
Douglas Gregor12e49d32009-10-15 22:53:21 +00007912 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007913 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007914 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007915 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007916 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007917 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007918 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007919 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007920 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007921 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7922 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007923 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7924 << Pattern;
7925 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007926 } else {
7927 if (InstantiateClass(NameLoc, Record, Def,
7928 getTemplateInstantiationArgs(Record),
7929 TSK))
7930 return true;
7931
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007932 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007933 if (!RecordDef)
7934 return true;
7935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007936 }
7937
Douglas Gregor1d957a32009-10-27 18:42:08 +00007938 // Instantiate all of the members of the class.
7939 InstantiateClassMembers(NameLoc, RecordDef,
7940 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007941
Douglas Gregor88d292c2010-05-13 16:44:06 +00007942 if (TSK == TSK_ExplicitInstantiationDefinition)
7943 MarkVTableUsed(NameLoc, RecordDef, true);
7944
Mike Stump87c57ac2009-05-16 07:39:55 +00007945 // FIXME: We don't have any representation for explicit instantiations of
7946 // member classes. Such a representation is not needed for compilation, but it
7947 // should be available for clients that want to see all of the declarations in
7948 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007949 return TagD;
7950}
7951
John McCallfaf5fb42010-08-26 23:41:50 +00007952DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7953 SourceLocation ExternLoc,
7954 SourceLocation TemplateLoc,
7955 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007956 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007957 // TODO: check if/when DNInfo should replace Name.
7958 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7959 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007960 if (!Name) {
7961 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007962 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007963 diag::err_explicit_instantiation_requires_name)
7964 << D.getDeclSpec().getSourceRange()
7965 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007966
Douglas Gregor450f00842009-09-25 18:43:00 +00007967 return true;
7968 }
7969
7970 // The scope passed in may not be a decl scope. Zip up the scope tree until
7971 // we find one that is.
7972 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7973 (S->getFlags() & Scope::TemplateParamScope) != 0)
7974 S = S->getParent();
7975
7976 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007977 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7978 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007979 if (R.isNull())
7980 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007981
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007982 // C++ [dcl.stc]p1:
7983 // A storage-class-specifier shall not be specified in [...] an explicit
7984 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007985 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007986 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7987 << Name;
7988 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007989 } else if (D.getDeclSpec().getStorageClassSpec()
7990 != DeclSpec::SCS_unspecified) {
7991 // Complain about then remove the storage class specifier.
7992 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7993 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7994
7995 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007996 }
7997
Douglas Gregor3c74d412009-10-14 20:14:33 +00007998 // C++0x [temp.explicit]p1:
7999 // [...] An explicit instantiation of a function template shall not use the
8000 // inline or constexpr specifiers.
8001 // Presumably, this also applies to member functions of class templates as
8002 // well.
Richard Smith83c19292011-10-18 03:44:03 +00008003 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008004 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008005 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00008006 diag::err_explicit_instantiation_inline :
8007 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00008008 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00008009 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00008010 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8011 // not already specified.
8012 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8013 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008014
Nathan Wilsonde498452016-02-08 05:34:00 +00008015 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8016 // applied only to the definition of a function template or variable template,
8017 // declared in namespace scope.
8018 if (D.getDeclSpec().isConceptSpecified()) {
8019 Diag(D.getDeclSpec().getConceptSpecLoc(),
8020 diag::err_concept_specified_specialization) << 0;
8021 return true;
8022 }
8023
Douglas Gregore47f5a72009-10-14 23:41:34 +00008024 // C++0x [temp.explicit]p2:
8025 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008026 // definition and an explicit instantiation declaration. An explicit
8027 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00008028 TemplateSpecializationKind TSK
8029 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8030 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008031
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008032 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00008033 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00008034
8035 if (!R->isFunctionType()) {
8036 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037 // A [...] static data member of a class template can be explicitly
8038 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008039 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008040 // C++1y [temp.explicit]p1:
8041 // A [...] variable [...] template specialization can be explicitly
8042 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00008043 if (Previous.isAmbiguous())
8044 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008045
John McCall67c00872009-12-02 08:25:40 +00008046 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00008047 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008048
Larisse Voufo39a1e502013-08-06 01:03:05 +00008049 if (!PrevTemplate) {
8050 if (!Prev || !Prev->isStaticDataMember()) {
8051 // We expect to see a data data member here.
8052 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8053 << Name;
8054 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8055 P != PEnd; ++P)
8056 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8057 return true;
8058 }
8059
8060 if (!Prev->getInstantiatedFromStaticDataMember()) {
8061 // FIXME: Check for explicit specialization?
8062 Diag(D.getIdentifierLoc(),
8063 diag::err_explicit_instantiation_data_member_not_instantiated)
8064 << Prev;
8065 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8066 // FIXME: Can we provide a note showing where this was declared?
8067 return true;
8068 }
8069 } else {
8070 // Explicitly instantiate a variable template.
8071
8072 // C++1y [dcl.spec.auto]p6:
8073 // ... A program that uses auto or decltype(auto) in a context not
8074 // explicitly allowed in this section is ill-formed.
8075 //
8076 // This includes auto-typed variable template instantiations.
8077 if (R->isUndeducedType()) {
8078 Diag(T->getTypeLoc().getLocStart(),
8079 diag::err_auto_not_allowed_var_inst);
8080 return true;
8081 }
8082
Richard Smithef985ac2013-09-18 02:10:12 +00008083 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8084 // C++1y [temp.explicit]p3:
8085 // If the explicit instantiation is for a variable, the unqualified-id
8086 // in the declaration shall be a template-id.
8087 Diag(D.getIdentifierLoc(),
8088 diag::err_explicit_instantiation_without_template_id)
8089 << PrevTemplate;
8090 Diag(PrevTemplate->getLocation(),
8091 diag::note_explicit_instantiation_here);
8092 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008093 }
8094
Nathan Wilson83839122016-04-09 02:55:27 +00008095 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8096 // explicit instantiation (14.8.2) [...] of a concept definition.
8097 if (PrevTemplate->isConcept()) {
8098 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8099 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8100 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8101 return true;
8102 }
8103
Richard Smithef985ac2013-09-18 02:10:12 +00008104 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008105 TemplateArgumentListInfo TemplateArgs =
8106 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008107
Larisse Voufo39a1e502013-08-06 01:03:05 +00008108 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8109 D.getIdentifierLoc(), TemplateArgs);
8110 if (Res.isInvalid())
8111 return true;
8112
8113 // Ignore access control bits, we don't need them for redeclaration
8114 // checking.
8115 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008117
Douglas Gregore47f5a72009-10-14 23:41:34 +00008118 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008120 // or a static data member of a class template specialization, the name of
8121 // the class template specialization in the qualified-id for the member
8122 // name shall be a simple-template-id.
8123 //
8124 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008125 //
Richard Smith5977d872013-09-18 21:55:14 +00008126 // This does not apply to variable template specializations, where the
8127 // template-id is in the unqualified-id instead.
8128 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008129 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008130 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008131 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132
Douglas Gregore47f5a72009-10-14 23:41:34 +00008133 // Check the scope of this explicit instantiation.
8134 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008135
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008136 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008137 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8138 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008139 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008140 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008141 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008142 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008143
Larisse Voufo39a1e502013-08-06 01:03:05 +00008144 if (!HasNoEffect) {
8145 // Instantiate static data member or variable template.
8146
8147 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8148 if (PrevTemplate) {
8149 // Merge attributes.
8150 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8151 ProcessDeclAttributeList(S, Prev, Attr);
8152 }
8153 if (TSK == TSK_ExplicitInstantiationDefinition)
8154 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8155 }
8156
8157 // Check the new variable specialization against the parsed input.
8158 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8159 Diag(T->getTypeLoc().getLocStart(),
8160 diag::err_invalid_var_template_spec_type)
8161 << 0 << PrevTemplate << R << Prev->getType();
8162 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8163 << 2 << PrevTemplate->getDeclName();
8164 return true;
8165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008166
Douglas Gregor450f00842009-09-25 18:43:00 +00008167 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008168 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008170
8171 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008172 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008173 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008174 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008175 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008176 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008177 HasExplicitTemplateArgs = true;
8178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008179
Douglas Gregor450f00842009-09-25 18:43:00 +00008180 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008181 // A [...] function [...] can be explicitly instantiated from its template.
8182 // A member function [...] of a class template can be explicitly
8183 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008184 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008185 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008186 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008187 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008188 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8189 P != PEnd; ++P) {
8190 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008191 if (!HasExplicitTemplateArgs) {
8192 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008193 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8194 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008195 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008196 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008197
John McCall58cc69d2010-01-27 01:50:18 +00008198 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008199 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8200 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008201 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008202 }
8203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008204
Douglas Gregor450f00842009-09-25 18:43:00 +00008205 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8206 if (!FunTmpl)
8207 continue;
8208
Larisse Voufo98b20f12013-07-19 23:00:19 +00008209 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008210 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008211 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008212 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008213 (HasExplicitTemplateArgs ? &TemplateArgs
8214 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008215 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008216 // Keep track of almost-matches.
8217 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008218 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008219 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008220 (void)TDK;
8221 continue;
8222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008223
Artem Belevich64135c32016-12-08 19:38:13 +00008224 // Target attributes are part of the cuda function signature, so
8225 // the cuda target of the instantiated function must match that of its
8226 // template. Given that C++ template deduction does not take
8227 // target attributes into account, we reject candidates here that
8228 // have a different target.
8229 if (LangOpts.CUDA &&
8230 IdentifyCUDATarget(Specialization,
8231 /* IgnoreImplicitHDAttributes = */ true) !=
8232 IdentifyCUDATarget(Attr)) {
8233 FailedCandidates.addCandidate().set(
8234 P.getPair(), FunTmpl->getTemplatedDecl(),
8235 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8236 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008237 }
8238
John McCall58cc69d2010-01-27 01:50:18 +00008239 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008241
Douglas Gregor450f00842009-09-25 18:43:00 +00008242 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008243 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008244 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008245 D.getIdentifierLoc(),
8246 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8247 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8248 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008249
John McCall58cc69d2010-01-27 01:50:18 +00008250 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008251 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008252
8253 // Ignore access control bits, we don't need them for redeclaration checking.
8254 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008255
Alexey Bataev73983912014-11-06 10:10:50 +00008256 // C++11 [except.spec]p4
8257 // In an explicit instantiation an exception-specification may be specified,
8258 // but is not required.
8259 // If an exception-specification is specified in an explicit instantiation
8260 // directive, it shall be compatible with the exception-specifications of
8261 // other declarations of that function.
8262 if (auto *FPT = R->getAs<FunctionProtoType>())
8263 if (FPT->hasExceptionSpec()) {
8264 unsigned DiagID =
8265 diag::err_mismatched_exception_spec_explicit_instantiation;
8266 if (getLangOpts().MicrosoftExt)
8267 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8268 bool Result = CheckEquivalentExceptionSpec(
8269 PDiag(DiagID) << Specialization->getType(),
8270 PDiag(diag::note_explicit_instantiation_here),
8271 Specialization->getType()->getAs<FunctionProtoType>(),
8272 Specialization->getLocation(), FPT, D.getLocStart());
8273 // In Microsoft mode, mismatching exception specifications just cause a
8274 // warning.
8275 if (!getLangOpts().MicrosoftExt && Result)
8276 return true;
8277 }
8278
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008279 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008280 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008281 diag::err_explicit_instantiation_member_function_not_instantiated)
8282 << Specialization
8283 << (Specialization->getTemplateSpecializationKind() ==
8284 TSK_ExplicitSpecialization);
8285 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8286 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008287 }
8288
Douglas Gregorec9fd132012-01-14 16:38:05 +00008289 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008290 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8291 PrevDecl = Specialization;
8292
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008293 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008294 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008295 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008296 PrevDecl,
8297 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008298 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008299 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008300 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008301
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008302 // FIXME: We may still want to build some representation of this
8303 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008304 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008305 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008306 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008307
8308 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008309 if (Attr)
8310 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008311
Richard Smitheb36ddf2014-04-24 22:45:46 +00008312 if (Specialization->isDefined()) {
8313 // Let the ASTConsumer know that this function has been explicitly
8314 // instantiated now, and its linkage might have changed.
8315 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8316 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008317 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008318
Douglas Gregore47f5a72009-10-14 23:41:34 +00008319 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008320 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008321 // or a static data member of a class template specialization, the name of
8322 // the class template specialization in the qualified-id for the member
8323 // name shall be a simple-template-id.
8324 //
8325 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008326 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008327 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008328 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008329 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008330 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008331 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008332 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008333
Nathan Wilson83839122016-04-09 02:55:27 +00008334 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8335 // explicit instantiation (14.8.2) [...] of a concept definition.
8336 if (FunTmpl && FunTmpl->isConcept() &&
8337 !D.getDeclSpec().isConceptSpecified()) {
8338 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8339 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8340 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8341 return true;
8342 }
8343
Douglas Gregore47f5a72009-10-14 23:41:34 +00008344 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008345 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008346 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008347 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008348 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008349
Douglas Gregor450f00842009-09-25 18:43:00 +00008350 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008351 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008352}
8353
John McCallfaf5fb42010-08-26 23:41:50 +00008354TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008355Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8356 const CXXScopeSpec &SS, IdentifierInfo *Name,
8357 SourceLocation TagLoc, SourceLocation NameLoc) {
8358 // This has to hold, because SS is expected to be defined.
8359 assert(Name && "Expected a name in a dependent tag");
8360
Aaron Ballman4a979672014-01-03 13:56:08 +00008361 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008362 if (!NNS)
8363 return true;
8364
Abramo Bagnara6150c882010-05-11 21:36:43 +00008365 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008366
Douglas Gregorba41d012010-04-24 16:38:41 +00008367 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8368 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008369 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008370 return true;
8371 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008372
Douglas Gregore7c20652011-03-02 00:47:37 +00008373 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008374 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008375 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8376
8377 // Create type-source location information for this type.
8378 TypeLocBuilder TLB;
8379 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008380 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008381 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8382 TL.setNameLoc(NameLoc);
8383 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008384}
8385
John McCallfaf5fb42010-08-26 23:41:50 +00008386TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008387Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8388 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008389 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008390 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008391 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008392
Richard Smith0bf8a4922011-10-18 20:49:44 +00008393 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8394 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008395 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008396 diag::warn_cxx98_compat_typename_outside_of_template :
8397 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008398 << FixItHint::CreateRemoval(TypenameLoc);
8399
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008400 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008401 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8402 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008403 if (T.isNull())
8404 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008405
8406 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8407 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008408 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008409 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008410 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008411 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008412 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008413 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008414 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008415 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008416 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008418
John McCallba7bf592010-08-24 05:47:05 +00008419 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008420}
8421
John McCallfaf5fb42010-08-26 23:41:50 +00008422TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008423Sema::ActOnTypenameType(Scope *S,
8424 SourceLocation TypenameLoc,
8425 const CXXScopeSpec &SS,
8426 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008427 TemplateTy TemplateIn,
8428 SourceLocation TemplateNameLoc,
8429 SourceLocation LAngleLoc,
8430 ASTTemplateArgsPtr TemplateArgsIn,
8431 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008432 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8433 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008434 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008435 diag::warn_cxx98_compat_typename_outside_of_template :
8436 diag::ext_typename_outside_of_template)
8437 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008438
8439 // Translate the parser's template argument list in our AST format.
8440 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8441 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8442
8443 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008444 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8445 // Construct a dependent template specialization type.
8446 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008447 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008448 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8449 DTN->getQualifier(),
8450 DTN->getIdentifier(),
8451 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008452
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008453 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008454 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008455 DependentTemplateSpecializationTypeLoc SpecTL
8456 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008457 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8458 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008459 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008460 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008461 SpecTL.setLAngleLoc(LAngleLoc);
8462 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008463 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8464 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008465 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008466 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008467
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008468 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8469 if (T.isNull())
8470 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008471
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008472 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008473 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008474 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008475 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008476 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8477 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008478 SpecTL.setLAngleLoc(LAngleLoc);
8479 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008480 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8481 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8482
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008483 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8484 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008485 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008486 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8487
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008488 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8489 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008490}
8491
Douglas Gregorb09518c2011-02-27 22:46:49 +00008492
Richard Smith6f8d2c62012-05-09 05:17:00 +00008493/// Determine whether this failed name lookup should be treated as being
8494/// disabled by a usage of std::enable_if.
8495static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8496 SourceRange &CondRange) {
8497 // We must be looking for a ::type...
8498 if (!II.isStr("type"))
8499 return false;
8500
8501 // ... within an explicitly-written template specialization...
8502 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8503 return false;
8504 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008505 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8506 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8507 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008508 return false;
8509 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008510 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008511
8512 // ... which names a complete class template declaration...
8513 const TemplateDecl *EnableIfDecl =
8514 EnableIfTST->getTemplateName().getAsTemplateDecl();
8515 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8516 return false;
8517
8518 // ... called "enable_if".
8519 const IdentifierInfo *EnableIfII =
8520 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8521 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8522 return false;
8523
8524 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008525 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008526 return true;
8527}
8528
Douglas Gregor333489b2009-03-27 23:10:48 +00008529/// \brief Build the type that describes a C++ typename specifier,
8530/// e.g., "typename T::type".
8531QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008532Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8533 SourceLocation KeywordLoc,
8534 NestedNameSpecifierLoc QualifierLoc,
8535 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008536 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008537 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008538 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008539
John McCall0b66eb32010-05-01 00:40:08 +00008540 DeclContext *Ctx = computeDeclContext(SS);
8541 if (!Ctx) {
8542 // If the nested-name-specifier is dependent and couldn't be
8543 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008544 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8545 return Context.getDependentNameType(Keyword,
8546 QualifierLoc.getNestedNameSpecifier(),
8547 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008548 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008549
John McCall0b66eb32010-05-01 00:40:08 +00008550 // If the nested-name-specifier refers to the current instantiation,
8551 // the "typename" keyword itself is superfluous. In C++03, the
8552 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8553 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008554 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008555
John McCall0b66eb32010-05-01 00:40:08 +00008556 if (RequireCompleteDeclContext(SS, Ctx))
8557 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008558
8559 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008560 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008561 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008562 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008563 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008564 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008565 case LookupResult::NotFound: {
8566 // If we're looking up 'type' within a template named 'enable_if', produce
8567 // a more specific diagnostic.
8568 SourceRange CondRange;
8569 if (isEnableIf(QualifierLoc, II, CondRange)) {
8570 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8571 << Ctx << CondRange;
8572 return QualType();
8573 }
8574
Douglas Gregore40876a2009-10-13 21:16:44 +00008575 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008576 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008577 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008578
8579 case LookupResult::FoundUnresolvedValue: {
8580 // We found a using declaration that is a value. Most likely, the using
8581 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008582 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008583 IILoc);
8584 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8585 << Name << Ctx << FullRange;
8586 if (UnresolvedUsingValueDecl *Using
8587 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008588 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008589 Diag(Loc, diag::note_using_value_decl_missing_typename)
8590 << FixItHint::CreateInsertion(Loc, "typename ");
8591 }
8592 }
8593 // Fall through to create a dependent typename type, from which we can recover
8594 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008595
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008596 case LookupResult::NotFoundInCurrentInstantiation:
8597 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008598 return Context.getDependentNameType(Keyword,
8599 QualifierLoc.getNestedNameSpecifier(),
8600 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008601
8602 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008603 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008604 // We found a type. Build an ElaboratedType, since the
8605 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008606 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008607 return Context.getElaboratedType(ETK_Typename,
8608 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008609 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008610 }
8611
8612 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008613 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008614 break;
8615
8616 case LookupResult::FoundOverloaded:
8617 DiagID = diag::err_typename_nested_not_type;
8618 Referenced = *Result.begin();
8619 break;
8620
John McCall6538c932009-10-10 05:48:19 +00008621 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008622 return QualType();
8623 }
8624
8625 // If we get here, it's because name lookup did not find a
8626 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008627 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008628 IILoc);
8629 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008630 if (Referenced)
8631 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8632 << Name;
8633 return QualType();
8634}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008635
8636namespace {
8637 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008638 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008639 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008640 SourceLocation Loc;
8641 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008642
Douglas Gregor15acfb92009-08-06 16:20:37 +00008643 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008644 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008645
Mike Stump11289f42009-09-09 15:08:12 +00008646 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008647 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008648 DeclarationName Entity)
8649 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008650 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008651
8652 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008653 /// transformed.
8654 ///
8655 /// For the purposes of type reconstruction, a type has already been
8656 /// transformed if it is NULL or if it is not dependent.
8657 bool AlreadyTransformed(QualType T) {
8658 return T.isNull() || !T->isDependentType();
8659 }
Mike Stump11289f42009-09-09 15:08:12 +00008660
8661 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008662 /// rebuilt.
8663 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008664
Douglas Gregor15acfb92009-08-06 16:20:37 +00008665 /// \brief Returns the name of the entity whose type is being rebuilt.
8666 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008667
Douglas Gregoref6ab412009-10-27 06:26:26 +00008668 /// \brief Sets the "base" location and entity when that
8669 /// information is known based on another transformation.
8670 void setBase(SourceLocation Loc, DeclarationName Entity) {
8671 this->Loc = Loc;
8672 this->Entity = Entity;
8673 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008674
8675 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8676 // Lambdas never need to be transformed.
8677 return E;
8678 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008679 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008680} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008681
Douglas Gregor15acfb92009-08-06 16:20:37 +00008682/// \brief Rebuilds a type within the context of the current instantiation.
8683///
Mike Stump11289f42009-09-09 15:08:12 +00008684/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008685/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008686/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008687/// partial specialization thereof). This routine will rebuild that type now
8688/// that we have entered the declarator's scope, which may produce different
8689/// canonical types, e.g.,
8690///
8691/// \code
8692/// template<typename T>
8693/// struct X {
8694/// typedef T* pointer;
8695/// pointer data();
8696/// };
8697///
8698/// template<typename T>
8699/// typename X<T>::pointer X<T>::data() { ... }
8700/// \endcode
8701///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008702/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008703/// since we do not know that we can look into X<T> when we parsed the type.
8704/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008705/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008706/// as the canonical type of T*, allowing the return types of the out-of-line
8707/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008708TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8709 SourceLocation Loc,
8710 DeclarationName Name) {
8711 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008712 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008713
Douglas Gregor15acfb92009-08-06 16:20:37 +00008714 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8715 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008716}
Douglas Gregorbe999392009-09-15 16:23:51 +00008717
John McCalldadc5752010-08-24 06:29:42 +00008718ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008719 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8720 DeclarationName());
8721 return Rebuilder.TransformExpr(E);
8722}
8723
John McCall99b2fe52010-04-29 23:50:39 +00008724bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008725 if (SS.isInvalid())
8726 return true;
John McCall2408e322010-04-27 00:57:59 +00008727
Douglas Gregor10176412011-02-25 16:07:42 +00008728 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008729 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8730 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008731 NestedNameSpecifierLoc Rebuilt
8732 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8733 if (!Rebuilt)
8734 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008735
Douglas Gregor10176412011-02-25 16:07:42 +00008736 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008737 return false;
John McCall2408e322010-04-27 00:57:59 +00008738}
8739
Douglas Gregor041b0842011-10-14 15:31:12 +00008740/// \brief Rebuild the template parameters now that we know we're in a current
8741/// instantiation.
8742bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8743 TemplateParameterList *Params) {
8744 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8745 Decl *Param = Params->getParam(I);
8746
8747 // There is nothing to rebuild in a type parameter.
8748 if (isa<TemplateTypeParmDecl>(Param))
8749 continue;
8750
8751 // Rebuild the template parameter list of a template template parameter.
8752 if (TemplateTemplateParmDecl *TTP
8753 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8754 if (RebuildTemplateParamsInCurrentInstantiation(
8755 TTP->getTemplateParameters()))
8756 return true;
8757
8758 continue;
8759 }
8760
8761 // Rebuild the type of a non-type template parameter.
8762 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8763 TypeSourceInfo *NewTSI
8764 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8765 NTTP->getLocation(),
8766 NTTP->getDeclName());
8767 if (!NewTSI)
8768 return true;
8769
8770 if (NewTSI != NTTP->getTypeSourceInfo()) {
8771 NTTP->setTypeSourceInfo(NewTSI);
8772 NTTP->setType(NewTSI->getType());
8773 }
8774 }
8775
8776 return false;
8777}
8778
Douglas Gregorbe999392009-09-15 16:23:51 +00008779/// \brief Produces a formatted string that describes the binding of
8780/// template parameters to template arguments.
8781std::string
8782Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8783 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008784 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008785}
8786
8787std::string
8788Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8789 const TemplateArgument *Args,
8790 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008791 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008792 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008793
Douglas Gregore62e6a02009-11-11 19:13:48 +00008794 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008795 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796
Douglas Gregorbe999392009-09-15 16:23:51 +00008797 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008798 if (I >= NumArgs)
8799 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008800
Douglas Gregorbe999392009-09-15 16:23:51 +00008801 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008802 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008803 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008804 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008805
Douglas Gregorbe999392009-09-15 16:23:51 +00008806 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008807 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008808 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008809 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008811
Douglas Gregor0192c232010-12-20 16:52:59 +00008812 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008813 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008814 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008815
8816 Out << ']';
8817 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008818}
Francois Pichet1c229c02011-04-22 22:18:13 +00008819
Richard Smithe40f2ba2013-08-07 21:41:30 +00008820void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8821 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008822 if (!FD)
8823 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008824
Justin Lebar28f09c52016-10-10 16:26:08 +00008825 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008826
8827 // Take tokens to avoid allocations
8828 LPT->Toks.swap(Toks);
8829 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00008830 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008831
8832 FD->setLateTemplateParsed(true);
8833}
8834
8835void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8836 if (!FD)
8837 return;
8838 FD->setLateTemplateParsed(false);
8839}
Francois Pichet1c229c02011-04-22 22:18:13 +00008840
8841bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8842 DeclContext *DC = CurContext;
8843
8844 while (DC) {
8845 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8846 const FunctionDecl *FD = RD->isLocalClass();
8847 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8848 } else if (DC->isTranslationUnit() || DC->isNamespace())
8849 return false;
8850
8851 DC = DC->getParent();
8852 }
8853 return false;
8854}
Richard Smith6739a102016-05-05 00:56:12 +00008855
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008856namespace {
Richard Smith6739a102016-05-05 00:56:12 +00008857/// \brief Walk the path from which a declaration was instantiated, and check
8858/// that every explicit specialization along that path is visible. This enforces
8859/// C++ [temp.expl.spec]/6:
8860///
8861/// If a template, a member template or a member of a class template is
8862/// explicitly specialized then that specialization shall be declared before
8863/// the first use of that specialization that would cause an implicit
8864/// instantiation to take place, in every translation unit in which such a
8865/// use occurs; no diagnostic is required.
8866///
8867/// and also C++ [temp.class.spec]/1:
8868///
8869/// A partial specialization shall be declared before the first use of a
8870/// class template specialization that would make use of the partial
8871/// specialization as the result of an implicit or explicit instantiation
8872/// in every translation unit in which such a use occurs; no diagnostic is
8873/// required.
8874class ExplicitSpecializationVisibilityChecker {
8875 Sema &S;
8876 SourceLocation Loc;
8877 llvm::SmallVector<Module *, 8> Modules;
8878
8879public:
8880 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8881 : S(S), Loc(Loc) {}
8882
8883 void check(NamedDecl *ND) {
8884 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8885 return checkImpl(FD);
8886 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8887 return checkImpl(RD);
8888 if (auto *VD = dyn_cast<VarDecl>(ND))
8889 return checkImpl(VD);
8890 if (auto *ED = dyn_cast<EnumDecl>(ND))
8891 return checkImpl(ED);
8892 }
8893
8894private:
8895 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8896 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8897 : Sema::MissingImportKind::ExplicitSpecialization;
8898 const bool Recover = true;
8899
8900 // If we got a custom set of modules (because only a subset of the
8901 // declarations are interesting), use them, otherwise let
8902 // diagnoseMissingImport intelligently pick some.
8903 if (Modules.empty())
8904 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8905 else
8906 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8907 }
8908
8909 // Check a specific declaration. There are three problematic cases:
8910 //
8911 // 1) The declaration is an explicit specialization of a template
8912 // specialization.
8913 // 2) The declaration is an explicit specialization of a member of an
8914 // templated class.
8915 // 3) The declaration is an instantiation of a template, and that template
8916 // is an explicit specialization of a member of a templated class.
8917 //
8918 // We don't need to go any deeper than that, as the instantiation of the
8919 // surrounding class / etc is not triggered by whatever triggered this
8920 // instantiation, and thus should be checked elsewhere.
8921 template<typename SpecDecl>
8922 void checkImpl(SpecDecl *Spec) {
8923 bool IsHiddenExplicitSpecialization = false;
8924 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8925 IsHiddenExplicitSpecialization =
8926 Spec->getMemberSpecializationInfo()
8927 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8928 : !S.hasVisibleDeclaration(Spec);
8929 } else {
8930 checkInstantiated(Spec);
8931 }
8932
8933 if (IsHiddenExplicitSpecialization)
8934 diagnose(Spec->getMostRecentDecl(), false);
8935 }
8936
8937 void checkInstantiated(FunctionDecl *FD) {
8938 if (auto *TD = FD->getPrimaryTemplate())
8939 checkTemplate(TD);
8940 }
8941
8942 void checkInstantiated(CXXRecordDecl *RD) {
8943 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8944 if (!SD)
8945 return;
8946
8947 auto From = SD->getSpecializedTemplateOrPartial();
8948 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8949 checkTemplate(TD);
8950 else if (auto *TD =
8951 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8952 if (!S.hasVisibleDeclaration(TD))
8953 diagnose(TD, true);
8954 checkTemplate(TD);
8955 }
8956 }
8957
8958 void checkInstantiated(VarDecl *RD) {
8959 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8960 if (!SD)
8961 return;
8962
8963 auto From = SD->getSpecializedTemplateOrPartial();
8964 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8965 checkTemplate(TD);
8966 else if (auto *TD =
8967 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8968 if (!S.hasVisibleDeclaration(TD))
8969 diagnose(TD, true);
8970 checkTemplate(TD);
8971 }
8972 }
8973
8974 void checkInstantiated(EnumDecl *FD) {}
8975
8976 template<typename TemplDecl>
8977 void checkTemplate(TemplDecl *TD) {
8978 if (TD->isMemberSpecialization()) {
8979 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8980 diagnose(TD->getMostRecentDecl(), false);
8981 }
8982 }
8983};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008984} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00008985
8986void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8987 if (!getLangOpts().Modules)
8988 return;
8989
8990 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8991}
8992
8993/// \brief Check whether a template partial specialization that we've discovered
8994/// is hidden, and produce suitable diagnostics if so.
8995void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8996 NamedDecl *Spec) {
8997 llvm::SmallVector<Module *, 8> Modules;
8998 if (!hasVisibleDeclaration(Spec, &Modules))
8999 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9000 MissingImportKind::PartialSpecialization,
9001 /*Recover*/true);
9002}