blob: 9d4029a9124766aa0e53515085aed8ac40da1dc7 [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
Larisse Voufo39a1e502013-08-06 01:03:05 +00002627DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002628 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002629 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002630 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002631 // D must be variable template id.
2632 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2633 "Variable template specialization is declared with a template it.");
2634
2635 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002636 TemplateArgumentListInfo TemplateArgs =
2637 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002638 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2639 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2640 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002641
Richard Smithbeef3452014-01-16 23:39:20 +00002642 TemplateName Name = TemplateId->Template.get();
2643
2644 // The template-id must name a variable template.
2645 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002646 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2647 if (!VarTemplate) {
2648 NamedDecl *FnTemplate;
2649 if (auto *OTS = Name.getAsOverloadedTemplate())
2650 FnTemplate = *OTS->begin();
2651 else
2652 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2653 if (FnTemplate)
2654 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2655 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002656 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2657 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002658 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002659
2660 // Check for unexpanded parameter packs in any of the template arguments.
2661 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2662 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2663 UPPC_PartialSpecialization))
2664 return true;
2665
2666 // Check that the template argument list is well-formed for this
2667 // template.
2668 SmallVector<TemplateArgument, 4> Converted;
2669 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2670 false, Converted))
2671 return true;
2672
Larisse Voufo39a1e502013-08-06 01:03:05 +00002673 // Find the variable template (partial) specialization declaration that
2674 // corresponds to these arguments.
2675 if (IsPartialSpecialization) {
2676 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002677 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2678 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002679 return true;
2680
2681 bool InstantiationDependent;
2682 if (!Name.isDependent() &&
2683 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002684 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002685 InstantiationDependent)) {
2686 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2687 << VarTemplate->getDeclName();
2688 IsPartialSpecialization = false;
2689 }
Richard Smith300e0c32013-09-24 04:49:23 +00002690
2691 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2692 Converted)) {
2693 // C++ [temp.class.spec]p9b3:
2694 //
2695 // -- The argument list of the specialization shall not be identical
2696 // to the implicit argument list of the primary template.
2697 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2698 << /*variable template*/ 1
2699 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2700 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2701 // FIXME: Recover from this by treating the declaration as a redeclaration
2702 // of the primary template.
2703 return true;
2704 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002705 }
2706
Craig Topperc3ec1492014-05-26 06:22:03 +00002707 void *InsertPos = nullptr;
2708 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002709
2710 if (IsPartialSpecialization)
2711 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002712 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002713 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002714 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002715
Craig Topperc3ec1492014-05-26 06:22:03 +00002716 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002717
2718 // Check whether we can declare a variable template specialization in
2719 // the current scope.
2720 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2721 TemplateNameLoc,
2722 IsPartialSpecialization))
2723 return true;
2724
2725 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2726 // Since the only prior variable template specialization with these
2727 // arguments was referenced but not declared, reuse that
2728 // declaration node as our own, updating its source location and
2729 // the list of outer template parameters to reflect our new declaration.
2730 Specialization = PrevDecl;
2731 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002732 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002733 } else if (IsPartialSpecialization) {
2734 // Create a new class template partial specialization declaration node.
2735 VarTemplatePartialSpecializationDecl *PrevPartial =
2736 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002737 VarTemplatePartialSpecializationDecl *Partial =
2738 VarTemplatePartialSpecializationDecl::Create(
2739 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2740 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002741 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002742
2743 if (!PrevPartial)
2744 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2745 Specialization = Partial;
2746
2747 // If we are providing an explicit specialization of a member variable
2748 // template specialization, make a note of that.
2749 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002750 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002751
2752 // Check that all of the template parameters of the variable template
2753 // partial specialization are deducible from the template
2754 // arguments. If not, this variable template partial specialization
2755 // will never be used.
2756 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2757 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2758 TemplateParams->getDepth(), DeducibleParams);
2759
2760 if (!DeducibleParams.all()) {
2761 unsigned NumNonDeducible =
2762 DeducibleParams.size() - DeducibleParams.count();
2763 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002764 << /*variable template*/ 1 << (NumNonDeducible > 1)
2765 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002766 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2767 if (!DeducibleParams[I]) {
2768 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2769 if (Param->getDeclName())
2770 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2771 << Param->getDeclName();
2772 else
2773 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002774 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002775 }
2776 }
2777 }
2778 } else {
2779 // Create a new class template specialization declaration node for
2780 // this explicit specialization or friend declaration.
2781 Specialization = VarTemplateSpecializationDecl::Create(
2782 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002783 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002784 Specialization->setTemplateArgsInfo(TemplateArgs);
2785
2786 if (!PrevDecl)
2787 VarTemplate->AddSpecialization(Specialization, InsertPos);
2788 }
2789
2790 // C++ [temp.expl.spec]p6:
2791 // If a template, a member template or the member of a class template is
2792 // explicitly specialized then that specialization shall be declared
2793 // before the first use of that specialization that would cause an implicit
2794 // instantiation to take place, in every translation unit in which such a
2795 // use occurs; no diagnostic is required.
2796 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2797 bool Okay = false;
2798 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2799 // Is there any previous explicit specialization declaration?
2800 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2801 Okay = true;
2802 break;
2803 }
2804 }
2805
2806 if (!Okay) {
2807 SourceRange Range(TemplateNameLoc, RAngleLoc);
2808 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2809 << Name << Range;
2810
2811 Diag(PrevDecl->getPointOfInstantiation(),
2812 diag::note_instantiation_required_here)
2813 << (PrevDecl->getTemplateSpecializationKind() !=
2814 TSK_ImplicitInstantiation);
2815 return true;
2816 }
2817 }
2818
2819 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2820 Specialization->setLexicalDeclContext(CurContext);
2821
2822 // Add the specialization into its lexical context, so that it can
2823 // be seen when iterating through the list of declarations in that
2824 // context. However, specializations are not found by name lookup.
2825 CurContext->addDecl(Specialization);
2826
2827 // Note that this is an explicit specialization.
2828 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2829
2830 if (PrevDecl) {
2831 // Check that this isn't a redefinition of this specialization,
2832 // merging with previous declarations.
2833 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2834 ForRedeclaration);
2835 PrevSpec.addDecl(PrevDecl);
2836 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002837 } else if (Specialization->isStaticDataMember() &&
2838 Specialization->isOutOfLine()) {
2839 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002840 }
2841
2842 // Link instantiations of static data members back to the template from
2843 // which they were instantiated.
2844 if (Specialization->isStaticDataMember())
2845 Specialization->setInstantiationOfStaticDataMember(
2846 VarTemplate->getTemplatedDecl(),
2847 Specialization->getSpecializationKind());
2848
2849 return Specialization;
2850}
2851
2852namespace {
2853/// \brief A partial specialization whose template arguments have matched
2854/// a given template-id.
2855struct PartialSpecMatchResult {
2856 VarTemplatePartialSpecializationDecl *Partial;
2857 TemplateArgumentList *Args;
2858};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002859} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002860
2861DeclResult
2862Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2863 SourceLocation TemplateNameLoc,
2864 const TemplateArgumentListInfo &TemplateArgs) {
2865 assert(Template && "A variable template id without template?");
2866
2867 // Check that the template argument list is well-formed for this template.
2868 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002869 if (CheckTemplateArgumentList(
2870 Template, TemplateNameLoc,
2871 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002872 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002873 return true;
2874
2875 // Find the variable template specialization declaration that
2876 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002877 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002878 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002879 Converted, InsertPos)) {
2880 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002881 // If we already have a variable template specialization, return it.
2882 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002883 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002884
2885 // This is the first time we have referenced this variable template
2886 // specialization. Create the canonical declaration and add it to
2887 // the set of specializations, based on the closest partial specialization
2888 // that it represents. That is,
2889 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2890 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002891 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002892 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2893 bool AmbiguousPartialSpec = false;
2894 typedef PartialSpecMatchResult MatchResult;
2895 SmallVector<MatchResult, 4> Matched;
2896 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002897 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2898 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002899
2900 // 1. Attempt to find the closest partial specialization that this
2901 // specializes, if any.
2902 // If any of the template arguments is dependent, then this is probably
2903 // a placeholder for an incomplete declarative context; which must be
2904 // complete by instantiation time. Thus, do not search through the partial
2905 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002906 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2907 // Perhaps better after unification of DeduceTemplateArguments() and
2908 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002909 bool InstantiationDependent = false;
2910 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2911 TemplateArgs, InstantiationDependent)) {
2912
2913 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2914 Template->getPartialSpecializations(PartialSpecs);
2915
2916 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2917 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2918 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2919
2920 if (TemplateDeductionResult Result =
2921 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2922 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002923 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002924 FailedCandidates.addCandidate().set(
2925 DeclAccessPair::make(Template, AS_public), Partial,
2926 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002927 (void)Result;
2928 } else {
2929 Matched.push_back(PartialSpecMatchResult());
2930 Matched.back().Partial = Partial;
2931 Matched.back().Args = Info.take();
2932 }
2933 }
2934
Larisse Voufo39a1e502013-08-06 01:03:05 +00002935 if (Matched.size() >= 1) {
2936 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2937 if (Matched.size() == 1) {
2938 // -- If exactly one matching specialization is found, the
2939 // instantiation is generated from that specialization.
2940 // We don't need to do anything for this.
2941 } else {
2942 // -- If more than one matching specialization is found, the
2943 // partial order rules (14.5.4.2) are used to determine
2944 // whether one of the specializations is more specialized
2945 // than the others. If none of the specializations is more
2946 // specialized than all of the other matching
2947 // specializations, then the use of the variable template is
2948 // ambiguous and the program is ill-formed.
2949 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2950 PEnd = Matched.end();
2951 P != PEnd; ++P) {
2952 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2953 PointOfInstantiation) ==
2954 P->Partial)
2955 Best = P;
2956 }
2957
2958 // Determine if the best partial specialization is more specialized than
2959 // the others.
2960 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2961 PEnd = Matched.end();
2962 P != PEnd; ++P) {
2963 if (P != Best && getMoreSpecializedPartialSpecialization(
2964 P->Partial, Best->Partial,
2965 PointOfInstantiation) != Best->Partial) {
2966 AmbiguousPartialSpec = true;
2967 break;
2968 }
2969 }
2970 }
2971
2972 // Instantiate using the best variable template partial specialization.
2973 InstantiationPattern = Best->Partial;
2974 InstantiationArgs = Best->Args;
2975 } else {
2976 // -- If no match is found, the instantiation is generated
2977 // from the primary template.
2978 // InstantiationPattern = Template->getTemplatedDecl();
2979 }
2980 }
2981
Larisse Voufo39a1e502013-08-06 01:03:05 +00002982 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00002983 // Note that we do not instantiate a definition until we see an odr-use
2984 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002985 // FIXME: LateAttrs et al.?
2986 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2987 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2988 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2989 if (!Decl)
2990 return true;
2991
2992 if (AmbiguousPartialSpec) {
2993 // Partial ordering did not produce a clear winner. Complain.
2994 Decl->setInvalidDecl();
2995 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2996 << Decl;
2997
2998 // Print the matching partial specializations.
Yaron Keren1cb81462016-11-16 13:45:34 +00002999 for (MatchResult P : Matched)
3000 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3001 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3002 *P.Args);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003003 return true;
3004 }
3005
3006 if (VarTemplatePartialSpecializationDecl *D =
3007 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3008 Decl->setInstantiationOf(D, InstantiationArgs);
3009
Richard Smith6739a102016-05-05 00:56:12 +00003010 checkSpecializationVisibility(TemplateNameLoc, Decl);
3011
Larisse Voufo39a1e502013-08-06 01:03:05 +00003012 assert(Decl && "No variable template specialization?");
3013 return Decl;
3014}
3015
3016ExprResult
3017Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3018 const DeclarationNameInfo &NameInfo,
3019 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3020 const TemplateArgumentListInfo *TemplateArgs) {
3021
3022 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3023 *TemplateArgs);
3024 if (Decl.isInvalid())
3025 return ExprError();
3026
3027 VarDecl *Var = cast<VarDecl>(Decl.get());
3028 if (!Var->getTemplateSpecializationKind())
3029 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3030 NameInfo.getLoc());
3031
3032 // Build an ordinary singleton decl ref.
3033 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00003034 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003035}
3036
John McCalldadc5752010-08-24 06:29:42 +00003037ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003038 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003039 LookupResult &R,
3040 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003041 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00003042 // FIXME: Can we do any checking at this point? I guess we could check the
3043 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003044 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003045 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003046 // foo<int> could identify a single function unambiguously
3047 // This approach does NOT work, since f<int>(1);
3048 // gets resolved prior to resorting to overload resolution
3049 // i.e., template<class T> void f(double);
3050 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003051
3052 // These should be filtered out by our callers.
3053 assert(!R.empty() && "empty lookup results when building templateid");
3054 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3055
Larisse Voufo39a1e502013-08-06 01:03:05 +00003056 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003057 bool InstantiationDependent;
3058 if (R.getAsSingle<VarTemplateDecl>() &&
3059 !TemplateSpecializationType::anyDependentTemplateArguments(
3060 *TemplateArgs, InstantiationDependent)) {
3061 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3062 R.getAsSingle<VarTemplateDecl>(),
3063 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003064 }
3065
John McCall58cc69d2010-01-27 01:50:18 +00003066 // We don't want lookup warnings at this point.
3067 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003068
John McCalle66edc12009-11-24 19:00:30 +00003069 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003070 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003071 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003072 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003073 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003075 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003076
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003077 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003078}
3079
John McCalle66edc12009-11-24 19:00:30 +00003080// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003081ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003082Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003083 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003084 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003085 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003086
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003087 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003088 DeclContext *DC;
3089 if (!(DC = computeDeclContext(SS, false)) ||
3090 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003091 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003092 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003093
Douglas Gregor786123d2010-05-21 23:18:07 +00003094 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003095 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003096 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003097 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003098
John McCalle66edc12009-11-24 19:00:30 +00003099 if (R.isAmbiguous())
3100 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
John McCalle66edc12009-11-24 19:00:30 +00003102 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003103 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3104 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003105 return ExprError();
3106 }
3107
3108 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003109 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003110 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003111 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003112 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3113 return ExprError();
3114 }
3115
Abramo Bagnara7945c982012-01-27 09:46:47 +00003116 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003117}
3118
Douglas Gregorb67535d2009-03-31 00:43:58 +00003119/// \brief Form a dependent template name.
3120///
3121/// This action forms a dependent template name given the template
3122/// name and its (presumably dependent) scope specifier. For
3123/// example, given "MetaFun::template apply", the scope specifier \p
3124/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3125/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003126TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003127 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003128 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003129 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003130 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003131 bool EnteringContext,
3132 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003133 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3134 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003135 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003136 diag::warn_cxx98_compat_template_outside_of_template :
3137 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003138 << FixItHint::CreateRemoval(TemplateKWLoc);
3139
Craig Topperc3ec1492014-05-26 06:22:03 +00003140 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003141 if (SS.isSet())
3142 LookupCtx = computeDeclContext(SS, EnteringContext);
3143 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003144 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003145 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003146 // C++0x [temp.names]p5:
3147 // If a name prefixed by the keyword template is not the name of
3148 // a template, the program is ill-formed. [Note: the keyword
3149 // template may not be applied to non-template members of class
3150 // templates. -end note ] [ Note: as is the case with the
3151 // typename prefix, the template prefix is allowed in cases
3152 // where it is not strictly necessary; i.e., when the
3153 // nested-name-specifier or the expression on the left of the ->
3154 // or . is not dependent on a template-parameter, or the use
3155 // does not appear in the scope of a template. -end note]
3156 //
3157 // Note: C++03 was more strict here, because it banned the use of
3158 // the "template" keyword prior to a template-name that was not a
3159 // dependent name. C++ DR468 relaxed this requirement (the
3160 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003161 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003162 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003163 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003164 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003165 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003166 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3167 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003168 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3169 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003170 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003171 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003172 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003173 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003174 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003175 << Name.getSourceRange()
3176 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003177 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003178 } else {
3179 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003180 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003181 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003182 }
3183
Aaron Ballman4a979672014-01-03 13:56:08 +00003184 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185
Douglas Gregor3cf81312009-11-03 23:16:33 +00003186 switch (Name.getKind()) {
3187 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003189 Name.Identifier));
3190 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
Douglas Gregor71395fa2009-11-04 00:56:37 +00003192 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003193 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003194 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003195 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003196
3197 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003198 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003199
Douglas Gregor3cf81312009-11-03 23:16:33 +00003200 default:
3201 break;
3202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003204 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003205 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003206 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003207 << Name.getSourceRange()
3208 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003209 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003210}
3211
Mike Stump11289f42009-09-09 15:08:12 +00003212bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003213 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003214 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003215 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003216 QualType ArgType;
3217 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003218
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003219 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003220 switch(Arg.getKind()) {
3221 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003222 // C++ [temp.arg.type]p1:
3223 // A template-argument for a template-parameter which is a
3224 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003225 ArgType = Arg.getAsType();
3226 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003227 break;
3228 case TemplateArgument::Template: {
3229 // We have a template type parameter but the template argument
3230 // is a template without any arguments.
3231 SourceRange SR = AL.getSourceRange();
3232 TemplateName Name = Arg.getAsTemplate();
3233 Diag(SR.getBegin(), diag::err_template_missing_args)
3234 << Name << SR;
3235 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3236 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003237
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003238 return true;
3239 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003240 case TemplateArgument::Expression: {
3241 // We have a template type parameter but the template argument is an
3242 // expression; see if maybe it is missing the "typename" keyword.
3243 CXXScopeSpec SS;
3244 DeclarationNameInfo NameInfo;
3245
3246 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3247 SS.Adopt(ArgExpr->getQualifierLoc());
3248 NameInfo = ArgExpr->getNameInfo();
3249 } else if (DependentScopeDeclRefExpr *ArgExpr =
3250 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3251 SS.Adopt(ArgExpr->getQualifierLoc());
3252 NameInfo = ArgExpr->getNameInfo();
3253 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3254 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003255 if (ArgExpr->isImplicitAccess()) {
3256 SS.Adopt(ArgExpr->getQualifierLoc());
3257 NameInfo = ArgExpr->getMemberNameInfo();
3258 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003259 }
3260
Reid Kleckner377c1592014-06-10 23:29:48 +00003261 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003262 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3263 LookupParsedName(Result, CurScope, &SS);
3264
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003265 if (Result.getAsSingle<TypeDecl>() ||
3266 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003267 LookupResult::NotFoundInCurrentInstantiation) {
3268 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003269 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003270 Diag(Loc, getLangOpts().MSVCCompat
3271 ? diag::ext_ms_template_type_arg_missing_typename
3272 : diag::err_template_arg_must_be_type_suggest)
3273 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003274 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003275
3276 // Recover by synthesizing a type using the location information that we
3277 // already have.
3278 ArgType =
3279 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3280 TypeLocBuilder TLB;
3281 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3282 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3283 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3284 TL.setNameLoc(NameInfo.getLoc());
3285 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3286
3287 // Overwrite our input TemplateArgumentLoc so that we can recover
3288 // properly.
3289 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3290 TemplateArgumentLocInfo(TSI));
3291
3292 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003293 }
3294 }
3295 // fallthrough
3296 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003297 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003298 // We have a template type parameter but the template argument
3299 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003300 SourceRange SR = AL.getSourceRange();
3301 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003302 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003303
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003304 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003305 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003306 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003307
Reid Kleckner377c1592014-06-10 23:29:48 +00003308 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003309 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003310
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003311 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003312 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003313
3314 // Objective-C ARC:
3315 // If an explicitly-specified template argument type is a lifetime type
3316 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003317 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003318 ArgType->isObjCLifetimeType() &&
3319 !ArgType.getObjCLifetime()) {
3320 Qualifiers Qs;
3321 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3322 ArgType = Context.getQualifiedType(ArgType, Qs);
3323 }
3324
3325 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003326 return false;
3327}
3328
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003329/// \brief Substitute template arguments into the default template argument for
3330/// the given template type parameter.
3331///
3332/// \param SemaRef the semantic analysis object for which we are performing
3333/// the substitution.
3334///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003336/// for.
3337///
3338/// \param TemplateLoc the location of the template name that started the
3339/// template-id we are checking.
3340///
3341/// \param RAngleLoc the location of the right angle bracket ('>') that
3342/// terminates the template-id.
3343///
3344/// \param Param the template template parameter whose default we are
3345/// substituting into.
3346///
3347/// \param Converted the list of template arguments provided for template
3348/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003349/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003350static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003351SubstDefaultTemplateArgument(Sema &SemaRef,
3352 TemplateDecl *Template,
3353 SourceLocation TemplateLoc,
3354 SourceLocation RAngleLoc,
3355 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003356 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003357 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003358
3359 // If the argument type is dependent, instantiate it now based
3360 // on the previously-computed template arguments.
3361 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003362 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003363 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003364 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003365 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003366 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367
David Majnemer8b622692016-07-03 21:17:51 +00003368 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003369
3370 // Only substitute for the innermost template argument list.
3371 MultiLevelTemplateArgumentList TemplateArgLists;
3372 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3373 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3374 TemplateArgLists.addOuterTemplateArguments(None);
3375
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003376 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003377 ArgType =
3378 SemaRef.SubstType(ArgType, TemplateArgLists,
3379 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003380 }
3381
3382 return ArgType;
3383}
3384
3385/// \brief Substitute template arguments into the default template argument for
3386/// the given non-type template parameter.
3387///
3388/// \param SemaRef the semantic analysis object for which we are performing
3389/// the substitution.
3390///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003392/// for.
3393///
3394/// \param TemplateLoc the location of the template name that started the
3395/// template-id we are checking.
3396///
3397/// \param RAngleLoc the location of the right angle bracket ('>') that
3398/// terminates the template-id.
3399///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003400/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003401/// substituting into.
3402///
3403/// \param Converted the list of template arguments provided for template
3404/// parameters that precede \p Param in the template parameter list.
3405///
3406/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003407static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003408SubstDefaultTemplateArgument(Sema &SemaRef,
3409 TemplateDecl *Template,
3410 SourceLocation TemplateLoc,
3411 SourceLocation RAngleLoc,
3412 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003413 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003414 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith54f18e82016-08-31 02:15:21 +00003415 Param, Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003416 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003417 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003418 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003419
David Majnemer8b622692016-07-03 21:17:51 +00003420 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003421
3422 // Only substitute for the innermost template argument list.
3423 MultiLevelTemplateArgumentList TemplateArgLists;
3424 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3425 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3426 TemplateArgLists.addOuterTemplateArguments(None);
3427
Faisal Vali48401eb2015-11-19 19:20:17 +00003428 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3429 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003430 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003431}
3432
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003433/// \brief Substitute template arguments into the default template argument for
3434/// the given template template parameter.
3435///
3436/// \param SemaRef the semantic analysis object for which we are performing
3437/// the substitution.
3438///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003440/// for.
3441///
3442/// \param TemplateLoc the location of the template name that started the
3443/// template-id we are checking.
3444///
3445/// \param RAngleLoc the location of the right angle bracket ('>') that
3446/// terminates the template-id.
3447///
3448/// \param Param the template template parameter whose default we are
3449/// substituting into.
3450///
3451/// \param Converted the list of template arguments provided for template
3452/// parameters that precede \p Param in the template parameter list.
3453///
Douglas Gregordf846d12011-03-02 18:46:51 +00003454/// \param QualifierLoc Will be set to the nested-name-specifier (with
3455/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003456///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003457/// \returns the substituted template argument, or NULL if an error occurred.
3458static TemplateName
3459SubstDefaultTemplateArgument(Sema &SemaRef,
3460 TemplateDecl *Template,
3461 SourceLocation TemplateLoc,
3462 SourceLocation RAngleLoc,
3463 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003464 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003465 NestedNameSpecifierLoc &QualifierLoc) {
Richard Smith54f18e82016-08-31 02:15:21 +00003466 Sema::InstantiatingTemplate Inst(
3467 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
3468 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003469 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003470 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471
David Majnemer8b622692016-07-03 21:17:51 +00003472 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003473
3474 // Only substitute for the innermost template argument list.
3475 MultiLevelTemplateArgumentList TemplateArgLists;
3476 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3477 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3478 TemplateArgLists.addOuterTemplateArguments(None);
3479
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003480 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003481 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003482 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003483 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003484 QualifierLoc =
3485 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003486 if (!QualifierLoc)
3487 return TemplateName();
3488 }
David Majnemer89189202013-08-28 23:48:32 +00003489
3490 return SemaRef.SubstTemplateName(
3491 QualifierLoc,
3492 Param->getDefaultArgument().getArgument().getAsTemplate(),
3493 Param->getDefaultArgument().getTemplateNameLoc(),
3494 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003495}
3496
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003497/// \brief If the given template parameter has a default template
3498/// argument, substitute into that default template argument and
3499/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003501Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3502 SourceLocation TemplateLoc,
3503 SourceLocation RAngleLoc,
3504 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003505 SmallVectorImpl<TemplateArgument>
3506 &Converted,
3507 bool &HasDefaultArg) {
3508 HasDefaultArg = false;
3509
3510 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003511 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003512 return TemplateArgumentLoc();
3513
Richard Smithc87b9382013-07-04 01:01:24 +00003514 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003515 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003516 TemplateLoc,
3517 RAngleLoc,
3518 TypeParm,
3519 Converted);
3520 if (DI)
3521 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3522
3523 return TemplateArgumentLoc();
3524 }
3525
3526 if (NonTypeTemplateParmDecl *NonTypeParm
3527 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003528 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003529 return TemplateArgumentLoc();
3530
Richard Smithc87b9382013-07-04 01:01:24 +00003531 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003532 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003533 TemplateLoc,
3534 RAngleLoc,
3535 NonTypeParm,
3536 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003537 if (Arg.isInvalid())
3538 return TemplateArgumentLoc();
3539
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003540 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003541 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3542 }
3543
3544 TemplateTemplateParmDecl *TempTempParm
3545 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003546 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003547 return TemplateArgumentLoc();
3548
Richard Smithc87b9382013-07-04 01:01:24 +00003549 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003550 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003551 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003553 RAngleLoc,
3554 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003555 Converted,
3556 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003557 if (TName.isNull())
3558 return TemplateArgumentLoc();
3559
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003561 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003562 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3563}
3564
Douglas Gregorda0fb532009-11-11 19:31:23 +00003565/// \brief Check that the given template argument corresponds to the given
3566/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003567///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003569/// checked.
3570///
Richard Trieu15b66532015-01-24 02:48:32 +00003571/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003572///
3573/// \param Template The template in which the template argument resides.
3574///
3575/// \param TemplateLoc The location of the template name for the template
3576/// whose argument list we're matching.
3577///
3578/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3579/// the template argument list.
3580///
3581/// \param ArgumentPackIndex The index into the argument pack where this
3582/// argument will be placed. Only valid if the parameter is a parameter pack.
3583///
3584/// \param Converted The checked, converted argument will be added to the
3585/// end of this small vector.
3586///
3587/// \param CTAK Describes how we arrived at this particular template argument:
3588/// explicitly written, deduced, etc.
3589///
3590/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003591bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003592 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003593 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003594 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003595 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003596 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003597 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003598 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003599 // Check template type parameters.
3600 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003601 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Douglas Gregoreebed722009-11-11 19:41:09 +00003603 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003605 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003606 // with the template arguments we've seen thus far. But if the
3607 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003608 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003609 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3610 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611
Peter Collingbourne01687632010-12-10 17:08:53 +00003612 if (NTTPType->isDependentType() &&
3613 !isa<TemplateTemplateParmDecl>(Template) &&
3614 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003615 // Do substitution on the type of the non-type template parameter.
3616 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003617 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003618 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003619 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003620 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003621
3622 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003623 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003624 NTTPType = SubstType(NTTPType,
3625 MultiLevelTemplateArgumentList(TemplateArgs),
3626 NTTP->getLocation(),
3627 NTTP->getDeclName());
3628 // If that worked, check the non-type template parameter type
3629 // for validity.
3630 if (!NTTPType.isNull())
3631 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3632 NTTP->getLocation());
3633 if (NTTPType.isNull())
3634 return true;
3635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636
Douglas Gregorda0fb532009-11-11 19:31:23 +00003637 switch (Arg.getArgument().getKind()) {
3638 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003639 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregorda0fb532009-11-11 19:31:23 +00003641 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003642 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003643 ExprResult Res =
3644 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3645 Result, CTAK);
3646 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003647 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
Richard Trieu15b66532015-01-24 02:48:32 +00003649 // If the resulting expression is new, then use it in place of the
3650 // old expression in the template argument.
3651 if (Res.get() != Arg.getArgument().getAsExpr()) {
3652 TemplateArgument TA(Res.get());
3653 Arg = TemplateArgumentLoc(TA, Res.get());
3654 }
3655
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003656 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003657 break;
3658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659
Douglas Gregorda0fb532009-11-11 19:31:23 +00003660 case TemplateArgument::Declaration:
3661 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003662 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003663 // We've already checked this template argument, so just copy
3664 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003665 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003666 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Douglas Gregorda0fb532009-11-11 19:31:23 +00003668 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003669 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003670 // We were given a template template argument. It may not be ill-formed;
3671 // see below.
3672 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003673 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3674 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003675 // We have a template argument such as \c T::template X, which we
3676 // parsed as a template template argument. However, since we now
3677 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003678 // template name into an expression.
3679
3680 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3681 Arg.getTemplateNameLoc());
3682
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003683 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003684 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003685 // FIXME: the template-template arg was a DependentTemplateName,
3686 // so it was provided with a template keyword. However, its source
3687 // location is not stored in the template argument structure.
3688 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003689 ExprResult E = DependentScopeDeclRefExpr::Create(
3690 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3691 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003692
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003693 // If we parsed the template argument as a pack expansion, create a
3694 // pack expansion expression.
3695 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003696 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003697 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003698 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
Douglas Gregorda0fb532009-11-11 19:31:23 +00003701 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003702 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003703 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003704 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003706 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003707 break;
3708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709
Douglas Gregorda0fb532009-11-11 19:31:23 +00003710 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003711 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003712 // therefore cannot be a non-type template argument.
3713 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3714 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
Douglas Gregorda0fb532009-11-11 19:31:23 +00003716 Diag(Param->getLocation(), diag::note_template_param_here);
3717 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003718
Douglas Gregorda0fb532009-11-11 19:31:23 +00003719 case TemplateArgument::Type: {
3720 // We have a non-type template parameter but the template
3721 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Douglas Gregorda0fb532009-11-11 19:31:23 +00003723 // C++ [temp.arg]p2:
3724 // In a template-argument, an ambiguity between a type-id and
3725 // an expression is resolved to a type-id, regardless of the
3726 // form of the corresponding template-parameter.
3727 //
3728 // We warn specifically about this case, since it can be rather
3729 // confusing for users.
3730 QualType T = Arg.getArgument().getAsType();
3731 SourceRange SR = Arg.getSourceRange();
3732 if (T->isFunctionType())
3733 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3734 else
3735 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3736 Diag(Param->getLocation(), diag::note_template_param_here);
3737 return true;
3738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregorda0fb532009-11-11 19:31:23 +00003740 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003741 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743
Douglas Gregorda0fb532009-11-11 19:31:23 +00003744 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745 }
3746
3747
Douglas Gregorda0fb532009-11-11 19:31:23 +00003748 // Check template template parameters.
3749 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Douglas Gregorda0fb532009-11-11 19:31:23 +00003751 // Substitute into the template parameter list of the template
3752 // template parameter, since previously-supplied template arguments
3753 // may appear within the template template parameter.
3754 {
3755 // Set up a template instantiation context.
3756 LocalInstantiationScope Scope(*this);
3757 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003758 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003759 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003760 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003761 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762
David Majnemer8b622692016-07-03 21:17:51 +00003763 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003764 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003766 MultiLevelTemplateArgumentList(TemplateArgs)));
3767 if (!TempParm)
3768 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Douglas Gregorda0fb532009-11-11 19:31:23 +00003771 switch (Arg.getArgument().getKind()) {
3772 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003773 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Douglas Gregorda0fb532009-11-11 19:31:23 +00003775 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003776 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003777 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003778 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003780 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003781 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782
Douglas Gregorda0fb532009-11-11 19:31:23 +00003783 case TemplateArgument::Expression:
3784 case TemplateArgument::Type:
3785 // We have a template template parameter but the template
3786 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003787 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003788 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003789 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003790
Douglas Gregorda0fb532009-11-11 19:31:23 +00003791 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003792 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003793 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003794 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003795 case TemplateArgument::NullPtr:
3796 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797
Douglas Gregorda0fb532009-11-11 19:31:23 +00003798 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003799 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003801
Douglas Gregorda0fb532009-11-11 19:31:23 +00003802 return false;
3803}
3804
Douglas Gregor8e072612012-02-03 07:34:46 +00003805/// \brief Diagnose an arity mismatch in the
3806static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3807 SourceLocation TemplateLoc,
3808 TemplateArgumentListInfo &TemplateArgs) {
3809 TemplateParameterList *Params = Template->getTemplateParameters();
3810 unsigned NumParams = Params->size();
3811 unsigned NumArgs = TemplateArgs.size();
3812
3813 SourceRange Range;
3814 if (NumArgs > NumParams)
3815 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3816 TemplateArgs.getRAngleLoc());
3817 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3818 << (NumArgs > NumParams)
3819 << (isa<ClassTemplateDecl>(Template)? 0 :
3820 isa<FunctionTemplateDecl>(Template)? 1 :
3821 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3822 << Template << Range;
3823 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3824 << Params->getSourceRange();
3825 return true;
3826}
3827
Richard Smith1fde8ec2012-09-07 02:06:42 +00003828/// \brief Check whether the template parameter is a pack expansion, and if so,
3829/// determine the number of parameters produced by that expansion. For instance:
3830///
3831/// \code
3832/// template<typename ...Ts> struct A {
3833/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3834/// };
3835/// \endcode
3836///
3837/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3838/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003839static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003840 if (NonTypeTemplateParmDecl *NTTP
3841 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3842 if (NTTP->isExpandedParameterPack())
3843 return NTTP->getNumExpansionTypes();
3844 }
3845
3846 if (TemplateTemplateParmDecl *TTP
3847 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3848 if (TTP->isExpandedParameterPack())
3849 return TTP->getNumExpansionTemplateParameters();
3850 }
3851
David Blaikie7a30dc52013-02-21 01:47:18 +00003852 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003853}
3854
Richard Smith35c1df52015-06-17 20:16:32 +00003855/// Diagnose a missing template argument.
3856template<typename TemplateParmDecl>
3857static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3858 TemplateDecl *TD,
3859 const TemplateParmDecl *D,
3860 TemplateArgumentListInfo &Args) {
3861 // Dig out the most recent declaration of the template parameter; there may be
3862 // declarations of the template that are more recent than TD.
3863 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3864 ->getTemplateParameters()
3865 ->getParam(D->getIndex()));
3866
3867 // If there's a default argument that's not visible, diagnose that we're
3868 // missing a module import.
3869 llvm::SmallVector<Module*, 8> Modules;
3870 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3871 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3872 D->getDefaultArgumentLoc(), Modules,
3873 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003874 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003875 return true;
3876 }
3877
3878 // FIXME: If there's a more recent default argument that *is* visible,
3879 // diagnose that it was declared too late.
3880
3881 return diagnoseArityMismatch(S, TD, Loc, Args);
3882}
3883
Douglas Gregord32e0282009-02-09 23:23:08 +00003884/// \brief Check that the given template argument list is well-formed
3885/// for specializing the given template.
3886bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3887 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003888 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003889 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003890 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003891 // Make a copy of the template arguments for processing. Only make the
3892 // changes at the end when successful in matching the arguments to the
3893 // template.
3894 TemplateArgumentListInfo NewArgs = TemplateArgs;
3895
Douglas Gregord32e0282009-02-09 23:23:08 +00003896 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003897
Richard Trieu15b66532015-01-24 02:48:32 +00003898 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003899
Mike Stump11289f42009-09-09 15:08:12 +00003900 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003901 // [...] The type and form of each template-argument specified in
3902 // a template-id shall match the type and form specified for the
3903 // corresponding parameter declared by the template in its
3904 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003905 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003906 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003907 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003908 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003909 for (TemplateParameterList::iterator Param = Params->begin(),
3910 ParamEnd = Params->end();
3911 Param != ParamEnd; /* increment in loop */) {
3912 // If we have an expanded parameter pack, make sure we don't have too
3913 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003914 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003915 if (*Expansions == ArgumentPack.size()) {
3916 // We're done with this parameter pack. Pack up its arguments and add
3917 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003918 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003919 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003920 ArgumentPack.clear();
3921
Richard Smith1fde8ec2012-09-07 02:06:42 +00003922 // This argument is assigned to the next parameter.
3923 ++Param;
3924 continue;
3925 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3926 // Not enough arguments for this parameter pack.
3927 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3928 << false
3929 << (isa<ClassTemplateDecl>(Template)? 0 :
3930 isa<FunctionTemplateDecl>(Template)? 1 :
3931 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3932 << Template;
3933 Diag(Template->getLocation(), diag::note_template_decl_here)
3934 << Params->getSourceRange();
3935 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003936 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003938
Richard Smith1fde8ec2012-09-07 02:06:42 +00003939 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003940 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003941 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003943 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003944 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945
Richard Smith96d71c32014-11-12 23:38:38 +00003946 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003947 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003948 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3949 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003950 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003951 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003952 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003953 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003954 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003955 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003956 Diag((*Param)->getLocation(), diag::note_template_param_here);
3957 return true;
3958 }
3959
Richard Smith1fde8ec2012-09-07 02:06:42 +00003960 // We're now done with this argument.
3961 ++ArgIdx;
3962
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003963 if ((*Param)->isTemplateParameterPack()) {
3964 // The template parameter was a template parameter pack, so take the
3965 // deduced argument and place it on the argument pack. Note that we
3966 // stay on the same template parameter so that we can deduce more
3967 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003968 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003969 } else {
3970 // Move to the next template parameter.
3971 ++Param;
3972 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003973
Richard Smith96d71c32014-11-12 23:38:38 +00003974 // If we just saw a pack expansion into a non-pack, then directly convert
3975 // the remaining arguments, because we don't know what parameters they'll
3976 // match up with.
3977 if (PackExpansionIntoNonPack) {
3978 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003979 // If we were part way through filling in an expanded parameter pack,
3980 // fall back to just producing individual arguments.
3981 Converted.insert(Converted.end(),
3982 ArgumentPack.begin(), ArgumentPack.end());
3983 ArgumentPack.clear();
3984 }
3985
3986 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003987 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003988 ++ArgIdx;
3989 }
3990
Richard Smith1fde8ec2012-09-07 02:06:42 +00003991 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003992 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003993
Douglas Gregor84d49a22009-11-11 21:54:23 +00003994 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003996
Douglas Gregor2f157c92011-06-03 02:59:40 +00003997 // If we're checking a partial template argument list, we're done.
3998 if (PartialTemplateArgs) {
3999 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00004000 Converted.push_back(
4001 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4002
Richard Smith1fde8ec2012-09-07 02:06:42 +00004003 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00004004 }
4005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004007 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00004008 if ((*Param)->isTemplateParameterPack()) {
4009 assert(!getExpandedPackSize(*Param) &&
4010 "Should have dealt with this already");
4011
4012 // A non-expanded parameter pack before the end of the parameter list
4013 // only occurs for an ill-formed template parameter list, unless we've
4014 // got a partial argument list for a function template, so just bail out.
4015 if (Param + 1 != ParamEnd)
4016 return true;
4017
Benjamin Kramercce63472015-08-05 09:40:22 +00004018 Converted.push_back(
4019 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00004020 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00004021
4022 ++Param;
4023 continue;
4024 }
4025
Douglas Gregor8e072612012-02-03 07:34:46 +00004026 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00004027 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028
Douglas Gregor84d49a22009-11-11 21:54:23 +00004029 // Retrieve the default template argument from the template
4030 // parameter. For each kind of template parameter, we substitute the
4031 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004032 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00004033 // the default argument.
4034 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004035 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004036 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4037 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004038
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004040 Template,
4041 TemplateLoc,
4042 RAngleLoc,
4043 TTP,
4044 Converted);
4045 if (!ArgType)
4046 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
Douglas Gregor84d49a22009-11-11 21:54:23 +00004048 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4049 ArgType);
4050 } else if (NonTypeTemplateParmDecl *NTTP
4051 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004052 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004053 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4054 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004055
John McCalldadc5752010-08-24 06:29:42 +00004056 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057 TemplateLoc,
4058 RAngleLoc,
4059 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004060 Converted);
4061 if (E.isInvalid())
4062 return true;
4063
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004064 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004065 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4066 } else {
4067 TemplateTemplateParmDecl *TempParm
4068 = cast<TemplateTemplateParmDecl>(*Param);
4069
Richard Smith95d83952015-06-10 20:36:34 +00004070 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004071 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4072 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004073
Douglas Gregordf846d12011-03-02 18:46:51 +00004074 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004075 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076 TemplateLoc,
4077 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004078 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004079 Converted,
4080 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004081 if (Name.isNull())
4082 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083
Douglas Gregor9d802122011-03-02 17:09:35 +00004084 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4085 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087
Douglas Gregor84d49a22009-11-11 21:54:23 +00004088 // Introduce an instantiation record that describes where we are using
Richard Smith54f18e82016-08-31 02:15:21 +00004089 // the default template argument. We're not actually instantiating a
4090 // template here, we just create this object to put a note into the
4091 // context stack.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004092 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4093 SourceRange(TemplateLoc, RAngleLoc));
4094 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004095 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096
Douglas Gregor84d49a22009-11-11 21:54:23 +00004097 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004098 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004099 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004100 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101
Richard Trieu15b66532015-01-24 02:48:32 +00004102 // Core issue 150 (assumed resolution): if this is a template template
4103 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004104 // template definition.
4105 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004106 NewArgs.addArgument(Arg);
4107
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004108 // Move to the next template parameter and argument.
4109 ++Param;
4110 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112
Richard Smith07f79912014-06-06 16:00:50 +00004113 // If we're performing a partial argument substitution, allow any trailing
4114 // pack expansions; they might be empty. This can happen even if
4115 // PartialTemplateArgs is false (the list of arguments is complete but
4116 // still dependent).
4117 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4118 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004119 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4120 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004121 }
4122
Douglas Gregor8e072612012-02-03 07:34:46 +00004123 // If we have any leftover arguments, then there were too many arguments.
4124 // Complain and fail.
4125 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004126 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4127
4128 // No problems found with the new argument list, propagate changes back
4129 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004130 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131
Richard Smith1fde8ec2012-09-07 02:06:42 +00004132 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004133}
4134
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004135namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136 class UnnamedLocalNoLinkageFinder
4137 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004138 {
4139 Sema &S;
4140 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004142 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004144 public:
4145 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4146
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147 bool Visit(QualType T) {
4148 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004151#define TYPE(Class, Parent) \
4152 bool Visit##Class##Type(const Class##Type *);
4153#define ABSTRACT_TYPE(Class, Parent) \
4154 bool Visit##Class##Type(const Class##Type *) { return false; }
4155#define NON_CANONICAL_TYPE(Class, Parent) \
4156 bool Visit##Class##Type(const Class##Type *) { return false; }
4157#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004159 bool VisitTagDecl(const TagDecl *Tag);
4160 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4161 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004162} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004163
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004164bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004165 return false;
4166}
4167
4168bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4169 return Visit(T->getElementType());
4170}
4171
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004173 return Visit(T->getPointeeType());
4174}
4175
4176bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004178 return Visit(T->getPointeeType());
4179}
4180
4181bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004183 return Visit(T->getPointeeType());
4184}
4185
4186bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004188 return Visit(T->getPointeeType());
4189}
4190
4191bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004193 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4194}
4195
4196bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004198 return Visit(T->getElementType());
4199}
4200
4201bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004203 return Visit(T->getElementType());
4204}
4205
4206bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004208 return Visit(T->getElementType());
4209}
4210
4211bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004213 return Visit(T->getElementType());
4214}
4215
4216bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004218 return Visit(T->getElementType());
4219}
4220
4221bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4222 return Visit(T->getElementType());
4223}
4224
4225bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4226 return Visit(T->getElementType());
4227}
4228
4229bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4230 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004231 for (const auto &A : T->param_types()) {
4232 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004233 return true;
4234 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Alp Toker314cc812014-01-25 16:55:45 +00004236 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004237}
4238
4239bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4240 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004241 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004242}
4243
4244bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4245 const UnresolvedUsingType*) {
4246 return false;
4247}
4248
4249bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4250 return false;
4251}
4252
4253bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4254 return Visit(T->getUnderlyingType());
4255}
4256
4257bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4258 return false;
4259}
4260
Alexis Hunte852b102011-05-24 22:41:36 +00004261bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4262 const UnaryTransformType*) {
4263 return false;
4264}
4265
Richard Smith30482bc2011-02-20 03:19:35 +00004266bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4267 return Visit(T->getDeducedType());
4268}
4269
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004270bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4271 return VisitTagDecl(T->getDecl());
4272}
4273
4274bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4275 return VisitTagDecl(T->getDecl());
4276}
4277
4278bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4279 const TemplateTypeParmType*) {
4280 return false;
4281}
4282
Douglas Gregorada4b792011-01-14 02:55:32 +00004283bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4284 const SubstTemplateTypeParmPackType *) {
4285 return false;
4286}
4287
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004288bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4289 const TemplateSpecializationType*) {
4290 return false;
4291}
4292
4293bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4294 const InjectedClassNameType* T) {
4295 return VisitTagDecl(T->getDecl());
4296}
4297
4298bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4299 const DependentNameType* T) {
4300 return VisitNestedNameSpecifier(T->getQualifier());
4301}
4302
4303bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4304 const DependentTemplateSpecializationType* T) {
4305 return VisitNestedNameSpecifier(T->getQualifier());
4306}
4307
Douglas Gregord2fa7662010-12-20 02:24:11 +00004308bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4309 const PackExpansionType* T) {
4310 return Visit(T->getPattern());
4311}
4312
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004313bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4314 return false;
4315}
4316
4317bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4318 const ObjCInterfaceType *) {
4319 return false;
4320}
4321
4322bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4323 const ObjCObjectPointerType *) {
4324 return false;
4325}
4326
Eli Friedman0dfb8892011-10-06 23:00:33 +00004327bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4328 return Visit(T->getValueType());
4329}
4330
Xiuli Pan9c14e282016-01-09 12:53:17 +00004331bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4332 return false;
4333}
4334
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004335bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4336 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004337 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004338 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004339 diag::warn_cxx98_compat_template_arg_local_type :
4340 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004341 << S.Context.getTypeDeclType(Tag) << SR;
4342 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343 }
4344
John McCall5ea95772013-03-09 00:54:27 +00004345 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004346 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004347 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004348 diag::warn_cxx98_compat_template_arg_unnamed_type :
4349 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004350 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4351 return true;
4352 }
4353
4354 return false;
4355}
4356
4357bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4358 NestedNameSpecifier *NNS) {
4359 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4360 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004362 switch (NNS->getKind()) {
4363 case NestedNameSpecifier::Identifier:
4364 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004365 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004366 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004367 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004368 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004370 case NestedNameSpecifier::TypeSpec:
4371 case NestedNameSpecifier::TypeSpecWithTemplate:
4372 return Visit(QualType(NNS->getAsType(), 0));
4373 }
David Blaikie8a40f702012-01-17 06:56:22 +00004374 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004375}
4376
Douglas Gregord32e0282009-02-09 23:23:08 +00004377/// \brief Check a template argument against its corresponding
4378/// template type parameter.
4379///
4380/// This routine implements the semantics of C++ [temp.arg.type]. It
4381/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004382bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004383 TypeSourceInfo *ArgInfo) {
4384 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004385 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004386 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004387
4388 if (Arg->isVariablyModifiedType()) {
4389 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004390 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004391 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004392 }
4393
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004394 // C++03 [temp.arg.type]p2:
4395 // A local type, a type with no linkage, an unnamed type or a type
4396 // compounded from any of these types shall not be used as a
4397 // template-argument for a template type-parameter.
4398 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004399 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004400 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004401 bool NeedsCheck;
4402 if (LangOpts.CPlusPlus11)
4403 NeedsCheck =
4404 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4405 SR.getBegin()) ||
4406 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4407 SR.getBegin());
4408 else
4409 NeedsCheck = Arg->hasUnnamedOrLocalType();
4410
4411 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004412 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4413 (void)Finder.Visit(Context.getCanonicalType(Arg));
4414 }
4415
Douglas Gregord32e0282009-02-09 23:23:08 +00004416 return false;
4417}
4418
Douglas Gregor20fdef32012-04-10 17:08:25 +00004419enum NullPointerValueKind {
4420 NPV_NotNullPointer,
4421 NPV_NullPointer,
4422 NPV_Error
4423};
4424
4425/// \brief Determine whether the given template argument is a null pointer
4426/// value of the appropriate type.
4427static NullPointerValueKind
4428isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4429 QualType ParamType, Expr *Arg) {
4430 if (Arg->isValueDependent() || Arg->isTypeDependent())
4431 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004432
Richard Smithdb0ac552015-12-18 22:40:25 +00004433 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004434 llvm_unreachable(
4435 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004436
David Majnemer5c734ad2014-08-14 00:49:23 +00004437 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004438 return NPV_NotNullPointer;
4439
4440 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004441 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4442 if (ArgRV.isInvalid())
4443 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004444 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004445
Douglas Gregor20fdef32012-04-10 17:08:25 +00004446 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004447 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004448 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004449 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004450 EvalResult.HasSideEffects) {
4451 SourceLocation DiagLoc = Arg->getExprLoc();
4452
4453 // If our only note is the usual "invalid subexpression" note, just point
4454 // the caret at its location rather than producing an essentially
4455 // redundant note.
4456 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4457 diag::note_invalid_subexpr_in_const_expr) {
4458 DiagLoc = Notes[0].first;
4459 Notes.clear();
4460 }
4461
4462 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4463 << Arg->getType() << Arg->getSourceRange();
4464 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4465 S.Diag(Notes[I].first, Notes[I].second);
4466
4467 S.Diag(Param->getLocation(), diag::note_template_param_here);
4468 return NPV_Error;
4469 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004470
4471 // C++11 [temp.arg.nontype]p1:
4472 // - an address constant expression of type std::nullptr_t
4473 if (Arg->getType()->isNullPtrType())
4474 return NPV_NullPointer;
4475
4476 // - a constant expression that evaluates to a null pointer value (4.10); or
4477 // - a constant expression that evaluates to a null member pointer value
4478 // (4.11); or
4479 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4480 (EvalResult.Val.isMemberPointer() &&
4481 !EvalResult.Val.getMemberPointerDecl())) {
4482 // If our expression has an appropriate type, we've succeeded.
4483 bool ObjCLifetimeConversion;
4484 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4485 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4486 ObjCLifetimeConversion))
4487 return NPV_NullPointer;
4488
4489 // The types didn't match, but we know we got a null pointer; complain,
4490 // then recover as if the types were correct.
4491 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4492 << Arg->getType() << ParamType << Arg->getSourceRange();
4493 S.Diag(Param->getLocation(), diag::note_template_param_here);
4494 return NPV_NullPointer;
4495 }
4496
4497 // If we don't have a null pointer value, but we do have a NULL pointer
4498 // constant, suggest a cast to the appropriate type.
4499 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4500 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4501 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004502 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4503 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4504 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004505 S.Diag(Param->getLocation(), diag::note_template_param_here);
4506 return NPV_NullPointer;
4507 }
4508
4509 // FIXME: If we ever want to support general, address-constant expressions
4510 // as non-type template arguments, we should return the ExprResult here to
4511 // be interpreted by the caller.
4512 return NPV_NotNullPointer;
4513}
4514
David Majnemer61c39a12013-08-23 05:39:39 +00004515/// \brief Checks whether the given template argument is compatible with its
4516/// template parameter.
4517static bool CheckTemplateArgumentIsCompatibleWithParameter(
4518 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4519 Expr *Arg, QualType ArgType) {
4520 bool ObjCLifetimeConversion;
4521 if (ParamType->isPointerType() &&
4522 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4523 S.IsQualificationConversion(ArgType, ParamType, false,
4524 ObjCLifetimeConversion)) {
4525 // For pointer-to-object types, qualification conversions are
4526 // permitted.
4527 } else {
4528 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4529 if (!ParamRef->getPointeeType()->isFunctionType()) {
4530 // C++ [temp.arg.nontype]p5b3:
4531 // For a non-type template-parameter of type reference to
4532 // object, no conversions apply. The type referred to by the
4533 // reference may be more cv-qualified than the (otherwise
4534 // identical) type of the template- argument. The
4535 // template-parameter is bound directly to the
4536 // template-argument, which shall be an lvalue.
4537
4538 // FIXME: Other qualifiers?
4539 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4540 unsigned ArgQuals = ArgType.getCVRQualifiers();
4541
4542 if ((ParamQuals | ArgQuals) != ParamQuals) {
4543 S.Diag(Arg->getLocStart(),
4544 diag::err_template_arg_ref_bind_ignores_quals)
4545 << ParamType << Arg->getType() << Arg->getSourceRange();
4546 S.Diag(Param->getLocation(), diag::note_template_param_here);
4547 return true;
4548 }
4549 }
4550 }
4551
4552 // At this point, the template argument refers to an object or
4553 // function with external linkage. We now need to check whether the
4554 // argument and parameter types are compatible.
4555 if (!S.Context.hasSameUnqualifiedType(ArgType,
4556 ParamType.getNonReferenceType())) {
4557 // We can't perform this conversion or binding.
4558 if (ParamType->isReferenceType())
4559 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4560 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4561 else
4562 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4563 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4564 S.Diag(Param->getLocation(), diag::note_template_param_here);
4565 return true;
4566 }
4567 }
4568
4569 return false;
4570}
4571
Douglas Gregorccb07762009-02-11 19:52:55 +00004572/// \brief Checks whether the given template argument is the address
4573/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004575CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4576 NonTypeTemplateParmDecl *Param,
4577 QualType ParamType,
4578 Expr *ArgIn,
4579 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004580 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004581 Expr *Arg = ArgIn;
4582 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004583
Douglas Gregorb242683d2010-04-01 18:32:35 +00004584 bool AddressTaken = false;
4585 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004586 if (S.getLangOpts().MicrosoftExt) {
4587 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4588 // dereference and address-of operators.
4589 Arg = Arg->IgnoreParenCasts();
4590
4591 bool ExtWarnMSTemplateArg = false;
4592 UnaryOperatorKind FirstOpKind;
4593 SourceLocation FirstOpLoc;
4594 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4595 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4596 if (UnOpKind == UO_Deref)
4597 ExtWarnMSTemplateArg = true;
4598 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4599 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4600 if (!AddrOpLoc.isValid()) {
4601 FirstOpKind = UnOpKind;
4602 FirstOpLoc = UnOp->getOperatorLoc();
4603 }
4604 } else
4605 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004606 }
David Majnemer61c39a12013-08-23 05:39:39 +00004607 if (FirstOpLoc.isValid()) {
4608 if (ExtWarnMSTemplateArg)
4609 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4610 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004611
David Majnemer61c39a12013-08-23 05:39:39 +00004612 if (FirstOpKind == UO_AddrOf)
4613 AddressTaken = true;
4614 else if (Arg->getType()->isPointerType()) {
4615 // We cannot let pointers get dereferenced here, that is obviously not a
4616 // constant expression.
4617 assert(FirstOpKind == UO_Deref);
4618 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4619 << Arg->getSourceRange();
4620 }
4621 }
4622 } else {
4623 // See through any implicit casts we added to fix the type.
4624 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004625
David Majnemer61c39a12013-08-23 05:39:39 +00004626 // C++ [temp.arg.nontype]p1:
4627 //
4628 // A template-argument for a non-type, non-template
4629 // template-parameter shall be one of: [...]
4630 //
4631 // -- the address of an object or function with external
4632 // linkage, including function templates and function
4633 // template-ids but excluding non-static class members,
4634 // expressed as & id-expression where the & is optional if
4635 // the name refers to a function or array, or if the
4636 // corresponding template-parameter is a reference; or
4637
4638 // In C++98/03 mode, give an extension warning on any extra parentheses.
4639 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4640 bool ExtraParens = false;
4641 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4642 if (!Invalid && !ExtraParens) {
4643 S.Diag(Arg->getLocStart(),
4644 S.getLangOpts().CPlusPlus11
4645 ? diag::warn_cxx98_compat_template_arg_extra_parens
4646 : diag::ext_template_arg_extra_parens)
4647 << Arg->getSourceRange();
4648 ExtraParens = true;
4649 }
4650
4651 Arg = Parens->getSubExpr();
4652 }
4653
4654 while (SubstNonTypeTemplateParmExpr *subst =
4655 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4656 Arg = subst->getReplacement()->IgnoreImpCasts();
4657
4658 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4659 if (UnOp->getOpcode() == UO_AddrOf) {
4660 Arg = UnOp->getSubExpr();
4661 AddressTaken = true;
4662 AddrOpLoc = UnOp->getOperatorLoc();
4663 }
4664 }
4665
4666 while (SubstNonTypeTemplateParmExpr *subst =
4667 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4668 Arg = subst->getReplacement()->IgnoreImpCasts();
4669 }
John McCall7c454bb2011-07-15 05:09:51 +00004670
David Majnemer07910d62014-06-26 07:48:46 +00004671 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4672 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4673
4674 // If our parameter has pointer type, check for a null template value.
4675 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4676 NullPointerValueKind NPV;
4677 // dllimport'd entities aren't constant but are available inside of template
4678 // arguments.
4679 if (Entity && Entity->hasAttr<DLLImportAttr>())
4680 NPV = NPV_NotNullPointer;
4681 else
4682 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4683 switch (NPV) {
4684 case NPV_NullPointer:
4685 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004686 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4687 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004688 return false;
4689
4690 case NPV_Error:
4691 return true;
4692
4693 case NPV_NotNullPointer:
4694 break;
4695 }
4696 }
4697
Chandler Carruth724a8a12010-01-31 10:01:20 +00004698 // Stop checking the precise nature of the argument if it is value dependent,
4699 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004700 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004701 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004702 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004703 }
David Majnemer61c39a12013-08-23 05:39:39 +00004704
4705 if (isa<CXXUuidofExpr>(Arg)) {
4706 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4707 ArgIn, Arg, ArgType))
4708 return true;
4709
4710 Converted = TemplateArgument(ArgIn);
4711 return false;
4712 }
4713
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004714 if (!DRE) {
4715 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4716 << Arg->getSourceRange();
4717 S.Diag(Param->getLocation(), diag::note_template_param_here);
4718 return true;
4719 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004720
Douglas Gregorccb07762009-02-11 19:52:55 +00004721 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004722 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004723 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004724 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004725 S.Diag(Param->getLocation(), diag::note_template_param_here);
4726 return true;
4727 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004728
4729 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004731 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004732 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004733 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004734 S.Diag(Param->getLocation(), diag::note_template_param_here);
4735 return true;
4736 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004737 }
Mike Stump11289f42009-09-09 15:08:12 +00004738
Richard Smith9380e0e2012-04-04 21:11:30 +00004739 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4740 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004741
Richard Smith9380e0e2012-04-04 21:11:30 +00004742 // A non-type template argument must refer to an object or function.
4743 if (!Func && !Var) {
4744 // We found something, but we don't know specifically what it is.
4745 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4746 << Arg->getSourceRange();
4747 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4748 return true;
4749 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004750
Richard Smith9380e0e2012-04-04 21:11:30 +00004751 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004752 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004753 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004754 diag::warn_cxx98_compat_template_arg_object_internal :
4755 diag::ext_template_arg_object_internal)
4756 << !Func << Entity << Arg->getSourceRange();
4757 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4758 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004759 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004760 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4761 << !Func << Entity << Arg->getSourceRange();
4762 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4763 << !Func;
4764 return true;
4765 }
4766
4767 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004768 // If the template parameter has pointer type, the function decays.
4769 if (ParamType->isPointerType() && !AddressTaken)
4770 ArgType = S.Context.getPointerType(Func->getType());
4771 else if (AddressTaken && ParamType->isReferenceType()) {
4772 // If we originally had an address-of operator, but the
4773 // parameter has reference type, complain and (if things look
4774 // like they will work) drop the address-of operator.
4775 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4776 ParamType.getNonReferenceType())) {
4777 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4778 << ParamType;
4779 S.Diag(Param->getLocation(), diag::note_template_param_here);
4780 return true;
4781 }
4782
4783 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4784 << ParamType
4785 << FixItHint::CreateRemoval(AddrOpLoc);
4786 S.Diag(Param->getLocation(), diag::note_template_param_here);
4787
4788 ArgType = Func->getType();
4789 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004790 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004791 // A value of reference type is not an object.
4792 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004793 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004794 diag::err_template_arg_reference_var)
4795 << Var->getType() << Arg->getSourceRange();
4796 S.Diag(Param->getLocation(), diag::note_template_param_here);
4797 return true;
4798 }
4799
Richard Smith9380e0e2012-04-04 21:11:30 +00004800 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004801 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004802 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4803 << Arg->getSourceRange();
4804 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4805 return true;
4806 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004807
4808 // If the template parameter has pointer type, we must have taken
4809 // the address of this object.
4810 if (ParamType->isReferenceType()) {
4811 if (AddressTaken) {
4812 // If we originally had an address-of operator, but the
4813 // parameter has reference type, complain and (if things look
4814 // like they will work) drop the address-of operator.
4815 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4816 ParamType.getNonReferenceType())) {
4817 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4818 << ParamType;
4819 S.Diag(Param->getLocation(), diag::note_template_param_here);
4820 return true;
4821 }
4822
4823 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4824 << ParamType
4825 << FixItHint::CreateRemoval(AddrOpLoc);
4826 S.Diag(Param->getLocation(), diag::note_template_param_here);
4827
4828 ArgType = Var->getType();
4829 }
4830 } else if (!AddressTaken && ParamType->isPointerType()) {
4831 if (Var->getType()->isArrayType()) {
4832 // Array-to-pointer decay.
4833 ArgType = S.Context.getArrayDecayedType(Var->getType());
4834 } else {
4835 // If the template parameter has pointer type but the address of
4836 // this object was not taken, complain and (possibly) recover by
4837 // taking the address of the entity.
4838 ArgType = S.Context.getPointerType(Var->getType());
4839 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4840 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4841 << ParamType;
4842 S.Diag(Param->getLocation(), diag::note_template_param_here);
4843 return true;
4844 }
4845
4846 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4847 << ParamType
4848 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4849
4850 S.Diag(Param->getLocation(), diag::note_template_param_here);
4851 }
4852 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004853 }
Mike Stump11289f42009-09-09 15:08:12 +00004854
David Majnemer61c39a12013-08-23 05:39:39 +00004855 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4856 Arg, ArgType))
4857 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004858
4859 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004860 Converted =
4861 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004862 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004863 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004864}
4865
4866/// \brief Checks whether the given template argument is a pointer to
4867/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004868static bool CheckTemplateArgumentPointerToMember(Sema &S,
4869 NonTypeTemplateParmDecl *Param,
4870 QualType ParamType,
4871 Expr *&ResultArg,
4872 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004873 bool Invalid = false;
4874
Douglas Gregor20fdef32012-04-10 17:08:25 +00004875 // Check for a null pointer value.
4876 Expr *Arg = ResultArg;
4877 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4878 case NPV_Error:
4879 return true;
4880 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004881 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004882 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4883 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004884 return false;
4885 case NPV_NotNullPointer:
4886 break;
4887 }
4888
4889 bool ObjCLifetimeConversion;
4890 if (S.IsQualificationConversion(Arg->getType(),
4891 ParamType.getNonReferenceType(),
4892 false, ObjCLifetimeConversion)) {
4893 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004894 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004895 ResultArg = Arg;
4896 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4897 ParamType.getNonReferenceType())) {
4898 // We can't perform this conversion.
4899 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4900 << Arg->getType() << ParamType << Arg->getSourceRange();
4901 S.Diag(Param->getLocation(), diag::note_template_param_here);
4902 return true;
4903 }
4904
Douglas Gregorccb07762009-02-11 19:52:55 +00004905 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004906 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004907 Arg = Cast->getSubExpr();
4908
4909 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004910 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004911 // A template-argument for a non-type, non-template
4912 // template-parameter shall be one of: [...]
4913 //
4914 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004915 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004916
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004917 // In C++98/03 mode, give an extension warning on any extra parentheses.
4918 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4919 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004920 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004921 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004922 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004923 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004924 diag::warn_cxx98_compat_template_arg_extra_parens :
4925 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004926 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004927 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004928 }
4929
4930 Arg = Parens->getSubExpr();
4931 }
4932
John McCall7c454bb2011-07-15 05:09:51 +00004933 while (SubstNonTypeTemplateParmExpr *subst =
4934 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4935 Arg = subst->getReplacement()->IgnoreImpCasts();
4936
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004937 // A pointer-to-member constant written &Class::member.
4938 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004939 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004940 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4941 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004942 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004945 // A constant of pointer-to-member type.
4946 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4947 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4948 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004949 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004950 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004951 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004952 } else {
4953 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004954 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004955 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004956 return Invalid;
4957 }
4958 }
4959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960
Craig Topperc3ec1492014-05-26 06:22:03 +00004961 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Douglas Gregorccb07762009-02-11 19:52:55 +00004964 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004965 return S.Diag(Arg->getLocStart(),
4966 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004967 << Arg->getSourceRange();
4968
David Majnemer3ac84e62013-10-22 21:56:38 +00004969 if (isa<FieldDecl>(DRE->getDecl()) ||
4970 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4971 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004972 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004973 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004974 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4975 "Only non-static member pointers can make it here");
4976
4977 // Okay: this is the address of a non-static member, and therefore
4978 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004979 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004980 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004981 } else {
4982 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004983 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004984 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004985 return Invalid;
4986 }
4987
4988 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004989 S.Diag(Arg->getLocStart(),
4990 diag::err_template_arg_not_pointer_to_member_form)
4991 << Arg->getSourceRange();
4992 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004993 return true;
4994}
4995
Douglas Gregord32e0282009-02-09 23:23:08 +00004996/// \brief Check a template argument against its corresponding
4997/// non-type template parameter.
4998///
Douglas Gregor463421d2009-03-03 04:44:36 +00004999/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00005000/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00005001/// returns the converted template argument. \p ParamType is the
5002/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00005003ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00005004 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00005005 TemplateArgument &Converted,
5006 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005007 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00005008
Richard Smith5f274382016-09-28 23:55:27 +00005009 // If the parameter type somehow involves auto, deduce the type now.
5010 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
5011 if (DeduceAutoType(
5012 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5013 Arg, ParamType) == DAR_Failed) {
5014 Diag(Arg->getExprLoc(),
5015 diag::err_non_type_template_parm_type_deduction_failure)
5016 << Param->getDeclName() << Param->getType() << Arg->getType()
5017 << Arg->getSourceRange();
5018 Diag(Param->getLocation(), diag::note_template_param_here);
5019 return ExprError();
5020 }
5021 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5022 // an error. The error message normally references the parameter
5023 // declaration, but here we'll pass the argument location because that's
5024 // where the parameter type is deduced.
5025 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5026 if (ParamType.isNull()) {
5027 Diag(Param->getLocation(), diag::note_template_param_here);
5028 return ExprError();
5029 }
5030 }
5031
Douglas Gregor86560402009-02-10 23:36:10 +00005032 // If either the parameter has a dependent type or the argument is
5033 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00005034 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00005035 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005036 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005037 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00005038 }
Douglas Gregor86560402009-02-10 23:36:10 +00005039
Richard Smithd663fdd2014-12-17 20:42:37 +00005040 // We should have already dropped all cv-qualifiers by now.
5041 assert(!ParamType.hasQualifiers() &&
5042 "non-type template parameter type cannot be qualified");
5043
5044 if (CTAK == CTAK_Deduced &&
5045 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
5046 // C++ [temp.deduct.type]p17:
5047 // If, in the declaration of a function template with a non-type
5048 // template-parameter, the non-type template-parameter is used
5049 // in an expression in the function parameter-list and, if the
5050 // corresponding template-argument is deduced, the
5051 // template-argument type shall match the type of the
5052 // template-parameter exactly, except that a template-argument
5053 // deduced from an array bound may be of any integral type.
5054 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5055 << Arg->getType().getUnqualifiedType()
5056 << ParamType.getUnqualifiedType();
5057 Diag(Param->getLocation(), diag::note_template_param_here);
5058 return ExprError();
5059 }
5060
Richard Smith410cc892014-11-26 03:26:53 +00005061 if (getLangOpts().CPlusPlus1z) {
5062 // FIXME: We can do some limited checking for a value-dependent but not
5063 // type-dependent argument.
5064 if (Arg->isValueDependent()) {
5065 Converted = TemplateArgument(Arg);
5066 return Arg;
5067 }
5068
5069 // C++1z [temp.arg.nontype]p1:
5070 // A template-argument for a non-type template parameter shall be
5071 // a converted constant expression of the type of the template-parameter.
5072 APValue Value;
5073 ExprResult ArgResult = CheckConvertedConstantExpression(
5074 Arg, ParamType, Value, CCEK_TemplateArg);
5075 if (ArgResult.isInvalid())
5076 return ExprError();
5077
Richard Smithd663fdd2014-12-17 20:42:37 +00005078 QualType CanonParamType = Context.getCanonicalType(ParamType);
5079
Richard Smith410cc892014-11-26 03:26:53 +00005080 // Convert the APValue to a TemplateArgument.
5081 switch (Value.getKind()) {
5082 case APValue::Uninitialized:
5083 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005084 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005085 break;
5086 case APValue::Int:
5087 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005088 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005089 break;
5090 case APValue::MemberPointer: {
5091 assert(ParamType->isMemberPointerType());
5092
5093 // FIXME: We need TemplateArgument representation and mangling for these.
5094 if (!Value.getMemberPointerPath().empty()) {
5095 Diag(Arg->getLocStart(),
5096 diag::err_template_arg_member_ptr_base_derived_not_supported)
5097 << Value.getMemberPointerDecl() << ParamType
5098 << Arg->getSourceRange();
5099 return ExprError();
5100 }
5101
5102 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005103 Converted = VD ? TemplateArgument(VD, CanonParamType)
5104 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005105 break;
5106 }
5107 case APValue::LValue: {
5108 // For a non-type template-parameter of pointer or reference type,
5109 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005110 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5111 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005112 // -- a temporary object
5113 // -- a string literal
5114 // -- the result of a typeid expression, or
5115 // -- a predefind __func__ variable
5116 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5117 if (isa<CXXUuidofExpr>(E)) {
5118 Converted = TemplateArgument(const_cast<Expr*>(E));
5119 break;
5120 }
5121 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5122 << Arg->getSourceRange();
5123 return ExprError();
5124 }
5125 auto *VD = const_cast<ValueDecl *>(
5126 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5127 // -- a subobject
5128 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5129 VD && VD->getType()->isArrayType() &&
5130 Value.getLValuePath()[0].ArrayIndex == 0 &&
5131 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5132 // Per defect report (no number yet):
5133 // ... other than a pointer to the first element of a complete array
5134 // object.
5135 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5136 Value.isLValueOnePastTheEnd()) {
5137 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5138 << Value.getAsString(Context, ParamType);
5139 return ExprError();
5140 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005141 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005142 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005143 assert((!VD || !ParamType->isNullPtrType()) &&
5144 "non-null value of type nullptr_t?");
5145 Converted = VD ? TemplateArgument(VD, CanonParamType)
5146 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005147 break;
5148 }
5149 case APValue::AddrLabelDiff:
5150 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5151 case APValue::Float:
5152 case APValue::ComplexInt:
5153 case APValue::ComplexFloat:
5154 case APValue::Vector:
5155 case APValue::Array:
5156 case APValue::Struct:
5157 case APValue::Union:
5158 llvm_unreachable("invalid kind for template argument");
5159 }
5160
5161 return ArgResult.get();
5162 }
5163
Douglas Gregor86560402009-02-10 23:36:10 +00005164 // C++ [temp.arg.nontype]p5:
5165 // The following conversions are performed on each expression used
5166 // as a non-type template-argument. If a non-type
5167 // template-argument cannot be converted to the type of the
5168 // corresponding template-parameter then the program is
5169 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005170 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005171 // C++11:
5172 // -- for a non-type template-parameter of integral or
5173 // enumeration type, conversions permitted in a converted
5174 // constant expression are applied.
5175 //
5176 // C++98:
5177 // -- for a non-type template-parameter of integral or
5178 // enumeration type, integral promotions (4.5) and integral
5179 // conversions (4.7) are applied.
5180
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005181 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005182 // We can't check arbitrary value-dependent arguments.
5183 // FIXME: If there's no viable conversion to the template parameter type,
5184 // we should be able to diagnose that prior to instantiation.
5185 if (Arg->isValueDependent()) {
5186 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005187 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005188 }
5189
5190 // C++ [temp.arg.nontype]p1:
5191 // A template-argument for a non-type, non-template template-parameter
5192 // shall be one of:
5193 //
5194 // -- for a non-type template-parameter of integral or enumeration
5195 // type, a converted constant expression of the type of the
5196 // template-parameter; or
5197 llvm::APSInt Value;
5198 ExprResult ArgResult =
5199 CheckConvertedConstantExpression(Arg, ParamType, Value,
5200 CCEK_TemplateArg);
5201 if (ArgResult.isInvalid())
5202 return ExprError();
5203
5204 // Widen the argument value to sizeof(parameter type). This is almost
5205 // always a no-op, except when the parameter type is bool. In
5206 // that case, this may extend the argument from 1 bit to 8 bits.
5207 QualType IntegerType = ParamType;
5208 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5209 IntegerType = Enum->getDecl()->getIntegerType();
5210 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5211
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005212 Converted = TemplateArgument(Context, Value,
5213 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005214 return ArgResult;
5215 }
5216
Richard Smith08b12f12011-10-27 22:11:44 +00005217 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5218 if (ArgResult.isInvalid())
5219 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005220 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005221
5222 QualType ArgType = Arg->getType();
5223
Douglas Gregor86560402009-02-10 23:36:10 +00005224 // C++ [temp.arg.nontype]p1:
5225 // A template-argument for a non-type, non-template
5226 // template-parameter shall be one of:
5227 //
5228 // -- an integral constant-expression of integral or enumeration
5229 // type; or
5230 // -- the name of a non-type template-parameter; or
5231 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005232 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005233 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005234 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005235 diag::err_template_arg_not_integral_or_enumeral)
5236 << ArgType << Arg->getSourceRange();
5237 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005238 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005239 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005240 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5241 QualType T;
5242
5243 public:
5244 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005245
5246 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5247 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005248 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5249 }
5250 } Diagnoser(ArgType);
5251
5252 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005253 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005254 if (!Arg)
5255 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005256 }
5257
Richard Smithd663fdd2014-12-17 20:42:37 +00005258 // From here on out, all we care about is the unqualified form
5259 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005260 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005261
5262 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005263 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005264 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005265 } else if (ParamType->isBooleanType()) {
5266 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005267 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005268 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5269 !ParamType->isEnumeralType()) {
5270 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005271 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005272 } else {
5273 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005274 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005275 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005276 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005277 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005278 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005279 }
5280
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005281 // Add the value of this argument to the list of converted
5282 // arguments. We use the bitwidth and signedness of the template
5283 // parameter.
5284 if (Arg->isValueDependent()) {
5285 // The argument is value-dependent. Create a new
5286 // TemplateArgument with the converted expression.
5287 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005288 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005289 }
5290
Douglas Gregor52aba872009-03-14 00:20:21 +00005291 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005292 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005293 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005294
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005295 if (ParamType->isBooleanType()) {
5296 // Value must be zero or one.
5297 Value = Value != 0;
5298 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5299 if (Value.getBitWidth() != AllowedBits)
5300 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005301 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005302 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005303 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005304
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005305 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005306 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005307 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005308 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005309 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005310 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005311
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005312 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005313 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005314 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005315 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005316 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5317 << Arg->getSourceRange();
5318 Diag(Param->getLocation(), diag::note_template_param_here);
5319 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005320
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005321 // Complain if we overflowed the template parameter's type.
5322 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005323 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005324 RequiredBits = OldValue.getActiveBits();
5325 else if (OldValue.isUnsigned())
5326 RequiredBits = OldValue.getActiveBits() + 1;
5327 else
5328 RequiredBits = OldValue.getMinSignedBits();
5329 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005330 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005331 diag::warn_template_arg_too_large)
5332 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5333 << Arg->getSourceRange();
5334 Diag(Param->getLocation(), diag::note_template_param_here);
5335 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005336 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005337
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005338 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005339 ParamType->isEnumeralType()
5340 ? Context.getCanonicalType(ParamType)
5341 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005342 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005343 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005344
Richard Smith08b12f12011-10-27 22:11:44 +00005345 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005346 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5347
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005348 // Handle pointer-to-function, reference-to-function, and
5349 // pointer-to-member-function all in (roughly) the same way.
5350 if (// -- For a non-type template-parameter of type pointer to
5351 // function, only the function-to-pointer conversion (4.3) is
5352 // applied. If the template-argument represents a set of
5353 // overloaded functions (or a pointer to such), the matching
5354 // function is selected from the set (13.4).
5355 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005356 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005357 // -- For a non-type template-parameter of type reference to
5358 // function, no conversions apply. If the template-argument
5359 // represents a set of overloaded functions, the matching
5360 // function is selected from the set (13.4).
5361 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005362 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005363 // -- For a non-type template-parameter of type pointer to
5364 // member function, no conversions apply. If the
5365 // template-argument represents a set of overloaded member
5366 // functions, the matching member function is selected from
5367 // the set (13.4).
5368 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005369 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005370 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005371
Douglas Gregor064fdb22010-04-14 23:11:21 +00005372 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005374 true,
5375 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005376 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005377 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005378
5379 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5380 ArgType = Arg->getType();
5381 } else
John Wiegley01296292011-04-08 18:41:53 +00005382 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005384
John Wiegley01296292011-04-08 18:41:53 +00005385 if (!ParamType->isMemberPointerType()) {
5386 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5387 ParamType,
5388 Arg, Converted))
5389 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005390 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005391 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005392
Douglas Gregor20fdef32012-04-10 17:08:25 +00005393 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5394 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005395 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005396 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005397 }
5398
Chris Lattner696197c2009-02-20 21:37:53 +00005399 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005400 // -- for a non-type template-parameter of type pointer to
5401 // object, qualification conversions (4.4) and the
5402 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005403 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005404 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005405 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005406
John Wiegley01296292011-04-08 18:41:53 +00005407 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5408 ParamType,
5409 Arg, Converted))
5410 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005411 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005412 }
Mike Stump11289f42009-09-09 15:08:12 +00005413
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005414 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005415 // -- For a non-type template-parameter of type reference to
5416 // object, no conversions apply. The type referred to by the
5417 // reference may be more cv-qualified than the (otherwise
5418 // identical) type of the template-argument. The
5419 // template-parameter is bound directly to the
5420 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005421 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005422 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005423
Douglas Gregor064fdb22010-04-14 23:11:21 +00005424 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5426 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005427 true,
5428 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005429 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005430 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005431
5432 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5433 ArgType = Arg->getType();
5434 } else
John Wiegley01296292011-04-08 18:41:53 +00005435 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005437
John Wiegley01296292011-04-08 18:41:53 +00005438 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5439 ParamType,
5440 Arg, Converted))
5441 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005442 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005443 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005444
Douglas Gregor20fdef32012-04-10 17:08:25 +00005445 // Deal with parameters of type std::nullptr_t.
5446 if (ParamType->isNullPtrType()) {
5447 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5448 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005449 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005450 }
5451
5452 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5453 case NPV_NotNullPointer:
5454 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5455 << Arg->getType() << ParamType;
5456 Diag(Param->getLocation(), diag::note_template_param_here);
5457 return ExprError();
5458
5459 case NPV_Error:
5460 return ExprError();
5461
5462 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005463 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005464 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5465 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005466 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005467 }
5468 }
5469
Douglas Gregor0e558532009-02-11 16:16:59 +00005470 // -- For a non-type template-parameter of type pointer to data
5471 // member, qualification conversions (4.4) are applied.
5472 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5473
Douglas Gregor20fdef32012-04-10 17:08:25 +00005474 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5475 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005476 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005477 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005478}
5479
5480/// \brief Check a template argument against its corresponding
5481/// template template parameter.
5482///
5483/// This routine implements the semantics of C++ [temp.arg.template].
5484/// It returns true if an error occurred, and false otherwise.
5485bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005486 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005487 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005488 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005489 TemplateDecl *Template = Name.getAsTemplateDecl();
5490 if (!Template) {
5491 // Any dependent template name is fine.
5492 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5493 return false;
5494 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005495
Richard Smith3f1b5d02011-05-05 21:57:07 +00005496 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005497 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005498 // the name of a class template or an alias template, expressed as an
5499 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005500 // primary class templates are considered when matching the
5501 // template template argument with the corresponding parameter;
5502 // partial specializations are not considered even if their
5503 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005504 //
5505 // Note that we also allow template template parameters here, which
5506 // will happen when we are dealing with, e.g., class template
5507 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005508 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005509 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005510 !isa<TypeAliasTemplateDecl>(Template) &&
5511 !isa<BuiltinTemplateDecl>(Template)) {
5512 assert(isa<FunctionTemplateDecl>(Template) &&
5513 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005514 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005515 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5516 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005517 }
5518
Richard Smith1fde8ec2012-09-07 02:06:42 +00005519 TemplateParameterList *Params = Param->getTemplateParameters();
5520 if (Param->isExpandedParameterPack())
5521 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5522
Douglas Gregor85e0f662009-02-10 00:24:35 +00005523 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005524 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005526 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005527 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005528}
5529
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005530/// \brief Given a non-type template argument that refers to a
5531/// declaration and the type of its corresponding non-type template
5532/// parameter, produce an expression that properly refers to that
5533/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005535Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5536 QualType ParamType,
5537 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005538 // C++ [temp.param]p8:
5539 //
5540 // A non-type template-parameter of type "array of T" or
5541 // "function returning T" is adjusted to be of type "pointer to
5542 // T" or "pointer to function returning T", respectively.
5543 if (ParamType->isArrayType())
5544 ParamType = Context.getArrayDecayedType(ParamType);
5545 else if (ParamType->isFunctionType())
5546 ParamType = Context.getPointerType(ParamType);
5547
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005548 // For a NULL non-type template argument, return nullptr casted to the
5549 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005550 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005551 return ImpCastExprToType(
5552 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5553 ParamType,
5554 ParamType->getAs<MemberPointerType>()
5555 ? CK_NullToMemberPointer
5556 : CK_NullToPointer);
5557 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005558 assert(Arg.getKind() == TemplateArgument::Declaration &&
5559 "Only declaration template arguments permitted here");
5560
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005561 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005564 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5565 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005566 // If the value is a class member, we might have a pointer-to-member.
5567 // Determine whether the non-type template template parameter is of
5568 // pointer-to-member type. If so, we need to build an appropriate
5569 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5570 // would refer to the member itself.
5571 if (ParamType->isMemberPointerType()) {
5572 QualType ClassType
5573 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5574 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005575 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005576 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005577 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005578 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005579
5580 // The actual value-ness of this is unimportant, but for
5581 // internal consistency's sake, references to instance methods
5582 // are r-values.
5583 ExprValueKind VK = VK_LValue;
5584 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5585 VK = VK_RValue;
5586
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005588 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005589 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005590 Loc,
5591 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005592 if (RefExpr.isInvalid())
5593 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005594
John McCalle3027922010-08-25 11:45:40 +00005595 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005597 // We might need to perform a trailing qualification conversion, since
5598 // the element type on the parameter could be more qualified than the
5599 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005600 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005601 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005602 ParamType.getUnqualifiedType(), false,
5603 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005604 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005606 assert(!RefExpr.isInvalid() &&
5607 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005608 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005609 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005610 }
5611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005613 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005614
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005615 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005616 // When the non-type template parameter is a pointer, take the
5617 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005618 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005619 if (RefExpr.isInvalid())
5620 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005621
5622 if (T->isFunctionType() || T->isArrayType()) {
5623 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005624 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005625 if (RefExpr.isInvalid())
5626 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005627
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005628 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005629 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005630
Douglas Gregorb242683d2010-04-01 18:32:35 +00005631 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005632 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005633 }
5634
John McCall7decc9e2010-11-18 06:31:45 +00005635 ExprValueKind VK = VK_RValue;
5636
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005637 // If the non-type template parameter has reference type, qualify the
5638 // resulting declaration reference with the extra qualifiers on the
5639 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005640 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5641 VK = VK_LValue;
5642 T = Context.getQualifiedType(T,
5643 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005644 } else if (isa<FunctionDecl>(VD)) {
5645 // References to functions are always lvalues.
5646 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648
John McCall7decc9e2010-11-18 06:31:45 +00005649 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005650}
5651
5652/// \brief Construct a new expression that refers to the given
5653/// integral template argument with the given source-location
5654/// information.
5655///
5656/// This routine takes care of the mapping from an integral template
5657/// argument (which may have any integral type) to the appropriate
5658/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005659ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005660Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5661 SourceLocation Loc) {
5662 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005663 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005664 QualType OrigT = Arg.getIntegralType();
5665
5666 // If this is an enum type that we're instantiating, we need to use an integer
5667 // type the same size as the enumerator. We don't want to build an
5668 // IntegerLiteral with enum type. The integer type of an enum type can be of
5669 // any integral type with C++11 enum classes, make sure we create the right
5670 // type of literal for it.
5671 QualType T = OrigT;
5672 if (const EnumType *ET = OrigT->getAs<EnumType>())
5673 T = ET->getDecl()->getIntegerType();
5674
5675 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005676 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005677 // This does not need to handle u8 character literals because those are
5678 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005679 CharacterLiteral::CharacterKind Kind;
5680 if (T->isWideCharType())
5681 Kind = CharacterLiteral::Wide;
5682 else if (T->isChar16Type())
5683 Kind = CharacterLiteral::UTF16;
5684 else if (T->isChar32Type())
5685 Kind = CharacterLiteral::UTF32;
5686 else
5687 Kind = CharacterLiteral::Ascii;
5688
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005689 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5690 Kind, T, Loc);
5691 } else if (T->isBooleanType()) {
5692 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5693 T, Loc);
5694 } else if (T->isNullPtrType()) {
5695 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5696 } else {
5697 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005698 }
5699
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005700 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005701 // FIXME: This is a hack. We need a better way to handle substituted
5702 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005703 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5704 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005705 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005706 Loc, Loc);
5707 }
5708
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005709 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005710}
5711
Douglas Gregor641040a2011-01-12 23:45:44 +00005712/// \brief Match two template parameters within template parameter lists.
5713static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5714 bool Complain,
5715 Sema::TemplateParameterListEqualKind Kind,
5716 SourceLocation TemplateArgLoc) {
5717 // Check the actual kind (type, non-type, template).
5718 if (Old->getKind() != New->getKind()) {
5719 if (Complain) {
5720 unsigned NextDiag = diag::err_template_param_different_kind;
5721 if (TemplateArgLoc.isValid()) {
5722 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5723 NextDiag = diag::note_template_param_different_kind;
5724 }
5725 S.Diag(New->getLocation(), NextDiag)
5726 << (Kind != Sema::TPL_TemplateMatch);
5727 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5728 << (Kind != Sema::TPL_TemplateMatch);
5729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730
Douglas Gregor641040a2011-01-12 23:45:44 +00005731 return false;
5732 }
5733
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005734 // Check that both are parameter packs are neither are parameter packs.
5735 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005736 // template template parameter, the template template parameter can have
5737 // a parameter pack where the template template argument does not.
5738 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5739 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5740 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005741 if (Complain) {
5742 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5743 if (TemplateArgLoc.isValid()) {
5744 S.Diag(TemplateArgLoc,
5745 diag::err_template_arg_template_params_mismatch);
5746 NextDiag = diag::note_template_parameter_pack_non_pack;
5747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748
Douglas Gregor641040a2011-01-12 23:45:44 +00005749 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5750 : isa<NonTypeTemplateParmDecl>(New)? 1
5751 : 2;
5752 S.Diag(New->getLocation(), NextDiag)
5753 << ParamKind << New->isParameterPack();
5754 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5755 << ParamKind << Old->isParameterPack();
5756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Douglas Gregor641040a2011-01-12 23:45:44 +00005758 return false;
5759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005760
Douglas Gregor641040a2011-01-12 23:45:44 +00005761 // For non-type template parameters, check the type of the parameter.
5762 if (NonTypeTemplateParmDecl *OldNTTP
5763 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5764 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Douglas Gregor641040a2011-01-12 23:45:44 +00005766 // If we are matching a template template argument to a template
5767 // template parameter and one of the non-type template parameter types
5768 // is dependent, then we must wait until template instantiation time
5769 // to actually compare the arguments.
5770 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5771 (OldNTTP->getType()->isDependentType() ||
5772 NewNTTP->getType()->isDependentType()))
5773 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774
Douglas Gregor641040a2011-01-12 23:45:44 +00005775 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5776 if (Complain) {
5777 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5778 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005780 diag::err_template_arg_template_params_mismatch);
5781 NextDiag = diag::note_template_nontype_parm_different_type;
5782 }
5783 S.Diag(NewNTTP->getLocation(), NextDiag)
5784 << NewNTTP->getType()
5785 << (Kind != Sema::TPL_TemplateMatch);
5786 S.Diag(OldNTTP->getLocation(),
5787 diag::note_template_nontype_parm_prev_declaration)
5788 << OldNTTP->getType();
5789 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005790
Douglas Gregor641040a2011-01-12 23:45:44 +00005791 return false;
5792 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005793
Douglas Gregor641040a2011-01-12 23:45:44 +00005794 return true;
5795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005796
Douglas Gregor641040a2011-01-12 23:45:44 +00005797 // For template template parameters, check the template parameter types.
5798 // The template parameter lists of template template
5799 // parameters must agree.
5800 if (TemplateTemplateParmDecl *OldTTP
5801 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005802 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005803 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5804 OldTTP->getTemplateParameters(),
5805 Complain,
5806 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005807 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005808 : Kind),
5809 TemplateArgLoc);
5810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005811
Douglas Gregor641040a2011-01-12 23:45:44 +00005812 return true;
5813}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005814
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005815/// \brief Diagnose a known arity mismatch when comparing template argument
5816/// lists.
5817static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005818void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005819 TemplateParameterList *New,
5820 TemplateParameterList *Old,
5821 Sema::TemplateParameterListEqualKind Kind,
5822 SourceLocation TemplateArgLoc) {
5823 unsigned NextDiag = diag::err_template_param_list_different_arity;
5824 if (TemplateArgLoc.isValid()) {
5825 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5826 NextDiag = diag::note_template_param_list_different_arity;
5827 }
5828 S.Diag(New->getTemplateLoc(), NextDiag)
5829 << (New->size() > Old->size())
5830 << (Kind != Sema::TPL_TemplateMatch)
5831 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5832 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5833 << (Kind != Sema::TPL_TemplateMatch)
5834 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5835}
5836
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005837/// \brief Determine whether the given template parameter lists are
5838/// equivalent.
5839///
Mike Stump11289f42009-09-09 15:08:12 +00005840/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005841/// source code as part of a new template declaration.
5842///
5843/// \param Old The old template parameter list, typically found via
5844/// name lookup of the template declared with this template parameter
5845/// list.
5846///
5847/// \param Complain If true, this routine will produce a diagnostic if
5848/// the template parameter lists are not equivalent.
5849///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005850/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005851///
5852/// \param TemplateArgLoc If this source location is valid, then we
5853/// are actually checking the template parameter list of a template
5854/// argument (New) against the template parameter list of its
5855/// corresponding template template parameter (Old). We produce
5856/// slightly different diagnostics in this scenario.
5857///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005858/// \returns True if the template parameter lists are equal, false
5859/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005860bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005861Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5862 TemplateParameterList *Old,
5863 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005864 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005865 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005866 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5867 if (Complain)
5868 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5869 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005870
5871 return false;
5872 }
5873
Douglas Gregor641040a2011-01-12 23:45:44 +00005874 // C++0x [temp.arg.template]p3:
5875 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005876 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005877 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005878 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005879 // template-parameter-list of P. [...]
5880 TemplateParameterList::iterator NewParm = New->begin();
5881 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005882 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005883 OldParmEnd = Old->end();
5884 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005885 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5886 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005887 if (NewParm == NewParmEnd) {
5888 if (Complain)
5889 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5890 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005891
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005892 return false;
5893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005894
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005895 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5896 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005897 return false;
5898
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005899 ++NewParm;
5900 continue;
5901 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005902
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005903 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005904 // [...] When P's template- parameter-list contains a template parameter
5905 // pack (14.5.3), the template parameter pack will match zero or more
5906 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005907 // template-parameter-list of A with the same type and form as the
5908 // template parameter pack in P (ignoring whether those template
5909 // parameters are template parameter packs).
5910 for (; NewParm != NewParmEnd; ++NewParm) {
5911 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5912 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005913 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005914 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005916
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005917 // Make sure we exhausted all of the arguments.
5918 if (NewParm != NewParmEnd) {
5919 if (Complain)
5920 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5921 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005922
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005923 return false;
5924 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005925
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005926 return true;
5927}
5928
5929/// \brief Check whether a template can be declared within this scope.
5930///
5931/// If the template declaration is valid in this scope, returns
5932/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005933bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005934Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005935 if (!S)
5936 return false;
5937
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005938 // Find the nearest enclosing declaration scope.
5939 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5940 (S->getFlags() & Scope::TemplateParamScope) != 0)
5941 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005942
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005943 // C++ [temp]p4:
5944 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005945 DeclContext *Ctx = S->getEntity();
Alex Lorenz560ae562016-11-02 15:46:34 +00005946 if (Ctx && Ctx->isExternCContext()) {
5947 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5948 << TemplateParams->getSourceRange();
5949 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
5950 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
5951 return true;
5952 }
Richard Smith8df390f2016-09-08 23:14:54 +00005953 Ctx = Ctx->getRedeclContext();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005954
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005955 // C++ [temp]p2:
5956 // A template-declaration can appear only as a namespace scope or
5957 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005958 if (Ctx) {
5959 if (Ctx->isFileContext())
5960 return false;
5961 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5962 // C++ [temp.mem]p2:
5963 // A local class shall not have member templates.
5964 if (RD->isLocalClass())
5965 return Diag(TemplateParams->getTemplateLoc(),
5966 diag::err_template_inside_local_class)
5967 << TemplateParams->getSourceRange();
5968 else
5969 return false;
5970 }
5971 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005972
Mike Stump11289f42009-09-09 15:08:12 +00005973 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005974 diag::err_template_outside_namespace_or_class_scope)
5975 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005976}
Douglas Gregor67a65642009-02-17 23:15:12 +00005977
Douglas Gregor54888652009-10-07 00:13:32 +00005978/// \brief Determine what kind of template specialization the given declaration
5979/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005980static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005981 if (!D)
5982 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005983
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005984 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5985 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005986 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5987 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005988 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5989 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005990
Douglas Gregor54888652009-10-07 00:13:32 +00005991 return TSK_Undeclared;
5992}
5993
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005994/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005995/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005996///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005997/// This routine determines whether a template specialization can be declared
5998/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005999///
6000/// \param S the semantic analysis object for which this check is being
6001/// performed.
6002///
6003/// \param Specialized the entity being specialized or instantiated, which
6004/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006005/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00006006/// member class).
6007///
6008/// \param PrevDecl the previous declaration of this entity, if any.
6009///
6010/// \param Loc the location of the explicit specialization or instantiation of
6011/// this entity.
6012///
6013/// \param IsPartialSpecialization whether this is a partial specialization of
6014/// a class template.
6015///
Douglas Gregor54888652009-10-07 00:13:32 +00006016/// \returns true if there was an error that we cannot recover from, false
6017/// otherwise.
6018static bool CheckTemplateSpecializationScope(Sema &S,
6019 NamedDecl *Specialized,
6020 NamedDecl *PrevDecl,
6021 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006022 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00006023 // Keep these "kind" numbers in sync with the %select statements in the
6024 // various diagnostics emitted by this routine.
6025 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006026 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006027 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006028 else if (isa<VarTemplateDecl>(Specialized))
6029 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00006030 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006031 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006032 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00006033 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006034 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00006035 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00006036 else if (isa<RecordDecl>(Specialized))
6037 EntityKind = 7;
6038 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6039 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00006040 else {
Richard Smith7d137e32012-03-23 03:33:32 +00006041 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006042 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006043 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00006044 return true;
6045 }
6046
Douglas Gregorf47b9112009-02-25 22:02:03 +00006047 // C++ [temp.expl.spec]p2:
6048 // An explicit specialization shall be declared in the namespace
6049 // of which the template is a member, or, for member templates, in
6050 // the namespace of which the enclosing class or enclosing class
6051 // template is a member. An explicit specialization of a member
6052 // function, member class or static data member of a class
6053 // template shall be declared in the namespace of which the class
6054 // template is a member. Such a declaration may also be a
6055 // definition. If the declaration is not a definition, the
6056 // specialization may be defined later in the name- space in which
6057 // the explicit specialization was declared, or in a namespace
6058 // that encloses the one in which the explicit specialization was
6059 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00006060 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00006061 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006062 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006063 return true;
6064 }
Douglas Gregore4b05162009-10-07 17:21:34 +00006065
Douglas Gregor40fb7442009-10-07 17:30:37 +00006066 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006067 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006068 // Do not warn for class scope explicit specialization during
6069 // instantiation, warning was already emitted during pattern
6070 // semantic analysis.
6071 if (!S.ActiveTemplateInstantiations.size())
6072 S.Diag(Loc, diag::ext_function_specialization_in_class)
6073 << Specialized;
6074 } else {
6075 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6076 << Specialized;
6077 return true;
6078 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006080
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006081 if (S.CurContext->isRecord() &&
6082 !S.CurContext->Equals(Specialized->getDeclContext())) {
6083 // Make sure that we're specializing in the right record context.
6084 // Otherwise, things can go horribly wrong.
6085 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6086 << Specialized;
6087 return true;
6088 }
6089
Douglas Gregore4b05162009-10-07 17:21:34 +00006090 // C++ [temp.class.spec]p6:
6091 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006092 // in any namespace scope in which its definition may be defined (14.5.1
6093 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006094 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006095 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006096 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006097
6098 // Make sure that this redeclaration (or definition) occurs in an enclosing
6099 // namespace.
6100 // Note that HandleDeclarator() performs this check for explicit
6101 // specializations of function templates, static data members, and member
6102 // functions, so we skip the check here for those kinds of entities.
6103 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6104 // Should we refactor that check, so that it occurs later?
6105 if (!DC->Encloses(SpecializedContext) &&
6106 !(isa<FunctionTemplateDecl>(Specialized) ||
6107 isa<FunctionDecl>(Specialized) ||
6108 isa<VarTemplateDecl>(Specialized) ||
6109 isa<VarDecl>(Specialized))) {
6110 if (isa<TranslationUnitDecl>(SpecializedContext))
6111 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6112 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006113 else if (isa<NamespaceDecl>(SpecializedContext)) {
6114 int Diag = diag::err_template_spec_redecl_out_of_scope;
6115 if (S.getLangOpts().MicrosoftExt)
6116 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6117 S.Diag(Loc, Diag) << EntityKind << Specialized
6118 << cast<NamedDecl>(SpecializedContext);
6119 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006120 llvm_unreachable("unexpected namespace context for specialization");
6121
6122 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6123 } else if ((!PrevDecl ||
6124 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6125 getTemplateSpecializationKind(PrevDecl) ==
6126 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006127 // C++ [temp.exp.spec]p2:
6128 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006130 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006131 // An explicit specialization of a member function, member class or
6132 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006133 // namespace of which the class template is a member.
6134 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006135 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006136 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006137 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006138 // C++11 [temp.explicit]p3:
6139 // An explicit instantiation shall appear in an enclosing namespace of its
6140 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006141 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006142 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006143 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006144 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006145 "DC encloses TU but isn't in enclosing namespace set");
6146 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006147 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006148 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6149 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006150 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006151 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006152 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006153 Diag = diag::ext_template_spec_decl_out_of_scope;
6154 else
6155 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6156 S.Diag(Loc, Diag)
6157 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006159
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006160 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006161 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006163
Douglas Gregorf47b9112009-02-25 22:02:03 +00006164 return false;
6165}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006166
Richard Smith6056d5e2014-02-09 00:54:43 +00006167static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6168 if (!E->isInstantiationDependent())
6169 return SourceLocation();
6170 DependencyChecker Checker(Depth);
6171 Checker.TraverseStmt(E);
6172 if (Checker.Match && Checker.MatchLoc.isInvalid())
6173 return E->getSourceRange();
6174 return Checker.MatchLoc;
6175}
6176
6177static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6178 if (!TL.getType()->isDependentType())
6179 return SourceLocation();
6180 DependencyChecker Checker(Depth);
6181 Checker.TraverseTypeLoc(TL);
6182 if (Checker.Match && Checker.MatchLoc.isInvalid())
6183 return TL.getSourceRange();
6184 return Checker.MatchLoc;
6185}
6186
Larisse Voufo39a1e502013-08-06 01:03:05 +00006187/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006188/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006189static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006190 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6191 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006192 for (unsigned I = 0; I != NumArgs; ++I) {
6193 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006194 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006195 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6196 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006197 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006198
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006199 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006201
Eli Friedmanb826a002012-09-26 02:36:12 +00006202 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006203 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006204
6205 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006206
Douglas Gregor98318c22011-01-03 21:37:45 +00006207 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006208 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6209 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006210
6211 // Strip off any implicit casts we added as part of type checking.
6212 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6213 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006214
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006215 // C++ [temp.class.spec]p8:
6216 // A non-type argument is non-specialized if it is the name of a
6217 // non-type parameter. All other non-type arguments are
6218 // specialized.
6219 //
6220 // Below, we check the two conditions that only apply to
6221 // specialized non-type arguments, so skip any non-specialized
6222 // arguments.
6223 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006224 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006225 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006226
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006227 // C++ [temp.class.spec]p9:
6228 // Within the argument list of a class template partial
6229 // specialization, the following restrictions apply:
6230 // -- A partially specialized non-type argument expression
6231 // shall not involve a template parameter of the partial
6232 // specialization except when the argument expression is a
6233 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006234 SourceRange ParamUseRange =
6235 findTemplateParameter(Param->getDepth(), ArgExpr);
6236 if (ParamUseRange.isValid()) {
6237 if (IsDefaultArgument) {
6238 S.Diag(TemplateNameLoc,
6239 diag::err_dependent_non_type_arg_in_partial_spec);
6240 S.Diag(ParamUseRange.getBegin(),
6241 diag::note_dependent_non_type_default_arg_in_partial_spec)
6242 << ParamUseRange;
6243 } else {
6244 S.Diag(ParamUseRange.getBegin(),
6245 diag::err_dependent_non_type_arg_in_partial_spec)
6246 << ParamUseRange;
6247 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006248 return true;
6249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006250
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006251 // -- The type of a template parameter corresponding to a
6252 // specialized non-type argument shall not be dependent on a
6253 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006254 //
6255 // FIXME: We need to delay this check until instantiation in some cases:
6256 //
6257 // template<template<typename> class X> struct A {
6258 // template<typename T, X<T> N> struct B;
6259 // template<typename T> struct B<T, 0>;
6260 // };
6261 // template<typename> using X = int;
6262 // A<X>::B<int, 0> b;
6263 ParamUseRange = findTemplateParameter(
6264 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6265 if (ParamUseRange.isValid()) {
6266 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6267 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6268 << Param->getType() << ParamUseRange;
6269 S.Diag(Param->getLocation(), diag::note_template_param_here)
6270 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006271 return true;
6272 }
6273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006275 return false;
6276}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006277
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006278/// \brief Check the non-type template arguments of a class template
6279/// partial specialization according to C++ [temp.class.spec]p9.
6280///
Richard Smith6056d5e2014-02-09 00:54:43 +00006281/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006282/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006283/// template.
6284/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006285/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006286/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006287///
Richard Smith6056d5e2014-02-09 00:54:43 +00006288/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006289static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006290 Sema &S, SourceLocation TemplateNameLoc,
6291 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006292 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006293 const TemplateArgument *ArgList = TemplateArgs.data();
6294
6295 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6296 NonTypeTemplateParmDecl *Param
6297 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6298 if (!Param)
6299 continue;
6300
Richard Smith6056d5e2014-02-09 00:54:43 +00006301 if (CheckNonTypeTemplatePartialSpecializationArgs(
6302 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006303 return true;
6304 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006305
6306 return false;
6307}
6308
John McCall48871652010-08-21 09:40:31 +00006309DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006310Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6311 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006312 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006313 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006314 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006315 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006316 MultiTemplateParamsArg
6317 TemplateParameterLists,
6318 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006319 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006320
Richard Smith4b55a9c2014-04-17 03:29:33 +00006321 CXXScopeSpec &SS = TemplateId.SS;
6322
Abramo Bagnara60804e12011-03-18 15:16:37 +00006323 // NOTE: KWLoc is the location of the tag keyword. This will instead
6324 // store the location of the outermost template keyword in the declaration.
6325 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006326 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6327 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6328 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6329 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006330
Douglas Gregor67a65642009-02-17 23:15:12 +00006331 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006332 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006333 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006334 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6335
6336 if (!ClassTemplate) {
6337 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006338 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006339 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6340 return true;
6341 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006342
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006343 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006344 bool isPartialSpecialization = false;
6345
Douglas Gregorf47b9112009-02-25 22:02:03 +00006346 // Check the validity of the template headers that introduce this
6347 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006348 // FIXME: We probably shouldn't complain about these headers for
6349 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006350 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006351 TemplateParameterList *TemplateParams =
6352 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006353 KWLoc, TemplateNameLoc, SS, &TemplateId,
6354 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6355 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006356 if (Invalid)
6357 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006358
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006359 if (TemplateParams && TemplateParams->size() > 0) {
6360 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006361
Douglas Gregorec9518b2010-12-21 08:14:57 +00006362 if (TUK == TUK_Friend) {
6363 Diag(KWLoc, diag::err_partial_specialization_friend)
6364 << SourceRange(LAngleLoc, RAngleLoc);
6365 return true;
6366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006368 // C++ [temp.class.spec]p10:
6369 // The template parameter list of a specialization shall not
6370 // contain default template argument values.
6371 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6372 Decl *Param = TemplateParams->getParam(I);
6373 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6374 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006375 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006376 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006377 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006378 }
6379 } else if (NonTypeTemplateParmDecl *NTTP
6380 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6381 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006382 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006383 diag::err_default_arg_in_partial_spec)
6384 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006385 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006386 }
6387 } else {
6388 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006389 if (TTP->hasDefaultArgument()) {
6390 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006391 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006392 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006393 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006394 }
6395 }
6396 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006397 } else if (TemplateParams) {
6398 if (TUK == TUK_Friend)
6399 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006400 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006401 SourceRange(TemplateParams->getTemplateLoc(),
6402 TemplateParams->getRAngleLoc()))
6403 << SourceRange(LAngleLoc, RAngleLoc);
6404 else
6405 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006406 } else {
6407 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006408 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006409
Douglas Gregor67a65642009-02-17 23:15:12 +00006410 // Check that the specialization uses the same tag kind as the
6411 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006412 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6413 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006414 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006415 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006416 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006417 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006418 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006419 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006420 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006421 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006422 diag::note_previous_use);
6423 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6424 }
6425
Douglas Gregorc40290e2009-03-09 23:48:35 +00006426 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006427 TemplateArgumentListInfo TemplateArgs =
6428 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006429
Douglas Gregor14406932011-01-03 20:35:03 +00006430 // Check for unexpanded parameter packs in any of the template arguments.
6431 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006432 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006433 UPPC_PartialSpecialization))
6434 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006435
Douglas Gregor67a65642009-02-17 23:15:12 +00006436 // Check that the template argument list is well-formed for this
6437 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006438 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006439 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6440 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006441 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006442
Douglas Gregor2373c592009-05-31 09:31:02 +00006443 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006444 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006445 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006446 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006447 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6448 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006449 return true;
6450
Douglas Gregor678d76c2011-07-01 01:22:09 +00006451 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006453 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006454 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006455 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6456 << ClassTemplate->getDeclName();
6457 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006458 }
6459 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006460
Craig Topperc3ec1492014-05-26 06:22:03 +00006461 void *InsertPos = nullptr;
6462 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006463
6464 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006465 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006466 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006467 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006468 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006469
Craig Topperc3ec1492014-05-26 06:22:03 +00006470 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006471
Douglas Gregorf47b9112009-02-25 22:02:03 +00006472 // Check whether we can declare a class template specialization in
6473 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006474 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006475 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6476 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006477 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006478 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479
Douglas Gregor15301382009-07-30 17:40:51 +00006480 // The canonical type
6481 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006482 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006483 // Build the canonical type that describes the converted template
6484 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006485 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6486 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006487 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006488
6489 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006490 ClassTemplate->getInjectedClassNameSpecialization())) {
6491 // C++ [temp.class.spec]p9b3:
6492 //
6493 // -- The argument list of the specialization shall not be identical
6494 // to the implicit argument list of the primary template.
6495 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006496 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006497 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006498 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6499 ClassTemplate->getIdentifier(),
6500 TemplateNameLoc,
6501 Attr,
6502 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006503 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006504 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006505 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006506 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006507 }
Douglas Gregor15301382009-07-30 17:40:51 +00006508
Douglas Gregor2373c592009-05-31 09:31:02 +00006509 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006510 ClassTemplatePartialSpecializationDecl *PrevPartial
6511 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006512 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006513 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006514 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006515 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006516 TemplateParams,
6517 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006518 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006519 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006520 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006521 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006522 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006523 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006524 Partial->setTemplateParameterListsInfo(
6525 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006526 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006527
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006528 if (!PrevPartial)
6529 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006530 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006531
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006533 // template specialization, make a note of that.
6534 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6535 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006536
Douglas Gregor91772d12009-06-13 00:26:55 +00006537 // Check that all of the template parameters of the class template
6538 // partial specialization are deducible from the template
6539 // arguments. If not, this class template partial specialization
6540 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006541 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006542 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006543 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006544 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006545
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006546 if (!DeducibleParams.all()) {
6547 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006548 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006549 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006550 << SourceRange(TemplateNameLoc, RAngleLoc);
6551 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6552 if (!DeducibleParams[I]) {
6553 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6554 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006555 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006556 diag::note_partial_spec_unused_parameter)
6557 << Param->getDeclName();
6558 else
Mike Stump11289f42009-09-09 15:08:12 +00006559 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006560 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006561 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006562 }
6563 }
6564 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006565 } else {
6566 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006567 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006568 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006569 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006570 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006571 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006572 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006573 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006574 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006575 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006576 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006577 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006578 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006579 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006580
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006581 if (!PrevDecl)
6582 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006583
David Majnemer678f50b2015-11-18 19:49:19 +00006584 if (CurContext->isDependentContext()) {
6585 // -fms-extensions permits specialization of nested classes without
6586 // fully specializing the outer class(es).
6587 assert(getLangOpts().MicrosoftExt &&
6588 "Only possible with -fms-extensions!");
6589 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6590 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006591 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006592 } else {
6593 CanonType = Context.getTypeDeclType(Specialization);
6594 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006595 }
6596
Douglas Gregor06db9f52009-10-12 20:18:28 +00006597 // C++ [temp.expl.spec]p6:
6598 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006600 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006602 // use occurs; no diagnostic is required.
6603 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006604 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006605 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006606 // Is there any previous explicit specialization declaration?
6607 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6608 Okay = true;
6609 break;
6610 }
6611 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006612
Douglas Gregorc854c662010-02-26 06:03:23 +00006613 if (!Okay) {
6614 SourceRange Range(TemplateNameLoc, RAngleLoc);
6615 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6616 << Context.getTypeDeclType(Specialization) << Range;
6617
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006619 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006620 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006621 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006622 return true;
6623 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625
Douglas Gregor2208a292009-09-26 20:57:03 +00006626 // If this is not a friend, note that this is an explicit specialization.
6627 if (TUK != TUK_Friend)
6628 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006629
6630 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006631 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006632 RecordDecl *Def = Specialization->getDefinition();
6633 NamedDecl *Hidden = nullptr;
6634 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6635 SkipBody->ShouldSkip = true;
6636 makeMergedDefinitionVisible(Hidden, KWLoc);
6637 // From here on out, treat this as just a redeclaration.
6638 TUK = TUK_Declaration;
6639 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006640 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006641 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006642 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006643 Diag(Def->getLocation(), diag::note_previous_definition);
6644 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006645 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006646 }
6647 }
6648
John McCall659a3372010-12-18 03:30:47 +00006649 if (Attr)
6650 ProcessDeclAttributeList(S, Specialization, Attr);
6651
Richard Smith034b94a2012-08-17 03:20:55 +00006652 // Add alignment attributes if necessary; these attributes are checked when
6653 // the ASTContext lays out the structure.
6654 if (TUK == TUK_Definition) {
6655 AddAlignmentAttributesForRecord(Specialization);
6656 AddMsStructLayoutForRecord(Specialization);
6657 }
6658
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006659 if (ModulePrivateLoc.isValid())
6660 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6661 << (isPartialSpecialization? 1 : 0)
6662 << FixItHint::CreateRemoval(ModulePrivateLoc);
6663
Douglas Gregord56a91e2009-02-26 22:19:44 +00006664 // Build the fully-sugared type for this class template
6665 // specialization as the user wrote in the specialization
6666 // itself. This means that we'll pretty-print the type retrieved
6667 // from the specialization's declaration the way that the user
6668 // actually wrote the specialization, rather than formatting the
6669 // name based on the "canonical" representation used to store the
6670 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006671 TypeSourceInfo *WrittenTy
6672 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6673 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006674 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006675 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006676 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006677 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006678
Douglas Gregor1e249f82009-02-25 22:18:32 +00006679 // C++ [temp.expl.spec]p9:
6680 // A template explicit specialization is in the scope of the
6681 // namespace in which the template was defined.
6682 //
6683 // We actually implement this paragraph where we set the semantic
6684 // context (in the creation of the ClassTemplateSpecializationDecl),
6685 // but we also maintain the lexical context where the actual
6686 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006687 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006688
Douglas Gregor67a65642009-02-17 23:15:12 +00006689 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006690 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006691 Specialization->startDefinition();
6692
Douglas Gregor2208a292009-09-26 20:57:03 +00006693 if (TUK == TUK_Friend) {
6694 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6695 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006696 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006697 /*FIXME:*/KWLoc);
6698 Friend->setAccess(AS_public);
6699 CurContext->addDecl(Friend);
6700 } else {
6701 // Add the specialization into its lexical context, so that it can
6702 // be seen when iterating through the list of declarations in that
6703 // context. However, specializations are not found by name lookup.
6704 CurContext->addDecl(Specialization);
6705 }
John McCall48871652010-08-21 09:40:31 +00006706 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006707}
Douglas Gregor333489b2009-03-27 23:10:48 +00006708
John McCall48871652010-08-21 09:40:31 +00006709Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006710 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006711 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006712 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006713 ActOnDocumentableDecl(NewDecl);
6714 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006715}
6716
John McCall4f7ced62010-02-11 01:33:53 +00006717/// \brief Strips various properties off an implicit instantiation
6718/// that has just been explicitly specialized.
6719static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006720 D->dropAttr<DLLImportAttr>();
6721 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006722
Nico Webere4974382014-12-19 23:52:45 +00006723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006724 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006725}
6726
Nico Webera8f80b32012-01-09 19:52:25 +00006727/// \brief Compute the diagnostic location for an explicit instantiation
6728// declaration or definition.
6729static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006730 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006731 // Explicit instantiations following a specialization have no effect and
6732 // hence no PointOfInstantiation. In that case, walk decl backwards
6733 // until a valid name loc is found.
6734 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006735 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6736 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006737 PrevDiagLoc = Prev->getLocation();
6738 }
6739 assert(PrevDiagLoc.isValid() &&
6740 "Explicit instantiation without point of instantiation?");
6741 return PrevDiagLoc;
6742}
6743
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006744/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006745/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006746/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006747/// new specialization/instantiation will have any effect.
6748///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006749/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006750/// instantiation.
6751///
6752/// \param NewTSK the kind of the new explicit specialization or instantiation.
6753///
6754/// \param PrevDecl the previous declaration of the entity.
6755///
6756/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6757///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006758/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006759/// declaration was instantiated (either implicitly or explicitly).
6760///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006762/// specialization or instantiation has no effect and should be ignored.
6763///
6764/// \returns true if there was an error that should prevent the introduction of
6765/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006766bool
6767Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6768 TemplateSpecializationKind NewTSK,
6769 NamedDecl *PrevDecl,
6770 TemplateSpecializationKind PrevTSK,
6771 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006772 bool &HasNoEffect) {
6773 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006774
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006775 switch (NewTSK) {
6776 case TSK_Undeclared:
6777 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006778 assert(
6779 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6780 "previous declaration must be implicit!");
6781 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006782
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006783 case TSK_ExplicitSpecialization:
6784 switch (PrevTSK) {
6785 case TSK_Undeclared:
6786 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006787 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006788 // explicitly specialized or has merely been mentioned without any
6789 // instantiation.
6790 return false;
6791
6792 case TSK_ImplicitInstantiation:
6793 if (PrevPointOfInstantiation.isInvalid()) {
6794 // The declaration itself has not actually been instantiated, so it is
6795 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006796 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006797 return false;
6798 }
6799 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006801 case TSK_ExplicitInstantiationDeclaration:
6802 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006803 assert((PrevTSK == TSK_ImplicitInstantiation ||
6804 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006805 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006806
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006807 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006808 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006809 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006811 // implicit instantiation to take place, in every translation unit in
6812 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006813 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006814 // Is there any previous explicit specialization declaration?
6815 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6816 return false;
6817 }
6818
Douglas Gregor1d957a32009-10-27 18:42:08 +00006819 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006820 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006821 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006822 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006824 return true;
6825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006826
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006827 case TSK_ExplicitInstantiationDeclaration:
6828 switch (PrevTSK) {
6829 case TSK_ExplicitInstantiationDeclaration:
6830 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006831 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006832 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006833
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006834 case TSK_Undeclared:
6835 case TSK_ImplicitInstantiation:
6836 // We're explicitly instantiating something that may have already been
6837 // implicitly instantiated; that's fine.
6838 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006840 case TSK_ExplicitSpecialization:
6841 // C++0x [temp.explicit]p4:
6842 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006844 // specialization for that template, the explicit instantiation has no
6845 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006846 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006847 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006848
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006849 case TSK_ExplicitInstantiationDefinition:
6850 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006851 // If an entity is the subject of both an explicit instantiation
6852 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006853 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006855 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006856
6857 // Explicit instantiations following a specialization have no effect and
6858 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6859 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006860 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6861 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006862 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006863 return false;
6864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006865
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006866 case TSK_ExplicitInstantiationDefinition:
6867 switch (PrevTSK) {
6868 case TSK_Undeclared:
6869 case TSK_ImplicitInstantiation:
6870 // We're explicitly instantiating something that may have already been
6871 // implicitly instantiated; that's fine.
6872 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006874 case TSK_ExplicitSpecialization:
6875 // C++ DR 259, C++0x [temp.explicit]p4:
6876 // For a given set of template parameters, if an explicit
6877 // instantiation of a template appears after a declaration of
6878 // an explicit specialization for that template, the explicit
6879 // instantiation has no effect.
Richard Smithe4caa482016-08-31 23:23:25 +00006880 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006881 << PrevDecl;
6882 Diag(PrevDecl->getLocation(),
6883 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006884 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006885 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006887 case TSK_ExplicitInstantiationDeclaration:
6888 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006890
6891 // C++0x [temp.explicit]p4:
6892 // For a given set of template parameters, if an explicit instantiation
6893 // of a template appears after a declaration of an explicit
6894 // specialization for that template, the explicit instantiation has no
6895 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006896 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006897 // Is there any previous explicit specialization declaration?
6898 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6899 HasNoEffect = true;
6900 break;
6901 }
6902 }
6903
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006904 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006906 case TSK_ExplicitInstantiationDefinition:
6907 // C++0x [temp.spec]p5:
6908 // For a given template and a given set of template-arguments,
6909 // - an explicit instantiation definition shall appear at most once
6910 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006911
6912 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6913 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006914 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006915 : diag::err_explicit_instantiation_duplicate)
6916 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006917 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006918 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006919 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006920 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006921 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006923
David Blaikie83d382b2011-09-23 05:06:16 +00006924 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006925}
6926
John McCallb9c78482010-04-08 09:05:18 +00006927/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006928/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006929///
James Dennettf14a6e52012-06-15 22:23:43 +00006930/// The only possible way to get a dependent function template specialization
6931/// is with a friend declaration, like so:
6932///
6933/// \code
6934/// template \<class T> void foo(T);
6935/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006936/// friend void foo<>(T);
6937/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006938/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006939///
6940/// There really isn't any useful analysis we can do here, so we
6941/// just store the information.
6942bool
6943Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6944 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6945 LookupResult &Previous) {
6946 // Remove anything from Previous that isn't a function template in
6947 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006948 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006949 LookupResult::Filter F = Previous.makeFilter();
6950 while (F.hasNext()) {
6951 NamedDecl *D = F.next()->getUnderlyingDecl();
6952 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006953 !FDLookupContext->InEnclosingNamespaceSetOf(
6954 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006955 F.erase();
6956 }
6957 F.done();
6958
6959 // Should this be diagnosed here?
6960 if (Previous.empty()) return true;
6961
6962 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6963 ExplicitTemplateArgs);
6964 return false;
6965}
6966
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006967/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006968/// specialization.
6969///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006970/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006971/// explicit function template specialization. On successful completion,
6972/// the function declaration \p FD will become a function template
6973/// specialization.
6974///
6975/// \param FD the function declaration, which will be updated to become a
6976/// function template specialization.
6977///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006978/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6979/// if any. Note that this may be valid info even when 0 arguments are
6980/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6981/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006982///
Francois Pichet3a44e432011-07-08 06:21:47 +00006983/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006984/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006985bool Sema::CheckFunctionTemplateSpecialization(
6986 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6987 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006988 // The set of function template specializations that could match this
6989 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006990 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006991 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6992 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006994 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6995 ConvertedTemplateArgs;
6996
Sebastian Redl50c68252010-08-31 00:36:30 +00006997 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006998 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6999 I != E; ++I) {
7000 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7001 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007003 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00007004 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7005 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007006 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007007
Richard Smith574f4f62013-01-14 05:37:29 +00007008 // When matching a constexpr member function template specialization
7009 // against the primary template, we don't yet know whether the
7010 // specialization has an implicit 'const' (because we don't know whether
7011 // it will be a static member function until we know which template it
7012 // specializes), so adjust it now assuming it specializes this template.
7013 QualType FT = FD->getType();
7014 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007015 CXXMethodDecl *OldMD =
7016 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00007017 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00007018 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00007019 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7020 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007021 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007022 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00007023 }
7024 }
7025
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007026 TemplateArgumentListInfo Args;
7027 if (ExplicitTemplateArgs)
7028 Args = *ExplicitTemplateArgs;
7029
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007030 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007031 // A trailing template-argument can be left unspecified in the
7032 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007033 // provided it can be deduced from the function argument type.
7034 // Perform template argument deduction to determine whether we may be
7035 // specializing this template.
7036 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00007037 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007038 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00007039 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7040 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00007041 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7042 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007043 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007044 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00007045 FailedCandidates.addCandidate().set(
7046 I.getPair(), FunTmpl->getTemplatedDecl(),
7047 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007048 (void)TDK;
7049 continue;
7050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007051
Artem Belevich64135c32016-12-08 19:38:13 +00007052 // Target attributes are part of the cuda function signature, so
7053 // the deduced template's cuda target must match that of the
7054 // specialization. Given that C++ template deduction does not
7055 // take target attributes into account, we reject candidates
7056 // here that have a different target.
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007057 if (LangOpts.CUDA &&
Artem Belevich64135c32016-12-08 19:38:13 +00007058 IdentifyCUDATarget(Specialization,
7059 /* IgnoreImplicitHDAttributes = */ true) !=
7060 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
Artem Belevich13e9b4d2016-12-07 19:27:16 +00007061 FailedCandidates.addCandidate().set(
7062 I.getPair(), FunTmpl->getTemplatedDecl(),
7063 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7064 continue;
7065 }
7066
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007067 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007068 if (ExplicitTemplateArgs)
7069 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00007070 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007071 }
7072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007073
Douglas Gregor5de279c2009-09-26 03:41:46 +00007074 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007075 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007076 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007077 FD->getLocation(),
7078 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7079 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00007080 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007081 PDiag(diag::note_function_template_spec_matched));
7082
John McCall58cc69d2010-01-27 01:50:18 +00007083 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007084 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007085
7086 // Ignore access information; it doesn't figure into redeclaration checking.
7087 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007088
Nathan Wilson83839122016-04-09 02:55:27 +00007089 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7090 // an explicit specialization (14.8.3) [...] of a concept definition.
7091 if (Specialization->getPrimaryTemplate()->isConcept()) {
7092 Diag(FD->getLocation(), diag::err_concept_specialized)
7093 << 0 /*function*/ << 1 /*explicitly specialized*/;
7094 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7095 return true;
7096 }
7097
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007098 FunctionTemplateSpecializationInfo *SpecInfo
7099 = Specialization->getTemplateSpecializationInfo();
7100 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007101
7102 // Note: do not overwrite location info if previous template
7103 // specialization kind was explicit.
7104 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007105 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007106 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007107 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7108 // function can differ from the template declaration with respect to
7109 // the constexpr specifier.
7110 Specialization->setConstexpr(FD->isConstexpr());
7111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007113 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007114 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007115
7116 // If this is a friend declaration, then we're not really declaring
7117 // an explicit specialization.
7118 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119
Douglas Gregor54888652009-10-07 00:13:32 +00007120 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007121 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007122 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007123 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007124 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007125 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007126 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007127
7128 // C++ [temp.expl.spec]p6:
7129 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007131 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007132 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007133 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007134 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007135 if (!isFriend &&
7136 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007137 TSK_ExplicitSpecialization,
7138 Specialization,
7139 SpecInfo->getTemplateSpecializationKind(),
7140 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007141 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007142 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007143
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007144 // Mark the prior declaration as an explicit specialization, so that later
7145 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007146 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007147 // Since explicit specializations do not inherit '=delete' from their
7148 // primary function template - check if the 'specialization' that was
7149 // implicitly generated (during template argument deduction for partial
7150 // ordering) from the most specialized of all the function templates that
7151 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7152 // first check that it was implicitly generated during template argument
7153 // deduction by making sure it wasn't referenced, and then reset the deleted
7154 // flag to not-deleted, so that we can inherit that information from 'FD'.
7155 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7156 !Specialization->getCanonicalDecl()->isReferenced()) {
7157 assert(
7158 Specialization->getCanonicalDecl() == Specialization &&
7159 "This must be the only existing declaration of this specialization");
7160 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007161 }
John McCall816d75b2010-03-24 07:46:06 +00007162 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007163 MarkUnusedFileScopedDecl(Specialization);
7164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007165
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007166 // Turn the given function declaration into a function template
7167 // specialization, with the template arguments from the previous
7168 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007169 // Take copies of (semantic and syntactic) template argument lists.
7170 const TemplateArgumentList* TemplArgs = new (Context)
7171 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007172 FD->setFunctionTemplateSpecialization(
7173 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7174 SpecInfo->getTemplateSpecializationKind(),
7175 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007176
Artem Belevich64135c32016-12-08 19:38:13 +00007177 // A function template specialization inherits the target attributes
7178 // of its template. (We require the attributes explicitly in the
7179 // code to match, but a template may have implicit attributes by
7180 // virtue e.g. of being constexpr, and it passes these implicit
7181 // attributes on to its specializations.)
7182 if (LangOpts.CUDA)
7183 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7184
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007185 // The "previous declaration" for this function template specialization is
7186 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007187 Previous.clear();
7188 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007189 return false;
7190}
7191
Douglas Gregor86d142a2009-10-08 07:24:58 +00007192/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007193/// specialization.
7194///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007195/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007196/// explicit member function specialization. On successful completion,
7197/// the function declaration \p FD will become a member function
7198/// specialization.
7199///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007200/// \param Member the member declaration, which will be updated to become a
7201/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007202///
John McCall1f82f242009-11-18 22:49:29 +00007203/// \param Previous the set of declarations, one of which may be specialized
7204/// by this function specialization; the set will be modified to contain the
7205/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007206bool
John McCall1f82f242009-11-18 22:49:29 +00007207Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007208 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007209
Douglas Gregor86d142a2009-10-08 07:24:58 +00007210 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007211 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007212 NamedDecl *Instantiation = nullptr;
7213 NamedDecl *InstantiatedFrom = nullptr;
7214 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007215
John McCall1f82f242009-11-18 22:49:29 +00007216 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007217 // Nowhere to look anyway.
7218 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007219 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7220 I != E; ++I) {
7221 NamedDecl *D = (*I)->getUnderlyingDecl();
7222 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007223 QualType Adjusted = Function->getType();
7224 if (!hasExplicitCallingConv(Adjusted))
7225 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7226 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007227 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007228 Instantiation = Method;
7229 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007230 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007231 break;
7232 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007233 }
7234 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007235 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007236 VarDecl *PrevVar;
7237 if (Previous.isSingleResult() &&
7238 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007239 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007240 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007241 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007242 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007243 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007244 }
7245 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007246 CXXRecordDecl *PrevRecord;
7247 if (Previous.isSingleResult() &&
7248 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007249 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007250 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007251 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007252 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007253 }
Richard Smith7d137e32012-03-23 03:33:32 +00007254 } else if (isa<EnumDecl>(Member)) {
7255 EnumDecl *PrevEnum;
7256 if (Previous.isSingleResult() &&
7257 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007258 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007259 Instantiation = PrevEnum;
7260 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7261 MSInfo = PrevEnum->getMemberSpecializationInfo();
7262 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007264
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007265 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007266 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007267 // specializations are always out-of-line, the caller will complain about
7268 // this mismatch later.
7269 return false;
7270 }
John McCalle820e5e2010-04-13 20:37:33 +00007271
7272 // If this is a friend, just bail out here before we start turning
7273 // things into explicit specializations.
7274 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7275 // Preserve instantiation information.
7276 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7277 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7278 cast<CXXMethodDecl>(InstantiatedFrom),
7279 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7280 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7281 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7282 cast<CXXRecordDecl>(InstantiatedFrom),
7283 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7284 }
7285
7286 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007287 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007288 return false;
7289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290
Douglas Gregor86d142a2009-10-08 07:24:58 +00007291 // Make sure that this is a specialization of a member.
7292 if (!InstantiatedFrom) {
7293 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7294 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007295 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7296 return true;
7297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007298
Douglas Gregor06db9f52009-10-12 20:18:28 +00007299 // C++ [temp.expl.spec]p6:
7300 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007301 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007302 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007303 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007304 // use occurs; no diagnostic is required.
7305 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007306
Abramo Bagnara8075c852010-06-12 07:44:57 +00007307 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007308 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7309 TSK_ExplicitSpecialization,
7310 Instantiation,
7311 MSInfo->getTemplateSpecializationKind(),
7312 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007313 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007314 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007315
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007316 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007317 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007318 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007319 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007320 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007321 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007322
Douglas Gregor86d142a2009-10-08 07:24:58 +00007323 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007324 // the original declaration to note that it is an explicit specialization
7325 // (if it was previously an implicit instantiation). This latter step
7326 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007327 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007328 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7329 if (InstantiationFunction->getTemplateSpecializationKind() ==
7330 TSK_ImplicitInstantiation) {
7331 InstantiationFunction->setTemplateSpecializationKind(
7332 TSK_ExplicitSpecialization);
7333 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007334 // Explicit specializations of member functions of class templates do not
7335 // inherit '=delete' from the member function they are specializing.
7336 if (InstantiationFunction->isDeleted()) {
7337 assert(InstantiationFunction->getCanonicalDecl() ==
7338 InstantiationFunction);
Richard Smith5f274382016-09-28 23:55:27 +00007339 InstantiationFunction->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007340 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007342
Douglas Gregor86d142a2009-10-08 07:24:58 +00007343 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7344 cast<CXXMethodDecl>(InstantiatedFrom),
7345 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007346 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007347 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007348 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7349 if (InstantiationVar->getTemplateSpecializationKind() ==
7350 TSK_ImplicitInstantiation) {
7351 InstantiationVar->setTemplateSpecializationKind(
7352 TSK_ExplicitSpecialization);
7353 InstantiationVar->setLocation(Member->getLocation());
7354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007355
Larisse Voufo39a1e502013-08-06 01:03:05 +00007356 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7357 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007358 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007359 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007360 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7361 if (InstantiationClass->getTemplateSpecializationKind() ==
7362 TSK_ImplicitInstantiation) {
7363 InstantiationClass->setTemplateSpecializationKind(
7364 TSK_ExplicitSpecialization);
7365 InstantiationClass->setLocation(Member->getLocation());
7366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007367
Douglas Gregor86d142a2009-10-08 07:24:58 +00007368 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007369 cast<CXXRecordDecl>(InstantiatedFrom),
7370 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007371 } else {
7372 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7373 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7374 if (InstantiationEnum->getTemplateSpecializationKind() ==
7375 TSK_ImplicitInstantiation) {
7376 InstantiationEnum->setTemplateSpecializationKind(
7377 TSK_ExplicitSpecialization);
7378 InstantiationEnum->setLocation(Member->getLocation());
7379 }
7380
7381 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7382 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007384
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007385 // Save the caller the trouble of having to figure out which declaration
7386 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007387 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007388 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007389 return false;
7390}
7391
Douglas Gregore47f5a72009-10-14 23:41:34 +00007392/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007393///
7394/// \returns true if a serious error occurs, false otherwise.
7395static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007396 SourceLocation InstLoc,
7397 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007398 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7399 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007400
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007401 if (CurContext->isRecord()) {
7402 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7403 << D;
7404 return true;
7405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007406
Richard Smith050d2612011-10-18 02:28:33 +00007407 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007408 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007409 // template. If the name declared in the explicit instantiation is an
7410 // unqualified name, the explicit instantiation shall appear in the
7411 // namespace where its template is declared or, if that namespace is inline
7412 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007413 //
7414 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007415 if (WasQualifiedName) {
7416 if (CurContext->Encloses(OrigContext))
7417 return false;
7418 } else {
7419 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7420 return false;
7421 }
7422
7423 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7424 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007425 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007426 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007427 diag::err_explicit_instantiation_out_of_scope :
7428 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007429 << D << NS;
7430 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007431 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007432 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007433 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7434 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7435 << D << NS;
7436 } else
7437 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007438 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007439 diag::err_explicit_instantiation_must_be_global :
7440 diag::warn_explicit_instantiation_must_be_global_0x)
7441 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007442 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007443 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007444}
7445
7446/// \brief Determine whether the given scope specifier has a template-id in it.
7447static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7448 if (!SS.isSet())
7449 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007450
Richard Smith050d2612011-10-18 02:28:33 +00007451 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007452 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007453 // or a static data member of a class template specialization, the name of
7454 // the class template specialization in the qualified-id for the member
7455 // name shall be a simple-template-id.
7456 //
7457 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007458 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7459 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007460 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007461 if (isa<TemplateSpecializationType>(T))
7462 return true;
7463
7464 return false;
7465}
7466
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007467/// Make a dllexport or dllimport attr on a class template specialization take
7468/// effect.
7469static void dllExportImportClassTemplateSpecialization(
7470 Sema &S, ClassTemplateSpecializationDecl *Def) {
7471 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
7472 assert(A && "dllExportImportClassTemplateSpecialization called "
7473 "on Def without dllexport or dllimport");
7474
7475 // We reject explicit instantiations in class scope, so there should
7476 // never be any delayed exported classes to worry about.
7477 assert(S.DelayedDllExportClasses.empty() &&
7478 "delayed exports present at explicit instantiation");
7479 S.checkClassLevelDLLAttribute(Def);
7480
7481 // Propagate attribute to base class templates.
7482 for (auto &B : Def->bases()) {
7483 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7484 B.getType()->getAsCXXRecordDecl()))
7485 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7486 }
7487
7488 S.referenceDLLExportedClassMethods();
7489}
7490
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007491// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007492DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007493Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007494 SourceLocation ExternLoc,
7495 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007496 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007497 SourceLocation KWLoc,
7498 const CXXScopeSpec &SS,
7499 TemplateTy TemplateD,
7500 SourceLocation TemplateNameLoc,
7501 SourceLocation LAngleLoc,
7502 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007503 SourceLocation RAngleLoc,
7504 AttributeList *Attr) {
7505 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007506 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007507 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007508 // Check that the specialization uses the same tag kind as the
7509 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007510 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7511 assert(Kind != TTK_Enum &&
7512 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007513
Richard Trieu265c3442016-04-05 21:13:54 +00007514 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7515
7516 if (!ClassTemplate) {
Reid Kleckner1a4ab7e2016-12-09 19:47:58 +00007517 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
7518 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
Richard Trieu265c3442016-04-05 21:13:54 +00007519 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007520 return true;
7521 }
7522
Douglas Gregord9034f02009-05-14 16:41:31 +00007523 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007524 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007525 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007526 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007527 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007528 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007529 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007530 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007531 diag::note_previous_use);
7532 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7533 }
7534
Douglas Gregore47f5a72009-10-14 23:41:34 +00007535 // C++0x [temp.explicit]p2:
7536 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007537 // definition and an explicit instantiation declaration. An explicit
7538 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007539 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7540 ? TSK_ExplicitInstantiationDefinition
7541 : TSK_ExplicitInstantiationDeclaration;
7542
7543 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7544 // Check for dllexport class template instantiation declarations.
7545 for (AttributeList *A = Attr; A; A = A->getNext()) {
7546 if (A->getKind() == AttributeList::AT_DLLExport) {
7547 Diag(ExternLoc,
7548 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7549 Diag(A->getLoc(), diag::note_attribute);
7550 break;
7551 }
7552 }
7553
7554 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7555 Diag(ExternLoc,
7556 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7557 Diag(A->getLocation(), diag::note_attribute);
7558 }
7559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007560
Hans Wennborga86a83b2016-05-26 19:42:56 +00007561 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7562 // instantiation declarations for most purposes.
7563 bool DLLImportExplicitInstantiationDef = false;
7564 if (TSK == TSK_ExplicitInstantiationDefinition &&
7565 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7566 // Check for dllimport class template instantiation definitions.
7567 bool DLLImport =
7568 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7569 for (AttributeList *A = Attr; A; A = A->getNext()) {
7570 if (A->getKind() == AttributeList::AT_DLLImport)
7571 DLLImport = true;
7572 if (A->getKind() == AttributeList::AT_DLLExport) {
7573 // dllexport trumps dllimport here.
7574 DLLImport = false;
7575 break;
7576 }
7577 }
7578 if (DLLImport) {
7579 TSK = TSK_ExplicitInstantiationDeclaration;
7580 DLLImportExplicitInstantiationDef = true;
7581 }
7582 }
7583
Douglas Gregora1f49972009-05-13 00:25:59 +00007584 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007585 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007586 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007587
7588 // Check that the template argument list is well-formed for this
7589 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007590 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007591 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7592 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007593 return true;
7594
Douglas Gregora1f49972009-05-13 00:25:59 +00007595 // Find the class template specialization declaration that
7596 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007597 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007598 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007599 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007600
Abramo Bagnara8075c852010-06-12 07:44:57 +00007601 TemplateSpecializationKind PrevDecl_TSK
7602 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7603
Douglas Gregor54888652009-10-07 00:13:32 +00007604 // C++0x [temp.explicit]p2:
7605 // [...] An explicit instantiation shall appear in an enclosing
7606 // namespace of its template. [...]
7607 //
7608 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007609 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7610 SS.isSet()))
7611 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612
Craig Topperc3ec1492014-05-26 06:22:03 +00007613 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007614
Abramo Bagnara8075c852010-06-12 07:44:57 +00007615 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007616 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007617 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007618 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007619 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007620 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007621 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007622
Abramo Bagnara8075c852010-06-12 07:44:57 +00007623 // Even though HasNoEffect == true means that this explicit instantiation
7624 // has no effect on semantics, we go on to put its syntax in the AST.
7625
7626 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7627 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007628 // Since the only prior class template specialization with these
7629 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007630 // declaration node as our own, updating the source location
7631 // for the template name to reflect our new declaration.
7632 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007633 Specialization = PrevDecl;
7634 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007635 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007636 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007637
7638 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7639 DLLImportExplicitInstantiationDef) {
7640 // The new specialization might add a dllimport attribute.
7641 HasNoEffect = false;
7642 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007643 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007644
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007645 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007646 // Create a new class template specialization declaration node for
7647 // this explicit specialization.
7648 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007649 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007650 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007651 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007652 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007653 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007654 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007655 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007656
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007657 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007658 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007659 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007660 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007661 }
7662
7663 // Build the fully-sugared type for this explicit instantiation as
7664 // the user wrote in the explicit instantiation itself. This means
7665 // that we'll pretty-print the type retrieved from the
7666 // specialization's declaration the way that the user actually wrote
7667 // the explicit instantiation, rather than formatting the name based
7668 // on the "canonical" representation used to store the template
7669 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007670 TypeSourceInfo *WrittenTy
7671 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7672 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007673 Context.getTypeDeclType(Specialization));
7674 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007675
Abramo Bagnara8075c852010-06-12 07:44:57 +00007676 // Set source locations for keywords.
7677 Specialization->setExternLoc(ExternLoc);
7678 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007679 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007680
Rafael Espindola0b062072012-01-03 06:04:21 +00007681 if (Attr)
7682 ProcessDeclAttributeList(S, Specialization, Attr);
7683
Abramo Bagnara8075c852010-06-12 07:44:57 +00007684 // Add the explicit instantiation into its lexical context. However,
7685 // since explicit instantiations are never found by name lookup, we
7686 // just put it into the declaration context directly.
7687 Specialization->setLexicalDeclContext(CurContext);
7688 CurContext->addDecl(Specialization);
7689
7690 // Syntax is now OK, so return if it has no other effect on semantics.
7691 if (HasNoEffect) {
7692 // Set the template specialization kind.
7693 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007694 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007695 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007696
7697 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007698 // A definition of a class template or class member template
7699 // shall be in scope at the point of the explicit instantiation of
7700 // the class template or class member template.
7701 //
7702 // This check comes when we actually try to perform the
7703 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007704 ClassTemplateSpecializationDecl *Def
7705 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007706 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007707 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007708 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007709 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007710 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007711 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7712 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007713
Douglas Gregor1d957a32009-10-27 18:42:08 +00007714 // Instantiate the members of this class template specialization.
7715 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007716 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007717 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007718 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007719 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7720 // TSK_ExplicitInstantiationDefinition
7721 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007722 (TSK == TSK_ExplicitInstantiationDefinition ||
7723 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007724 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007725 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007726
Hans Wennborgc0875502015-06-09 00:39:05 +00007727 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
Shoaib Meenaiab3f96c2016-11-09 23:52:20 +00007728 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7729 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
Hans Wennborgc0875502015-06-09 00:39:05 +00007730 // In the MS ABI, an explicit instantiation definition can add a dll
7731 // attribute to a template with a previous instantiation declaration.
7732 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007733 auto *A = cast<InheritableAttr>(
7734 getDLLAttr(Specialization)->clone(getASTContext()));
7735 A->setInherited(true);
7736 Def->addAttr(A);
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007737 dllExportImportClassTemplateSpecialization(*this, Def);
Hans Wennborg17f9b442015-05-27 00:06:45 +00007738 }
7739 }
7740
Shoaib Meenaifc78d7c2016-12-05 18:01:35 +00007741 // Fix a TSK_ImplicitInstantiation followed by a
7742 // TSK_ExplicitInstantiationDefinition
7743 if (Old_TSK == TSK_ImplicitInstantiation &&
7744 Specialization->hasAttr<DLLExportAttr>() &&
7745 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
7746 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
7747 // In the MS ABI, an explicit instantiation definition can add a dll
7748 // attribute to a template with a previous implicit instantiation.
7749 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
7750 // avoid potentially strange codegen behavior. For example, if we extend
7751 // this conditional to dllimport, and we have a source file calling a
7752 // method on an implicitly instantiated template class instance and then
7753 // declaring a dllimport explicit instantiation definition for the same
7754 // template class, the codegen for the method call will not respect the
7755 // dllimport, while it will with cl. The Def will already have the DLL
7756 // attribute, since the Def and Specialization will be the same in the
7757 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
7758 // attribute to the Specialization; we just need to make it take effect.
7759 assert(Def == Specialization &&
7760 "Def and Specialization should match for implicit instantiation");
7761 dllExportImportClassTemplateSpecialization(*this, Def);
7762 }
7763
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007764 // Set the template specialization kind. Make sure it is set before
7765 // instantiating the members which will trigger ASTConsumer callbacks.
7766 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007767 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007768 } else {
7769
7770 // Set the template specialization kind.
7771 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007772 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007773
John McCall48871652010-08-21 09:40:31 +00007774 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007775}
7776
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007777// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007778DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007779Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007780 SourceLocation ExternLoc,
7781 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007782 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007783 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007784 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007785 IdentifierInfo *Name,
7786 SourceLocation NameLoc,
7787 AttributeList *Attr) {
7788
Douglas Gregord6ab8742009-05-28 23:31:59 +00007789 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007790 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007791 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007792 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007793 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007794 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007795 SourceLocation(), false, TypeResult(),
7796 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007797 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7798
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007799 if (!TagD)
7800 return true;
7801
John McCall48871652010-08-21 09:40:31 +00007802 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007803 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007804
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007805 if (Tag->isInvalidDecl())
7806 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007807
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007808 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7809 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7810 if (!Pattern) {
7811 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7812 << Context.getTypeDeclType(Record);
7813 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7814 return true;
7815 }
7816
Douglas Gregore47f5a72009-10-14 23:41:34 +00007817 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007818 // If the explicit instantiation is for a class or member class, the
7819 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007820 // simple-template-id.
7821 //
7822 // C++98 has the same restriction, just worded differently.
7823 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007824 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007825 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007826
Douglas Gregore47f5a72009-10-14 23:41:34 +00007827 // C++0x [temp.explicit]p2:
7828 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007829 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007830 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007831 TemplateSpecializationKind TSK
7832 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7833 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007834
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007835 // C++0x [temp.explicit]p2:
7836 // [...] An explicit instantiation shall appear in an enclosing
7837 // namespace of its template. [...]
7838 //
7839 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007840 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007841
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007842 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007843 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007844 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007845 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007846 PrevDecl = Record;
7847 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007848 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007849 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007850 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007852 PrevDecl,
7853 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007854 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007855 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007856 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007857 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007858 return TagD;
7859 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007860
Douglas Gregor12e49d32009-10-15 22:53:21 +00007861 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007862 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007863 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007864 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007866 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007868 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007869 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007870 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7871 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007872 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7873 << Pattern;
7874 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007875 } else {
7876 if (InstantiateClass(NameLoc, Record, Def,
7877 getTemplateInstantiationArgs(Record),
7878 TSK))
7879 return true;
7880
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007881 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007882 if (!RecordDef)
7883 return true;
7884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007885 }
7886
Douglas Gregor1d957a32009-10-27 18:42:08 +00007887 // Instantiate all of the members of the class.
7888 InstantiateClassMembers(NameLoc, RecordDef,
7889 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007890
Douglas Gregor88d292c2010-05-13 16:44:06 +00007891 if (TSK == TSK_ExplicitInstantiationDefinition)
7892 MarkVTableUsed(NameLoc, RecordDef, true);
7893
Mike Stump87c57ac2009-05-16 07:39:55 +00007894 // FIXME: We don't have any representation for explicit instantiations of
7895 // member classes. Such a representation is not needed for compilation, but it
7896 // should be available for clients that want to see all of the declarations in
7897 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007898 return TagD;
7899}
7900
John McCallfaf5fb42010-08-26 23:41:50 +00007901DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7902 SourceLocation ExternLoc,
7903 SourceLocation TemplateLoc,
7904 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007905 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007906 // TODO: check if/when DNInfo should replace Name.
7907 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7908 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007909 if (!Name) {
7910 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007911 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007912 diag::err_explicit_instantiation_requires_name)
7913 << D.getDeclSpec().getSourceRange()
7914 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007915
Douglas Gregor450f00842009-09-25 18:43:00 +00007916 return true;
7917 }
7918
7919 // The scope passed in may not be a decl scope. Zip up the scope tree until
7920 // we find one that is.
7921 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7922 (S->getFlags() & Scope::TemplateParamScope) != 0)
7923 S = S->getParent();
7924
7925 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007926 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7927 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007928 if (R.isNull())
7929 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007930
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007931 // C++ [dcl.stc]p1:
7932 // A storage-class-specifier shall not be specified in [...] an explicit
7933 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007934 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007935 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7936 << Name;
7937 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007938 } else if (D.getDeclSpec().getStorageClassSpec()
7939 != DeclSpec::SCS_unspecified) {
7940 // Complain about then remove the storage class specifier.
7941 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7942 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7943
7944 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007945 }
7946
Douglas Gregor3c74d412009-10-14 20:14:33 +00007947 // C++0x [temp.explicit]p1:
7948 // [...] An explicit instantiation of a function template shall not use the
7949 // inline or constexpr specifiers.
7950 // Presumably, this also applies to member functions of class templates as
7951 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007952 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007953 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007954 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007955 diag::err_explicit_instantiation_inline :
7956 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007957 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007958 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007959 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7960 // not already specified.
7961 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7962 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007963
Nathan Wilsonde498452016-02-08 05:34:00 +00007964 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7965 // applied only to the definition of a function template or variable template,
7966 // declared in namespace scope.
7967 if (D.getDeclSpec().isConceptSpecified()) {
7968 Diag(D.getDeclSpec().getConceptSpecLoc(),
7969 diag::err_concept_specified_specialization) << 0;
7970 return true;
7971 }
7972
Douglas Gregore47f5a72009-10-14 23:41:34 +00007973 // C++0x [temp.explicit]p2:
7974 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007975 // definition and an explicit instantiation declaration. An explicit
7976 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007977 TemplateSpecializationKind TSK
7978 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7979 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007980
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007981 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007982 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007983
7984 if (!R->isFunctionType()) {
7985 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986 // A [...] static data member of a class template can be explicitly
7987 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007988 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007989 // C++1y [temp.explicit]p1:
7990 // A [...] variable [...] template specialization can be explicitly
7991 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007992 if (Previous.isAmbiguous())
7993 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007994
John McCall67c00872009-12-02 08:25:40 +00007995 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007996 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007997
Larisse Voufo39a1e502013-08-06 01:03:05 +00007998 if (!PrevTemplate) {
7999 if (!Prev || !Prev->isStaticDataMember()) {
8000 // We expect to see a data data member here.
8001 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8002 << Name;
8003 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8004 P != PEnd; ++P)
8005 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8006 return true;
8007 }
8008
8009 if (!Prev->getInstantiatedFromStaticDataMember()) {
8010 // FIXME: Check for explicit specialization?
8011 Diag(D.getIdentifierLoc(),
8012 diag::err_explicit_instantiation_data_member_not_instantiated)
8013 << Prev;
8014 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8015 // FIXME: Can we provide a note showing where this was declared?
8016 return true;
8017 }
8018 } else {
8019 // Explicitly instantiate a variable template.
8020
8021 // C++1y [dcl.spec.auto]p6:
8022 // ... A program that uses auto or decltype(auto) in a context not
8023 // explicitly allowed in this section is ill-formed.
8024 //
8025 // This includes auto-typed variable template instantiations.
8026 if (R->isUndeducedType()) {
8027 Diag(T->getTypeLoc().getLocStart(),
8028 diag::err_auto_not_allowed_var_inst);
8029 return true;
8030 }
8031
Richard Smithef985ac2013-09-18 02:10:12 +00008032 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8033 // C++1y [temp.explicit]p3:
8034 // If the explicit instantiation is for a variable, the unqualified-id
8035 // in the declaration shall be a template-id.
8036 Diag(D.getIdentifierLoc(),
8037 diag::err_explicit_instantiation_without_template_id)
8038 << PrevTemplate;
8039 Diag(PrevTemplate->getLocation(),
8040 diag::note_explicit_instantiation_here);
8041 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00008042 }
8043
Nathan Wilson83839122016-04-09 02:55:27 +00008044 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8045 // explicit instantiation (14.8.2) [...] of a concept definition.
8046 if (PrevTemplate->isConcept()) {
8047 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8048 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8049 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8050 return true;
8051 }
8052
Richard Smithef985ac2013-09-18 02:10:12 +00008053 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00008054 TemplateArgumentListInfo TemplateArgs =
8055 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00008056
Larisse Voufo39a1e502013-08-06 01:03:05 +00008057 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8058 D.getIdentifierLoc(), TemplateArgs);
8059 if (Res.isInvalid())
8060 return true;
8061
8062 // Ignore access control bits, we don't need them for redeclaration
8063 // checking.
8064 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00008065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Douglas Gregore47f5a72009-10-14 23:41:34 +00008067 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008068 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008069 // or a static data member of a class template specialization, the name of
8070 // the class template specialization in the qualified-id for the member
8071 // name shall be a simple-template-id.
8072 //
8073 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00008074 //
Richard Smith5977d872013-09-18 21:55:14 +00008075 // This does not apply to variable template specializations, where the
8076 // template-id is in the unqualified-id instead.
8077 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008078 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008079 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008080 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008081
Douglas Gregore47f5a72009-10-14 23:41:34 +00008082 // Check the scope of this explicit instantiation.
8083 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008084
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008085 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00008086 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8087 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00008088 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008089 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00008090 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00008091 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008092
Larisse Voufo39a1e502013-08-06 01:03:05 +00008093 if (!HasNoEffect) {
8094 // Instantiate static data member or variable template.
8095
8096 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8097 if (PrevTemplate) {
8098 // Merge attributes.
8099 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8100 ProcessDeclAttributeList(S, Prev, Attr);
8101 }
8102 if (TSK == TSK_ExplicitInstantiationDefinition)
8103 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8104 }
8105
8106 // Check the new variable specialization against the parsed input.
8107 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8108 Diag(T->getTypeLoc().getLocStart(),
8109 diag::err_invalid_var_template_spec_type)
8110 << 0 << PrevTemplate << R << Prev->getType();
8111 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8112 << 2 << PrevTemplate->getDeclName();
8113 return true;
8114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008115
Douglas Gregor450f00842009-09-25 18:43:00 +00008116 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00008117 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119
8120 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008121 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008122 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008123 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008124 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008125 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008126 HasExplicitTemplateArgs = true;
8127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008128
Douglas Gregor450f00842009-09-25 18:43:00 +00008129 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008130 // A [...] function [...] can be explicitly instantiated from its template.
8131 // A member function [...] of a class template can be explicitly
8132 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008133 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008134 UnresolvedSet<8> Matches;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008135 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008136 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008137 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8138 P != PEnd; ++P) {
8139 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008140 if (!HasExplicitTemplateArgs) {
8141 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Richard Smithbaa47832016-12-01 02:11:49 +00008142 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8143 /*AdjustExceptionSpec*/true);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008144 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008145 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008146
John McCall58cc69d2010-01-27 01:50:18 +00008147 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008148 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8149 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008150 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008151 }
8152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153
Douglas Gregor450f00842009-09-25 18:43:00 +00008154 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8155 if (!FunTmpl)
8156 continue;
8157
Larisse Voufo98b20f12013-07-19 23:00:19 +00008158 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008159 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008160 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008161 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008162 (HasExplicitTemplateArgs ? &TemplateArgs
8163 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008164 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008165 // Keep track of almost-matches.
8166 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008167 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008168 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008169 (void)TDK;
8170 continue;
8171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008172
Artem Belevich64135c32016-12-08 19:38:13 +00008173 // Target attributes are part of the cuda function signature, so
8174 // the cuda target of the instantiated function must match that of its
8175 // template. Given that C++ template deduction does not take
8176 // target attributes into account, we reject candidates here that
8177 // have a different target.
8178 if (LangOpts.CUDA &&
8179 IdentifyCUDATarget(Specialization,
8180 /* IgnoreImplicitHDAttributes = */ true) !=
8181 IdentifyCUDATarget(Attr)) {
8182 FailedCandidates.addCandidate().set(
8183 P.getPair(), FunTmpl->getTemplatedDecl(),
8184 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8185 continue;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00008186 }
8187
John McCall58cc69d2010-01-27 01:50:18 +00008188 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008190
Douglas Gregor450f00842009-09-25 18:43:00 +00008191 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008192 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008193 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008194 D.getIdentifierLoc(),
8195 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8196 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8197 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008198
John McCall58cc69d2010-01-27 01:50:18 +00008199 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008200 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008201
8202 // Ignore access control bits, we don't need them for redeclaration checking.
8203 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008204
Alexey Bataev73983912014-11-06 10:10:50 +00008205 // C++11 [except.spec]p4
8206 // In an explicit instantiation an exception-specification may be specified,
8207 // but is not required.
8208 // If an exception-specification is specified in an explicit instantiation
8209 // directive, it shall be compatible with the exception-specifications of
8210 // other declarations of that function.
8211 if (auto *FPT = R->getAs<FunctionProtoType>())
8212 if (FPT->hasExceptionSpec()) {
8213 unsigned DiagID =
8214 diag::err_mismatched_exception_spec_explicit_instantiation;
8215 if (getLangOpts().MicrosoftExt)
8216 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8217 bool Result = CheckEquivalentExceptionSpec(
8218 PDiag(DiagID) << Specialization->getType(),
8219 PDiag(diag::note_explicit_instantiation_here),
8220 Specialization->getType()->getAs<FunctionProtoType>(),
8221 Specialization->getLocation(), FPT, D.getLocStart());
8222 // In Microsoft mode, mismatching exception specifications just cause a
8223 // warning.
8224 if (!getLangOpts().MicrosoftExt && Result)
8225 return true;
8226 }
8227
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008228 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008229 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008230 diag::err_explicit_instantiation_member_function_not_instantiated)
8231 << Specialization
8232 << (Specialization->getTemplateSpecializationKind() ==
8233 TSK_ExplicitSpecialization);
8234 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8235 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008236 }
8237
Douglas Gregorec9fd132012-01-14 16:38:05 +00008238 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008239 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8240 PrevDecl = Specialization;
8241
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008242 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008243 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008244 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008245 PrevDecl,
8246 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008247 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008248 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008249 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008250
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008251 // FIXME: We may still want to build some representation of this
8252 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008253 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008254 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008255 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008256
8257 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008258 if (Attr)
8259 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008260
Richard Smitheb36ddf2014-04-24 22:45:46 +00008261 if (Specialization->isDefined()) {
8262 // Let the ASTConsumer know that this function has been explicitly
8263 // instantiated now, and its linkage might have changed.
8264 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8265 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008266 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008267
Douglas Gregore47f5a72009-10-14 23:41:34 +00008268 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008269 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008270 // or a static data member of a class template specialization, the name of
8271 // the class template specialization in the qualified-id for the member
8272 // name shall be a simple-template-id.
8273 //
8274 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008275 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008276 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008277 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008278 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008279 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008280 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008281 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008282
Nathan Wilson83839122016-04-09 02:55:27 +00008283 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8284 // explicit instantiation (14.8.2) [...] of a concept definition.
8285 if (FunTmpl && FunTmpl->isConcept() &&
8286 !D.getDeclSpec().isConceptSpecified()) {
8287 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8288 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8289 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8290 return true;
8291 }
8292
Douglas Gregore47f5a72009-10-14 23:41:34 +00008293 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008294 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008295 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008296 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008297 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008298
Douglas Gregor450f00842009-09-25 18:43:00 +00008299 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008300 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008301}
8302
John McCallfaf5fb42010-08-26 23:41:50 +00008303TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008304Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8305 const CXXScopeSpec &SS, IdentifierInfo *Name,
8306 SourceLocation TagLoc, SourceLocation NameLoc) {
8307 // This has to hold, because SS is expected to be defined.
8308 assert(Name && "Expected a name in a dependent tag");
8309
Aaron Ballman4a979672014-01-03 13:56:08 +00008310 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008311 if (!NNS)
8312 return true;
8313
Abramo Bagnara6150c882010-05-11 21:36:43 +00008314 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008315
Douglas Gregorba41d012010-04-24 16:38:41 +00008316 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8317 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008318 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008319 return true;
8320 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008321
Douglas Gregore7c20652011-03-02 00:47:37 +00008322 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008323 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008324 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8325
8326 // Create type-source location information for this type.
8327 TypeLocBuilder TLB;
8328 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008329 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008330 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8331 TL.setNameLoc(NameLoc);
8332 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008333}
8334
John McCallfaf5fb42010-08-26 23:41:50 +00008335TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008336Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8337 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008338 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008339 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008340 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008341
Richard Smith0bf8a4922011-10-18 20:49:44 +00008342 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8343 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008344 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008345 diag::warn_cxx98_compat_typename_outside_of_template :
8346 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008347 << FixItHint::CreateRemoval(TypenameLoc);
8348
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008349 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008350 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8351 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008352 if (T.isNull())
8353 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008354
8355 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8356 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008357 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008358 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008359 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008360 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008361 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008362 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008363 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008364 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008365 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008367
John McCallba7bf592010-08-24 05:47:05 +00008368 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008369}
8370
John McCallfaf5fb42010-08-26 23:41:50 +00008371TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008372Sema::ActOnTypenameType(Scope *S,
8373 SourceLocation TypenameLoc,
8374 const CXXScopeSpec &SS,
8375 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008376 TemplateTy TemplateIn,
8377 SourceLocation TemplateNameLoc,
8378 SourceLocation LAngleLoc,
8379 ASTTemplateArgsPtr TemplateArgsIn,
8380 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008381 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8382 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008383 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008384 diag::warn_cxx98_compat_typename_outside_of_template :
8385 diag::ext_typename_outside_of_template)
8386 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008387
8388 // Translate the parser's template argument list in our AST format.
8389 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8390 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8391
8392 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008393 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8394 // Construct a dependent template specialization type.
8395 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008396 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008397 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8398 DTN->getQualifier(),
8399 DTN->getIdentifier(),
8400 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008401
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008402 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008403 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008404 DependentTemplateSpecializationTypeLoc SpecTL
8405 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008406 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8407 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008408 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008409 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008410 SpecTL.setLAngleLoc(LAngleLoc);
8411 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008412 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8413 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008414 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008415 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008416
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008417 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8418 if (T.isNull())
8419 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008420
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008421 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008422 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008423 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008424 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008425 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8426 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008427 SpecTL.setLAngleLoc(LAngleLoc);
8428 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008429 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8430 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8431
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008432 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8433 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008434 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008435 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8436
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008437 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8438 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008439}
8440
Douglas Gregorb09518c2011-02-27 22:46:49 +00008441
Richard Smith6f8d2c62012-05-09 05:17:00 +00008442/// Determine whether this failed name lookup should be treated as being
8443/// disabled by a usage of std::enable_if.
8444static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8445 SourceRange &CondRange) {
8446 // We must be looking for a ::type...
8447 if (!II.isStr("type"))
8448 return false;
8449
8450 // ... within an explicitly-written template specialization...
8451 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8452 return false;
8453 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008454 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8455 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8456 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008457 return false;
8458 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008459 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008460
8461 // ... which names a complete class template declaration...
8462 const TemplateDecl *EnableIfDecl =
8463 EnableIfTST->getTemplateName().getAsTemplateDecl();
8464 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8465 return false;
8466
8467 // ... called "enable_if".
8468 const IdentifierInfo *EnableIfII =
8469 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8470 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8471 return false;
8472
8473 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008474 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008475 return true;
8476}
8477
Douglas Gregor333489b2009-03-27 23:10:48 +00008478/// \brief Build the type that describes a C++ typename specifier,
8479/// e.g., "typename T::type".
8480QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008481Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8482 SourceLocation KeywordLoc,
8483 NestedNameSpecifierLoc QualifierLoc,
8484 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008485 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008486 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008487 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008488
John McCall0b66eb32010-05-01 00:40:08 +00008489 DeclContext *Ctx = computeDeclContext(SS);
8490 if (!Ctx) {
8491 // If the nested-name-specifier is dependent and couldn't be
8492 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008493 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8494 return Context.getDependentNameType(Keyword,
8495 QualifierLoc.getNestedNameSpecifier(),
8496 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008497 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008498
John McCall0b66eb32010-05-01 00:40:08 +00008499 // If the nested-name-specifier refers to the current instantiation,
8500 // the "typename" keyword itself is superfluous. In C++03, the
8501 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8502 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008503 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008504
John McCall0b66eb32010-05-01 00:40:08 +00008505 if (RequireCompleteDeclContext(SS, Ctx))
8506 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008507
8508 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008509 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008510 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008511 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008512 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008513 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008514 case LookupResult::NotFound: {
8515 // If we're looking up 'type' within a template named 'enable_if', produce
8516 // a more specific diagnostic.
8517 SourceRange CondRange;
8518 if (isEnableIf(QualifierLoc, II, CondRange)) {
8519 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8520 << Ctx << CondRange;
8521 return QualType();
8522 }
8523
Douglas Gregore40876a2009-10-13 21:16:44 +00008524 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008525 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008526 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008527
8528 case LookupResult::FoundUnresolvedValue: {
8529 // We found a using declaration that is a value. Most likely, the using
8530 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008531 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008532 IILoc);
8533 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8534 << Name << Ctx << FullRange;
8535 if (UnresolvedUsingValueDecl *Using
8536 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008537 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008538 Diag(Loc, diag::note_using_value_decl_missing_typename)
8539 << FixItHint::CreateInsertion(Loc, "typename ");
8540 }
8541 }
8542 // Fall through to create a dependent typename type, from which we can recover
8543 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008544
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008545 case LookupResult::NotFoundInCurrentInstantiation:
8546 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008547 return Context.getDependentNameType(Keyword,
8548 QualifierLoc.getNestedNameSpecifier(),
8549 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008550
8551 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008552 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008553 // We found a type. Build an ElaboratedType, since the
8554 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008555 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008556 return Context.getElaboratedType(ETK_Typename,
8557 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008558 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008559 }
8560
8561 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008562 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008563 break;
8564
8565 case LookupResult::FoundOverloaded:
8566 DiagID = diag::err_typename_nested_not_type;
8567 Referenced = *Result.begin();
8568 break;
8569
John McCall6538c932009-10-10 05:48:19 +00008570 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008571 return QualType();
8572 }
8573
8574 // If we get here, it's because name lookup did not find a
8575 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008576 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008577 IILoc);
8578 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008579 if (Referenced)
8580 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8581 << Name;
8582 return QualType();
8583}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008584
8585namespace {
8586 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008587 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008588 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008589 SourceLocation Loc;
8590 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008591
Douglas Gregor15acfb92009-08-06 16:20:37 +00008592 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008593 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008594
Mike Stump11289f42009-09-09 15:08:12 +00008595 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008596 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008597 DeclarationName Entity)
8598 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008599 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008600
8601 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008602 /// transformed.
8603 ///
8604 /// For the purposes of type reconstruction, a type has already been
8605 /// transformed if it is NULL or if it is not dependent.
8606 bool AlreadyTransformed(QualType T) {
8607 return T.isNull() || !T->isDependentType();
8608 }
Mike Stump11289f42009-09-09 15:08:12 +00008609
8610 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008611 /// rebuilt.
8612 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008613
Douglas Gregor15acfb92009-08-06 16:20:37 +00008614 /// \brief Returns the name of the entity whose type is being rebuilt.
8615 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008616
Douglas Gregoref6ab412009-10-27 06:26:26 +00008617 /// \brief Sets the "base" location and entity when that
8618 /// information is known based on another transformation.
8619 void setBase(SourceLocation Loc, DeclarationName Entity) {
8620 this->Loc = Loc;
8621 this->Entity = Entity;
8622 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008623
8624 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8625 // Lambdas never need to be transformed.
8626 return E;
8627 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008628 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008629} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008630
Douglas Gregor15acfb92009-08-06 16:20:37 +00008631/// \brief Rebuilds a type within the context of the current instantiation.
8632///
Mike Stump11289f42009-09-09 15:08:12 +00008633/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008634/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008635/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008636/// partial specialization thereof). This routine will rebuild that type now
8637/// that we have entered the declarator's scope, which may produce different
8638/// canonical types, e.g.,
8639///
8640/// \code
8641/// template<typename T>
8642/// struct X {
8643/// typedef T* pointer;
8644/// pointer data();
8645/// };
8646///
8647/// template<typename T>
8648/// typename X<T>::pointer X<T>::data() { ... }
8649/// \endcode
8650///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008651/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008652/// since we do not know that we can look into X<T> when we parsed the type.
8653/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008654/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008655/// as the canonical type of T*, allowing the return types of the out-of-line
8656/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008657TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8658 SourceLocation Loc,
8659 DeclarationName Name) {
8660 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008661 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008662
Douglas Gregor15acfb92009-08-06 16:20:37 +00008663 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8664 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008665}
Douglas Gregorbe999392009-09-15 16:23:51 +00008666
John McCalldadc5752010-08-24 06:29:42 +00008667ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008668 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8669 DeclarationName());
8670 return Rebuilder.TransformExpr(E);
8671}
8672
John McCall99b2fe52010-04-29 23:50:39 +00008673bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008674 if (SS.isInvalid())
8675 return true;
John McCall2408e322010-04-27 00:57:59 +00008676
Douglas Gregor10176412011-02-25 16:07:42 +00008677 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008678 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8679 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008680 NestedNameSpecifierLoc Rebuilt
8681 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8682 if (!Rebuilt)
8683 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008684
Douglas Gregor10176412011-02-25 16:07:42 +00008685 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008686 return false;
John McCall2408e322010-04-27 00:57:59 +00008687}
8688
Douglas Gregor041b0842011-10-14 15:31:12 +00008689/// \brief Rebuild the template parameters now that we know we're in a current
8690/// instantiation.
8691bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8692 TemplateParameterList *Params) {
8693 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8694 Decl *Param = Params->getParam(I);
8695
8696 // There is nothing to rebuild in a type parameter.
8697 if (isa<TemplateTypeParmDecl>(Param))
8698 continue;
8699
8700 // Rebuild the template parameter list of a template template parameter.
8701 if (TemplateTemplateParmDecl *TTP
8702 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8703 if (RebuildTemplateParamsInCurrentInstantiation(
8704 TTP->getTemplateParameters()))
8705 return true;
8706
8707 continue;
8708 }
8709
8710 // Rebuild the type of a non-type template parameter.
8711 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8712 TypeSourceInfo *NewTSI
8713 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8714 NTTP->getLocation(),
8715 NTTP->getDeclName());
8716 if (!NewTSI)
8717 return true;
8718
8719 if (NewTSI != NTTP->getTypeSourceInfo()) {
8720 NTTP->setTypeSourceInfo(NewTSI);
8721 NTTP->setType(NewTSI->getType());
8722 }
8723 }
8724
8725 return false;
8726}
8727
Douglas Gregorbe999392009-09-15 16:23:51 +00008728/// \brief Produces a formatted string that describes the binding of
8729/// template parameters to template arguments.
8730std::string
8731Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8732 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008733 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008734}
8735
8736std::string
8737Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8738 const TemplateArgument *Args,
8739 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008740 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008741 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008742
Douglas Gregore62e6a02009-11-11 19:13:48 +00008743 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008744 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008745
Douglas Gregorbe999392009-09-15 16:23:51 +00008746 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008747 if (I >= NumArgs)
8748 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008749
Douglas Gregorbe999392009-09-15 16:23:51 +00008750 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008751 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008752 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008753 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008754
Douglas Gregorbe999392009-09-15 16:23:51 +00008755 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008756 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008757 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008758 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008760
Douglas Gregor0192c232010-12-20 16:52:59 +00008761 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008762 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008763 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008764
8765 Out << ']';
8766 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008767}
Francois Pichet1c229c02011-04-22 22:18:13 +00008768
Richard Smithe40f2ba2013-08-07 21:41:30 +00008769void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8770 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008771 if (!FD)
8772 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008773
Justin Lebar28f09c52016-10-10 16:26:08 +00008774 auto LPT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008775
8776 // Take tokens to avoid allocations
8777 LPT->Toks.swap(Toks);
8778 LPT->D = FnD;
Justin Lebar28f09c52016-10-10 16:26:08 +00008779 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008780
8781 FD->setLateTemplateParsed(true);
8782}
8783
8784void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8785 if (!FD)
8786 return;
8787 FD->setLateTemplateParsed(false);
8788}
Francois Pichet1c229c02011-04-22 22:18:13 +00008789
8790bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8791 DeclContext *DC = CurContext;
8792
8793 while (DC) {
8794 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8795 const FunctionDecl *FD = RD->isLocalClass();
8796 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8797 } else if (DC->isTranslationUnit() || DC->isNamespace())
8798 return false;
8799
8800 DC = DC->getParent();
8801 }
8802 return false;
8803}
Richard Smith6739a102016-05-05 00:56:12 +00008804
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008805namespace {
Richard Smith6739a102016-05-05 00:56:12 +00008806/// \brief Walk the path from which a declaration was instantiated, and check
8807/// that every explicit specialization along that path is visible. This enforces
8808/// C++ [temp.expl.spec]/6:
8809///
8810/// If a template, a member template or a member of a class template is
8811/// explicitly specialized then that specialization shall be declared before
8812/// the first use of that specialization that would cause an implicit
8813/// instantiation to take place, in every translation unit in which such a
8814/// use occurs; no diagnostic is required.
8815///
8816/// and also C++ [temp.class.spec]/1:
8817///
8818/// A partial specialization shall be declared before the first use of a
8819/// class template specialization that would make use of the partial
8820/// specialization as the result of an implicit or explicit instantiation
8821/// in every translation unit in which such a use occurs; no diagnostic is
8822/// required.
8823class ExplicitSpecializationVisibilityChecker {
8824 Sema &S;
8825 SourceLocation Loc;
8826 llvm::SmallVector<Module *, 8> Modules;
8827
8828public:
8829 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8830 : S(S), Loc(Loc) {}
8831
8832 void check(NamedDecl *ND) {
8833 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8834 return checkImpl(FD);
8835 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8836 return checkImpl(RD);
8837 if (auto *VD = dyn_cast<VarDecl>(ND))
8838 return checkImpl(VD);
8839 if (auto *ED = dyn_cast<EnumDecl>(ND))
8840 return checkImpl(ED);
8841 }
8842
8843private:
8844 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8845 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8846 : Sema::MissingImportKind::ExplicitSpecialization;
8847 const bool Recover = true;
8848
8849 // If we got a custom set of modules (because only a subset of the
8850 // declarations are interesting), use them, otherwise let
8851 // diagnoseMissingImport intelligently pick some.
8852 if (Modules.empty())
8853 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8854 else
8855 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8856 }
8857
8858 // Check a specific declaration. There are three problematic cases:
8859 //
8860 // 1) The declaration is an explicit specialization of a template
8861 // specialization.
8862 // 2) The declaration is an explicit specialization of a member of an
8863 // templated class.
8864 // 3) The declaration is an instantiation of a template, and that template
8865 // is an explicit specialization of a member of a templated class.
8866 //
8867 // We don't need to go any deeper than that, as the instantiation of the
8868 // surrounding class / etc is not triggered by whatever triggered this
8869 // instantiation, and thus should be checked elsewhere.
8870 template<typename SpecDecl>
8871 void checkImpl(SpecDecl *Spec) {
8872 bool IsHiddenExplicitSpecialization = false;
8873 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8874 IsHiddenExplicitSpecialization =
8875 Spec->getMemberSpecializationInfo()
8876 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8877 : !S.hasVisibleDeclaration(Spec);
8878 } else {
8879 checkInstantiated(Spec);
8880 }
8881
8882 if (IsHiddenExplicitSpecialization)
8883 diagnose(Spec->getMostRecentDecl(), false);
8884 }
8885
8886 void checkInstantiated(FunctionDecl *FD) {
8887 if (auto *TD = FD->getPrimaryTemplate())
8888 checkTemplate(TD);
8889 }
8890
8891 void checkInstantiated(CXXRecordDecl *RD) {
8892 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8893 if (!SD)
8894 return;
8895
8896 auto From = SD->getSpecializedTemplateOrPartial();
8897 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8898 checkTemplate(TD);
8899 else if (auto *TD =
8900 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8901 if (!S.hasVisibleDeclaration(TD))
8902 diagnose(TD, true);
8903 checkTemplate(TD);
8904 }
8905 }
8906
8907 void checkInstantiated(VarDecl *RD) {
8908 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8909 if (!SD)
8910 return;
8911
8912 auto From = SD->getSpecializedTemplateOrPartial();
8913 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8914 checkTemplate(TD);
8915 else if (auto *TD =
8916 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8917 if (!S.hasVisibleDeclaration(TD))
8918 diagnose(TD, true);
8919 checkTemplate(TD);
8920 }
8921 }
8922
8923 void checkInstantiated(EnumDecl *FD) {}
8924
8925 template<typename TemplDecl>
8926 void checkTemplate(TemplDecl *TD) {
8927 if (TD->isMemberSpecialization()) {
8928 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8929 diagnose(TD->getMostRecentDecl(), false);
8930 }
8931 }
8932};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008933} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00008934
8935void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8936 if (!getLangOpts().Modules)
8937 return;
8938
8939 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8940}
8941
8942/// \brief Check whether a template partial specialization that we've discovered
8943/// is hidden, and produce suitable diagnostics if so.
8944void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8945 NamedDecl *Spec) {
8946 llvm::SmallVector<Module *, 8> Modules;
8947 if (!hasVisibleDeclaration(Spec, &Modules))
8948 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8949 MissingImportKind::PartialSpecialization,
8950 /*Recover*/true);
8951}