blob: ede1c5bcc64166c6233396cdf7a88a3511b2890c [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
432 if (!MightBeCxx11UnevalField && !isAddressOfOperand &&
433 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
John McCall87fe5d52010-05-20 01:18:31 +0000434 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
John McCalle66edc12009-11-24 19:00:30 +0000436 // Since the 'this' expression is synthesized, we don't need to
437 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000438 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000439
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return CXXDependentScopeMemberExpr::Create(
441 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
442 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
443 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000444 }
445
Abramo Bagnara7945c982012-01-27 09:46:47 +0000446 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000447}
448
John McCalldadc5752010-08-24 06:29:42 +0000449ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000450Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000451 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000452 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000453 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000454 return DependentScopeDeclRefExpr::Create(
455 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
456 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000457}
458
Vassil Vassilevb21ee082016-08-18 22:01:25 +0000459
460/// Determine whether we would be unable to instantiate this template (because
461/// it either has no definition, or is in the process of being instantiated).
462bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
463 NamedDecl *Instantiation,
464 bool InstantiatedFromMember,
465 const NamedDecl *Pattern,
466 const NamedDecl *PatternDef,
467 TemplateSpecializationKind TSK,
468 bool Complain /*= true*/) {
469 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation));
470
471 if (PatternDef && (isa<FunctionDecl>(PatternDef)
472 || !cast<TagDecl>(PatternDef)->isBeingDefined())) {
473 NamedDecl *SuggestedDef = nullptr;
474 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
475 /*OnlyNeedComplete*/false)) {
476 // If we're allowed to diagnose this and recover, do so.
477 bool Recover = Complain && !isSFINAEContext();
478 if (Complain)
479 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
480 Sema::MissingImportKind::Definition, Recover);
481 return !Recover;
482 }
483 return false;
484 }
485
486
487 QualType InstantiationTy;
488 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
489 InstantiationTy = Context.getTypeDeclType(TD);
490 else
491 InstantiationTy = cast<FunctionDecl>(Instantiation)->getType();
492 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
493 // Say nothing
494 } else if (PatternDef) {
495 Diag(PointOfInstantiation,
496 diag::err_template_instantiate_within_definition)
497 << (TSK != TSK_ImplicitInstantiation)
498 << InstantiationTy;
499 // Not much point in noting the template declaration here, since
500 // we're lexically inside it.
501 Instantiation->setInvalidDecl();
502 } else if (InstantiatedFromMember) {
503 Diag(PointOfInstantiation,
504 diag::err_implicit_instantiate_member_undefined)
505 << InstantiationTy;
506 Diag(Pattern->getLocation(), diag::note_member_declared_at);
507 } else {
508 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
509 << (TSK != TSK_ImplicitInstantiation)
510 << InstantiationTy;
511 Diag(Pattern->getLocation(), diag::note_template_decl_here);
512 }
513
514 // In general, Instantiation isn't marked invalid to get more than one
515 // error for multiple undefined instantiations. But the code that does
516 // explicit declaration -> explicit definition conversion can't handle
517 // invalid declarations, so mark as invalid in that case.
518 if (TSK == TSK_ExplicitInstantiationDeclaration)
519 Instantiation->setInvalidDecl();
520 return true;
521}
522
Douglas Gregor5101c242008-12-05 18:15:24 +0000523/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
524/// that the template parameter 'PrevDecl' is being shadowed by a new
525/// declaration at location Loc. Returns true to indicate that this is
526/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000527void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000528 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000529
530 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000531 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000532 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000533
534 // C++ [temp.local]p4:
535 // A template-parameter shall not be redeclared within its
536 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000537 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000538 << cast<NamedDecl>(PrevDecl)->getDeclName();
539 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000540}
541
Douglas Gregor463421d2009-03-03 04:44:36 +0000542/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000543/// the parameter D to reference the templated declaration and return a pointer
544/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000545TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
546 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
547 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000548 return Temp;
549 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000551}
552
Douglas Gregoreb29d182011-01-05 17:40:24 +0000553ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
554 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000556 "Only template template arguments can be pack expansions here");
557 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
558 "Template template argument pack expansion without packs");
559 ParsedTemplateArgument Result(*this);
560 Result.EllipsisLoc = EllipsisLoc;
561 return Result;
562}
563
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000564static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
565 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000567 switch (Arg.getKind()) {
568 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000569 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000570 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000572 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000573 return TemplateArgumentLoc(TemplateArgument(T), DI);
574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000576 case ParsedTemplateArgument::NonType: {
577 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
578 return TemplateArgumentLoc(TemplateArgument(E), E);
579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000581 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000582 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000583 TemplateArgument TArg;
584 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000585 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000586 else
587 TArg = Template;
588 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000589 Arg.getScopeSpec().getWithLocInContext(
590 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000591 Arg.getLocation(),
592 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000593 }
594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000596 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000597}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000599/// \brief Translates template arguments as provided by the parser
600/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000601void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
602 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000603 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000604 TemplateArgs.addArgument(translateTemplateArgument(*this,
605 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000606}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Richard Smithb80d5402013-06-25 22:21:36 +0000608static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
609 SourceLocation Loc,
610 IdentifierInfo *Name) {
611 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
612 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
613 if (PrevDecl && PrevDecl->isTemplateParameter())
614 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
615}
616
Douglas Gregor5101c242008-12-05 18:15:24 +0000617/// ActOnTypeParameter - Called when a C++ template type parameter
618/// (e.g., "typename T") has been parsed. Typename specifies whether
619/// the keyword "typename" was used to declare the type parameter
620/// (otherwise, "class" was used), and KeyLoc is the location of the
621/// "class" or "typename" keyword. ParamName is the name of the
622/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000623/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000624/// If the type parameter has a default argument, it will be added
625/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000626Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000627 SourceLocation EllipsisLoc,
628 SourceLocation KeyLoc,
629 IdentifierInfo *ParamName,
630 SourceLocation ParamNameLoc,
631 unsigned Depth, unsigned Position,
632 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000633 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000634 assert(S->isTemplateParamScope() &&
635 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000636
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000637 SourceLocation Loc = ParamNameLoc;
638 if (!ParamName)
639 Loc = KeyLoc;
640
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000641 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000642 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000643 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000644 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000645 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000646 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000647
648 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000649 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
650
Douglas Gregor5101c242008-12-05 18:15:24 +0000651 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000652 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000653 IdResolver.AddDecl(Param);
654 }
655
Douglas Gregorf5500772011-01-05 15:48:55 +0000656 // C++0x [temp.param]p9:
657 // A default template-argument may be specified for any kind of
658 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000659 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000660 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000661 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000662 }
663
Douglas Gregordc13ded2010-07-01 00:00:45 +0000664 // Handle the default argument, if provided.
665 if (DefaultArg) {
666 TypeSourceInfo *DefaultTInfo;
667 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668
Douglas Gregordc13ded2010-07-01 00:00:45 +0000669 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000671 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000673 UPPC_DefaultArgument))
674 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Douglas Gregordc13ded2010-07-01 00:00:45 +0000676 // Check the template argument itself.
677 if (CheckTemplateArgument(Param, DefaultTInfo)) {
678 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000679 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
Richard Smith1469b912015-06-10 00:29:03 +0000682 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684
John McCall48871652010-08-21 09:40:31 +0000685 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000686}
687
Douglas Gregor463421d2009-03-03 04:44:36 +0000688/// \brief Check that the type of a non-type template parameter is
689/// well-formed.
690///
691/// \returns the (possibly-promoted) parameter type if valid;
692/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000693QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000694Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000695 // We don't allow variably-modified types as the type of non-type template
696 // parameters.
697 if (T->isVariablyModifiedType()) {
698 Diag(Loc, diag::err_variably_modified_nontype_template_param)
699 << T;
700 return QualType();
701 }
702
Douglas Gregor463421d2009-03-03 04:44:36 +0000703 // C++ [temp.param]p4:
704 //
705 // A non-type template-parameter shall have one of the following
706 // (optionally cv-qualified) types:
707 //
708 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000709 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000710 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000711 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000712 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000713 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000714 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000715 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000716 // -- std::nullptr_t.
717 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000718 // If T is a dependent type, we can't do the check now, so we
719 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000720 T->isDependentType()) {
721 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
722 // are ignored when determining its type.
723 return T.getUnqualifiedType();
724 }
725
Douglas Gregor463421d2009-03-03 04:44:36 +0000726 // C++ [temp.param]p8:
727 //
728 // A non-type template-parameter of type "array of T" or
729 // "function returning T" is adjusted to be of type "pointer to
730 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000731 else if (T->isArrayType() || T->isFunctionType())
732 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733
Douglas Gregor463421d2009-03-03 04:44:36 +0000734 Diag(Loc, diag::err_template_nontype_parm_bad_type)
735 << T;
736
737 return QualType();
738}
739
John McCall48871652010-08-21 09:40:31 +0000740Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
741 unsigned Depth,
742 unsigned Position,
743 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000744 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000745 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
746 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000747
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000748 assert(S->isTemplateParamScope() &&
749 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000750 bool Invalid = false;
751
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000752 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
753 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000754 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000755 Invalid = true;
756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757
Richard Smithb80d5402013-06-25 22:21:36 +0000758 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000759 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000760 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000761 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000762 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000763 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000765 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000766 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000767
Douglas Gregor5101c242008-12-05 18:15:24 +0000768 if (Invalid)
769 Param->setInvalidDecl();
770
Richard Smithb80d5402013-06-25 22:21:36 +0000771 if (ParamName) {
772 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
773 ParamName);
774
Douglas Gregor5101c242008-12-05 18:15:24 +0000775 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000776 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000777 IdResolver.AddDecl(Param);
778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Douglas Gregorf5500772011-01-05 15:48:55 +0000780 // C++0x [temp.param]p9:
781 // A default template-argument may be specified for any kind of
782 // template-parameter that is not a template parameter pack.
783 if (Default && IsParameterPack) {
784 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000785 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000786 }
787
Douglas Gregordc13ded2010-07-01 00:00:45 +0000788 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000789 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000790 // Check for unexpanded parameter packs.
791 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
792 return Param;
793
Douglas Gregordc13ded2010-07-01 00:00:45 +0000794 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000795 ExprResult DefaultRes =
796 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000797 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000798 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000799 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000800 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000801 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Richard Smith1469b912015-06-10 00:29:03 +0000803 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
John McCall48871652010-08-21 09:40:31 +0000806 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000807}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000808
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000809/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000810/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000811/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000812Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
813 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000814 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000815 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000816 IdentifierInfo *Name,
817 SourceLocation NameLoc,
818 unsigned Depth,
819 unsigned Position,
820 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000821 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000822 assert(S->isTemplateParamScope() &&
823 "Template template parameter not in template parameter scope!");
824
825 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000826 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000827 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000828 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829 NameLoc.isInvalid()? TmpLoc : NameLoc,
830 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000831 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000832 Param->setAccess(AS_public);
833
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000835 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000836 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000837 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
838
John McCall48871652010-08-21 09:40:31 +0000839 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000840 IdResolver.AddDecl(Param);
841 }
842
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000843 if (Params->size() == 0) {
844 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
845 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
846 Param->setInvalidDecl();
847 }
848
Douglas Gregorf5500772011-01-05 15:48:55 +0000849 // C++0x [temp.param]p9:
850 // A default template-argument may be specified for any kind of
851 // template-parameter that is not a template parameter pack.
852 if (IsParameterPack && !Default.isInvalid()) {
853 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
854 Default = ParsedTemplateArgument();
855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856
Douglas Gregordc13ded2010-07-01 00:00:45 +0000857 if (!Default.isInvalid()) {
858 // Check only that we have a template template argument. We don't want to
859 // try to check well-formedness now, because our template template parameter
860 // might have dependent types in its template parameters, which we wouldn't
861 // be able to match now.
862 //
863 // If none of the template template parameter's template arguments mention
864 // other template parameters, we could actually perform more checking here.
865 // However, it isn't worth doing.
866 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
867 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000868 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000869 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000870 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000871 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000872
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000873 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000875 DefaultArg.getArgument().getAsTemplate(),
876 UPPC_DefaultArgument))
877 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Richard Smith1469b912015-06-10 00:29:03 +0000879 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
John McCall48871652010-08-21 09:40:31 +0000882 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000883}
884
Hubert Tongf608c052016-04-29 18:05:37 +0000885/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
886/// constrained by RequiresClause, that contains the template parameters in
887/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000888TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000889Sema::ActOnTemplateParameterList(unsigned Depth,
890 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000891 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000892 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000893 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000894 SourceLocation RAngleLoc,
895 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000896 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000897 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000898
David Majnemer902f8c62015-12-27 07:16:27 +0000899 return TemplateParameterList::Create(
900 Context, TemplateLoc, LAngleLoc,
901 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000902 RAngleLoc, RequiresClause);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000903}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000904
John McCall3e11ebe2010-03-15 10:12:16 +0000905static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
906 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000907 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000908}
909
John McCallfaf5fb42010-08-26 23:41:50 +0000910DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000911Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000912 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000913 IdentifierInfo *Name, SourceLocation NameLoc,
914 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000915 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000916 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000917 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000918 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000919 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000920 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000921 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000922 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000923 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000924 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000925
926 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000927 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000928 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000929
Abramo Bagnara6150c882010-05-11 21:36:43 +0000930 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
931 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932
933 // There is no such thing as an unnamed class template.
934 if (!Name) {
935 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000936 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000937 }
938
Richard Smith6483d222012-04-21 01:27:54 +0000939 // Find any previous declaration with this name. For a friend with no
940 // scope explicitly specified, we only look for tag declarations (per
941 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000942 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000943 LookupResult Previous(*this, Name, NameLoc,
944 (SS.isEmpty() && TUK == TUK_Friend)
945 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000946 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000947 if (SS.isNotEmpty() && !SS.isInvalid()) {
948 SemanticContext = computeDeclContext(SS, true);
949 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000950 // FIXME: Horrible, horrible hack! We can't currently represent this
951 // in the AST, and historically we have just ignored such friend
952 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000953 Diag(NameLoc, TUK == TUK_Friend
954 ? diag::warn_template_qualified_friend_ignored
955 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000956 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000957 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000958 }
Mike Stump11289f42009-09-09 15:08:12 +0000959
John McCall0b66eb32010-05-01 00:40:08 +0000960 if (RequireCompleteDeclContext(SS, SemanticContext))
961 return true;
962
Douglas Gregor041b0842011-10-14 15:31:12 +0000963 // If we're adding a template to a dependent context, we may need to
964 // rebuilding some of the types used within the template parameter list,
965 // now that we know what the current instantiation is.
966 if (SemanticContext->isDependentContext()) {
967 ContextRAII SavedContext(*this, SemanticContext);
968 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
969 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000970 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
971 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000972
John McCall27b18f82009-11-17 02:14:36 +0000973 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000974 } else {
975 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000976
977 // C++14 [class.mem]p14:
978 // If T is the name of a class, then each of the following shall have a
979 // name different from T:
980 // -- every member template of class T
981 if (TUK != TUK_Friend &&
982 DiagnoseClassNameShadow(SemanticContext,
983 DeclarationNameInfo(Name, NameLoc)))
984 return true;
985
John McCall27b18f82009-11-17 02:14:36 +0000986 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000987 }
Mike Stump11289f42009-09-09 15:08:12 +0000988
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000989 if (Previous.isAmbiguous())
990 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991
Craig Topperc3ec1492014-05-26 06:22:03 +0000992 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000993 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000994 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000995
Serge Pavlove50bf752016-06-10 04:39:07 +0000996 if (PrevDecl && PrevDecl->isTemplateParameter()) {
997 // Maybe we will complain about the shadowed template parameter.
998 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
999 // Just pretend that we didn't see the previous declaration.
1000 PrevDecl = nullptr;
1001 }
1002
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001003 // If there is a previous declaration with the same name, check
1004 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +00001005 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001006 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001007
1008 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001010 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001012 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1013 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +00001015 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1016 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1017 PrevClassTemplate
1018 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1019 ->getSpecializedTemplate();
1020 }
1021 }
1022
John McCalld43784f2009-12-18 11:25:59 +00001023 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +00001024 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001025 // [...] When looking for a prior declaration of a class or a function
1026 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +00001027 // function is neither a qualified name nor a template-id, scopes outside
1028 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +00001029 if (!SS.isSet()) {
1030 DeclContext *OutermostContext = CurContext;
1031 while (!OutermostContext->isFileContext())
1032 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +00001033
Richard Smith61e582f2012-04-20 07:12:26 +00001034 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +00001035 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1036 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1037 SemanticContext = PrevDecl->getDeclContext();
1038 } else {
1039 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001040 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +00001041 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001042 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +00001043 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +00001044
1045 // Check that the chosen semantic context doesn't already contain a
1046 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +00001047 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +00001048 DeclContext *LookupContext = SemanticContext;
1049 while (LookupContext->isTransparentContext())
1050 LookupContext = LookupContext->getLookupParent();
1051 LookupQualifiedName(Previous, LookupContext);
1052
1053 if (Previous.isAmbiguous())
1054 return true;
1055
1056 if (Previous.begin() != Previous.end())
1057 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +00001058 }
John McCall90d3bb92009-12-17 23:21:11 +00001059 }
Richard Smith72bcaec2013-12-05 04:30:04 +00001060 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +00001061 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1062 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001063 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064
Richard Smithfc805ca2015-07-06 04:43:58 +00001065 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1066 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1067 if (SS.isEmpty() &&
1068 !(PrevClassTemplate &&
1069 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1070 SemanticContext->getRedeclContext()))) {
1071 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1072 Diag(Shadow->getTargetDecl()->getLocation(),
1073 diag::note_using_decl_target);
1074 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1075 // Recover by ignoring the old declaration.
1076 PrevDecl = PrevClassTemplate = nullptr;
1077 }
1078 }
1079
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001080 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001081 // Ensure that the template parameter lists are compatible. Skip this check
1082 // for a friend in a dependent context: the template parameter list itself
1083 // could be dependent.
1084 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1085 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001086 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001087 /*Complain=*/true,
1088 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001089 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001090
1091 // C++ [temp.class]p4:
1092 // In a redeclaration, partial specialization, explicit
1093 // specialization or explicit instantiation of a class template,
1094 // the class-key shall agree in kind with the original class
1095 // template declaration (7.1.5.3).
1096 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001097 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001098 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001099 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001100 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001101 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001102 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001103 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001104 }
1105
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001106 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001107 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001108 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001109 // If we have a prior definition that is not visible, treat this as
1110 // simply making that previous definition visible.
1111 NamedDecl *Hidden = nullptr;
1112 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001113 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001114 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1115 assert(Tmpl && "original definition of a class template is not a "
1116 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001117 makeMergedDefinitionVisible(Hidden, KWLoc);
1118 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001119 return Def;
1120 }
1121
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001122 Diag(NameLoc, diag::err_redefinition) << Name;
1123 Diag(Def->getLocation(), diag::note_previous_definition);
1124 // FIXME: Would it make sense to try to "forget" the previous
1125 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001126 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001127 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001128 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001129 } else if (PrevDecl) {
1130 // C++ [temp]p5:
1131 // A class template shall not have the same name as any other
1132 // template, class, function, object, enumeration, enumerator,
1133 // namespace, or type in the same scope (3.3), except as specified
1134 // in (14.5.4).
1135 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1136 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001137 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001138 }
1139
Douglas Gregordba32632009-02-10 19:49:53 +00001140 // Check the template parameter list of this declaration, possibly
1141 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001142 // template declaration. Skip this check for a friend in a dependent
1143 // context, because the template parameter list might be dependent.
1144 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001145 CheckTemplateParameterList(
1146 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001147 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1148 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001149 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1150 SemanticContext->isDependentContext())
1151 ? TPC_ClassTemplateMember
1152 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1153 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001154 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001155
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001156 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001158 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001159 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1160 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001161 : diag::err_member_decl_does_not_match)
1162 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001163 Invalid = true;
1164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165 }
1166
Mike Stump11289f42009-09-09 15:08:12 +00001167 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001168 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001169 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001170 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001171 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001172 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001173 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001174 NewClass->setTemplateParameterListsInfo(
1175 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1176 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001177
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001178 // Add alignment attributes if necessary; these attributes are checked when
1179 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001180 if (TUK == TUK_Definition) {
1181 AddAlignmentAttributesForRecord(NewClass);
1182 AddMsStructLayoutForRecord(NewClass);
1183 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001184
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001185 ClassTemplateDecl *NewTemplate
1186 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1187 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001188 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001189 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001190
Douglas Gregor21823bf2011-12-20 18:11:52 +00001191 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001192 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001193
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001194 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001195 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001196 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001197 assert(T->isDependentType() && "Class template type is not dependent?");
1198 (void)T;
1199
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001200 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001201 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001203 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1204 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205
Anders Carlsson137108d2009-03-26 01:24:28 +00001206 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001207 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001208 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001210 // Set the lexical context of these templates
1211 NewClass->setLexicalDeclContext(CurContext);
1212 NewTemplate->setLexicalDeclContext(CurContext);
1213
John McCall9bb74a52009-07-31 02:45:11 +00001214 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001215 NewClass->startDefinition();
1216
1217 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001218 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001219
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001220 if (PrevClassTemplate)
1221 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1222
Rafael Espindola385c0422012-07-13 18:04:45 +00001223 AddPushedVisibilityAttribute(NewClass);
1224
Richard Smith234ff472014-08-23 00:49:01 +00001225 if (TUK != TUK_Friend) {
1226 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1227 Scope *Outer = S;
1228 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1229 Outer = Outer->getParent();
1230 PushOnScopeChains(NewTemplate, Outer);
1231 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001232 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001233 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001234 NewClass->setAccess(PrevClassTemplate->getAccess());
1235 }
John McCall27b5c252009-09-14 21:59:20 +00001236
Richard Smith64017682013-07-17 23:53:16 +00001237 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238
John McCall27b5c252009-09-14 21:59:20 +00001239 // Friend templates are visible in fairly strange ways.
1240 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001241 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001242 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001243 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1244 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001245 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001247
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001248 FriendDecl *Friend = FriendDecl::Create(
1249 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001250 Friend->setAccess(AS_public);
1251 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001252 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001253
Douglas Gregordba32632009-02-10 19:49:53 +00001254 if (Invalid) {
1255 NewTemplate->setInvalidDecl();
1256 NewClass->setInvalidDecl();
1257 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001258
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001259 ActOnDocumentableDecl(NewTemplate);
1260
John McCall48871652010-08-21 09:40:31 +00001261 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001262}
1263
Douglas Gregored5731f2009-11-25 17:50:39 +00001264/// \brief Diagnose the presence of a default template argument on a
1265/// template parameter, which is ill-formed in certain contexts.
1266///
1267/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001269 Sema::TemplateParamListContext TPC,
1270 SourceLocation ParamLoc,
1271 SourceRange DefArgRange) {
1272 switch (TPC) {
1273 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001274 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001275 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001276 return false;
1277
1278 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001279 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001281 // A default template-argument shall not be specified in a
1282 // function template declaration or a function template
1283 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001284 // If a friend function template declaration specifies a default
1285 // template-argument, that declaration shall be a definition and shall be
1286 // the only declaration of the function template in the translation unit.
1287 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001288 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001289 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1290 : diag::ext_template_parameter_default_in_function_template)
1291 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001292 return false;
1293
1294 case Sema::TPC_ClassTemplateMember:
1295 // C++0x [temp.param]p9:
1296 // A default template-argument shall not be specified in the
1297 // template-parameter-lists of the definition of a member of a
1298 // class template that appears outside of the member's class.
1299 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1300 << DefArgRange;
1301 return true;
1302
David Majnemerba8f17a2013-06-25 22:08:55 +00001303 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001304 case Sema::TPC_FriendFunctionTemplate:
1305 // C++ [temp.param]p9:
1306 // A default template-argument shall not be specified in a
1307 // friend template declaration.
1308 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1309 << DefArgRange;
1310 return true;
1311
1312 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1313 // for friend function templates if there is only a single
1314 // declaration (and it is a definition). Strange!
1315 }
1316
David Blaikie8a40f702012-01-17 06:56:22 +00001317 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001318}
1319
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001320/// \brief Check for unexpanded parameter packs within the template parameters
1321/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001322static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1323 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001324 // A template template parameter which is a parameter pack is also a pack
1325 // expansion.
1326 if (TTP->isParameterPack())
1327 return false;
1328
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001329 TemplateParameterList *Params = TTP->getTemplateParameters();
1330 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1331 NamedDecl *P = Params->getParam(I);
1332 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001333 if (!NTTP->isParameterPack() &&
1334 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001335 NTTP->getTypeSourceInfo(),
1336 Sema::UPPC_NonTypeTemplateParameterType))
1337 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001338
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001339 continue;
1340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341
1342 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001343 = dyn_cast<TemplateTemplateParmDecl>(P))
1344 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1345 return true;
1346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001348 return false;
1349}
1350
Douglas Gregordba32632009-02-10 19:49:53 +00001351/// \brief Checks the validity of a template parameter list, possibly
1352/// considering the template parameter list from a previous
1353/// declaration.
1354///
1355/// If an "old" template parameter list is provided, it must be
1356/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1357/// template parameter list.
1358///
1359/// \param NewParams Template parameter list for a new template
1360/// declaration. This template parameter list will be updated with any
1361/// default arguments that are carried through from the previous
1362/// template parameter list.
1363///
1364/// \param OldParams If provided, template parameter list from a
1365/// previous declaration of the same template. Default template
1366/// arguments will be merged from the old template parameter list to
1367/// the new template parameter list.
1368///
Douglas Gregored5731f2009-11-25 17:50:39 +00001369/// \param TPC Describes the context in which we are checking the given
1370/// template parameter list.
1371///
Douglas Gregordba32632009-02-10 19:49:53 +00001372/// \returns true if an error occurred, false otherwise.
1373bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001374 TemplateParameterList *OldParams,
1375 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001376 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001377
Douglas Gregordba32632009-02-10 19:49:53 +00001378 // C++ [temp.param]p10:
1379 // The set of default template-arguments available for use with a
1380 // template declaration or definition is obtained by merging the
1381 // default arguments from the definition (if in scope) and all
1382 // declarations in scope in the same way default function
1383 // arguments are (8.3.6).
1384 bool SawDefaultArgument = false;
1385 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001386
Mike Stumpc89c8e32009-02-11 23:03:27 +00001387 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001388 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001389 if (OldParams)
1390 OldParam = OldParams->begin();
1391
Douglas Gregor0693def2011-01-27 01:40:17 +00001392 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001393 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1394 NewParamEnd = NewParams->end();
1395 NewParam != NewParamEnd; ++NewParam) {
1396 // Variables used to diagnose redundant default arguments
1397 bool RedundantDefaultArg = false;
1398 SourceLocation OldDefaultLoc;
1399 SourceLocation NewDefaultLoc;
1400
David Blaikie651c73c2011-10-19 05:19:50 +00001401 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001402 bool MissingDefaultArg = false;
1403
David Blaikie651c73c2011-10-19 05:19:50 +00001404 // Variable used to diagnose non-final parameter packs
1405 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001406
Douglas Gregordba32632009-02-10 19:49:53 +00001407 if (TemplateTypeParmDecl *NewTypeParm
1408 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001409 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410 if (NewTypeParm->hasDefaultArgument() &&
1411 DiagnoseDefaultTemplateArgument(*this, TPC,
1412 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001413 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001414 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001415 NewTypeParm->removeDefaultArgument();
1416
1417 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001418 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001419 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001420 if (NewTypeParm->isParameterPack()) {
1421 assert(!NewTypeParm->hasDefaultArgument() &&
1422 "Parameter packs can't have a default argument!");
1423 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001424 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001425 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001426 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1427 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1428 SawDefaultArgument = true;
1429 RedundantDefaultArg = true;
1430 PreviousDefaultArgLoc = NewDefaultLoc;
1431 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1432 // Merge the default argument from the old declaration to the
1433 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001434 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001435 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1436 } else if (NewTypeParm->hasDefaultArgument()) {
1437 SawDefaultArgument = true;
1438 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1439 } else if (SawDefaultArgument)
1440 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001441 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001442 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001443 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001444 if (!NewNonTypeParm->isParameterPack() &&
1445 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001447 UPPC_NonTypeTemplateParameterType)) {
1448 Invalid = true;
1449 continue;
1450 }
1451
Douglas Gregored5731f2009-11-25 17:50:39 +00001452 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453 if (NewNonTypeParm->hasDefaultArgument() &&
1454 DiagnoseDefaultTemplateArgument(*this, TPC,
1455 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001456 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001457 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001458 }
1459
Mike Stump12b8ce12009-08-04 21:02:39 +00001460 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001461 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001462 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001463 if (NewNonTypeParm->isParameterPack()) {
1464 assert(!NewNonTypeParm->hasDefaultArgument() &&
1465 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001466 if (!NewNonTypeParm->isPackExpansion())
1467 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001468 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001469 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001470 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1471 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1472 SawDefaultArgument = true;
1473 RedundantDefaultArg = true;
1474 PreviousDefaultArgLoc = NewDefaultLoc;
1475 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1476 // Merge the default argument from the old declaration to the
1477 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001478 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001479 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1480 } else if (NewNonTypeParm->hasDefaultArgument()) {
1481 SawDefaultArgument = true;
1482 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1483 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001484 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001485 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001486 TemplateTemplateParmDecl *NewTemplateParm
1487 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001489 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001490 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001491 Invalid = true;
1492 continue;
1493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494
David Blaikie651c73c2011-10-19 05:19:50 +00001495 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496 if (NewTemplateParm->hasDefaultArgument() &&
1497 DiagnoseDefaultTemplateArgument(*this, TPC,
1498 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001499 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001500 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001501
1502 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001503 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001504 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001505 if (NewTemplateParm->isParameterPack()) {
1506 assert(!NewTemplateParm->hasDefaultArgument() &&
1507 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001508 if (!NewTemplateParm->isPackExpansion())
1509 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001510 } else if (OldTemplateParm &&
1511 hasVisibleDefaultArgument(OldTemplateParm) &&
1512 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001513 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1514 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001515 SawDefaultArgument = true;
1516 RedundantDefaultArg = true;
1517 PreviousDefaultArgLoc = NewDefaultLoc;
1518 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1519 // Merge the default argument from the old declaration to the
1520 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001521 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001522 PreviousDefaultArgLoc
1523 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001524 } else if (NewTemplateParm->hasDefaultArgument()) {
1525 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001526 PreviousDefaultArgLoc
1527 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001528 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001529 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001530 }
1531
Richard Smith1fde8ec2012-09-07 02:06:42 +00001532 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001533 // If a template parameter of a primary class template or alias template
1534 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001535 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001536 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1537 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001538 Diag((*NewParam)->getLocation(),
1539 diag::err_template_param_pack_must_be_last_template_parameter);
1540 Invalid = true;
1541 }
1542
Douglas Gregordba32632009-02-10 19:49:53 +00001543 if (RedundantDefaultArg) {
1544 // C++ [temp.param]p12:
1545 // A template-parameter shall not be given default arguments
1546 // by two different declarations in the same scope.
1547 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1548 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1549 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001550 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001551 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552 // If a template-parameter of a class template has a default
1553 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001554 // have a default template-argument supplied or be a template parameter
1555 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001556 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001557 diag::err_template_param_default_arg_missing);
1558 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1559 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001560 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001561 }
1562
1563 // If we have an old template parameter list that we're merging
1564 // in, move on to the next parameter.
1565 if (OldParams)
1566 ++OldParam;
1567 }
1568
Douglas Gregor0693def2011-01-27 01:40:17 +00001569 // We were missing some default arguments at the end of the list, so remove
1570 // all of the default arguments.
1571 if (RemoveDefaultArguments) {
1572 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1573 NewParamEnd = NewParams->end();
1574 NewParam != NewParamEnd; ++NewParam) {
1575 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1576 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001578 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1579 NTTP->removeDefaultArgument();
1580 else
1581 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1582 }
1583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001584
Douglas Gregordba32632009-02-10 19:49:53 +00001585 return Invalid;
1586}
Douglas Gregord32e0282009-02-09 23:23:08 +00001587
John McCalla020a012010-10-20 05:44:58 +00001588namespace {
1589
1590/// A class which looks for a use of a certain level of template
1591/// parameter.
1592struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1593 typedef RecursiveASTVisitor<DependencyChecker> super;
1594
1595 unsigned Depth;
1596 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001597 SourceLocation MatchLoc;
1598
1599 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001600
1601 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1602 NamedDecl *ND = Params->getParam(0);
1603 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1604 Depth = PD->getDepth();
1605 } else if (NonTypeTemplateParmDecl *PD =
1606 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1607 Depth = PD->getDepth();
1608 } else {
1609 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1610 }
1611 }
1612
Richard Smith6056d5e2014-02-09 00:54:43 +00001613 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001614 if (ParmDepth >= Depth) {
1615 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001616 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001617 return true;
1618 }
1619 return false;
1620 }
1621
Richard Smith6056d5e2014-02-09 00:54:43 +00001622 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1623 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1624 }
1625
John McCalla020a012010-10-20 05:44:58 +00001626 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1627 return !Matches(T->getDepth());
1628 }
1629
1630 bool TraverseTemplateName(TemplateName N) {
1631 if (TemplateTemplateParmDecl *PD =
1632 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001633 if (Matches(PD->getDepth()))
1634 return false;
John McCalla020a012010-10-20 05:44:58 +00001635 return super::TraverseTemplateName(N);
1636 }
1637
1638 bool VisitDeclRefExpr(DeclRefExpr *E) {
1639 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001640 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1641 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001642 return false;
John McCalla020a012010-10-20 05:44:58 +00001643 return super::VisitDeclRefExpr(E);
1644 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001645
1646 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1647 return TraverseType(T->getReplacementType());
1648 }
1649
1650 bool
1651 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1652 return TraverseTemplateArgument(T->getArgumentPack());
1653 }
1654
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001655 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1656 return TraverseType(T->getInjectedSpecializationType());
1657 }
John McCalla020a012010-10-20 05:44:58 +00001658};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001659} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001660
Douglas Gregor972fe532011-05-10 18:27:06 +00001661/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001662/// list.
1663static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001664DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001665 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001666 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001667 return Checker.Match;
1668}
1669
Douglas Gregor972fe532011-05-10 18:27:06 +00001670// Find the source range corresponding to the named type in the given
1671// nested-name-specifier, if any.
1672static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1673 QualType T,
1674 const CXXScopeSpec &SS) {
1675 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1676 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1677 if (const Type *CurType = NNS->getAsType()) {
1678 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1679 return NNSLoc.getTypeLoc().getSourceRange();
1680 } else
1681 break;
1682
1683 NNSLoc = NNSLoc.getPrefix();
1684 }
1685
1686 return SourceRange();
1687}
1688
Mike Stump11289f42009-09-09 15:08:12 +00001689/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001690/// specifier, returning the template parameter list that applies to the
1691/// name.
1692///
1693/// \param DeclStartLoc the start of the declaration that has a scope
1694/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001695///
Douglas Gregor972fe532011-05-10 18:27:06 +00001696/// \param DeclLoc The location of the declaration itself.
1697///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001698/// \param SS the scope specifier that will be matched to the given template
1699/// parameter lists. This scope specifier precedes a qualified name that is
1700/// being declared.
1701///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001702/// \param TemplateId The template-id following the scope specifier, if there
1703/// is one. Used to check for a missing 'template<>'.
1704///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001705/// \param ParamLists the template parameter lists, from the outermost to the
1706/// innermost template parameter lists.
1707///
John McCalle820e5e2010-04-13 20:37:33 +00001708/// \param IsFriend Whether to apply the slightly different rules for
1709/// matching template parameters to scope specifiers in friend
1710/// declarations.
1711///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001712/// \param IsExplicitSpecialization will be set true if the entity being
1713/// declared is an explicit specialization, false otherwise.
1714///
Mike Stump11289f42009-09-09 15:08:12 +00001715/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001716/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001717/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001718/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001719/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001720/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001721TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1722 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001723 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001724 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1725 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001726 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001727 Invalid = false;
1728
1729 // The sequence of nested types to which we will match up the template
1730 // parameter lists. We first build this list by starting with the type named
1731 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001732 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001733 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001734 if (SS.getScopeRep()) {
1735 if (CXXRecordDecl *Record
1736 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1737 T = Context.getTypeDeclType(Record);
1738 else
1739 T = QualType(SS.getScopeRep()->getAsType(), 0);
1740 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001741
1742 // If we found an explicit specialization that prevents us from needing
1743 // 'template<>' headers, this will be set to the location of that
1744 // explicit specialization.
1745 SourceLocation ExplicitSpecLoc;
1746
1747 while (!T.isNull()) {
1748 NestedTypes.push_back(T);
1749
1750 // Retrieve the parent of a record type.
1751 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1752 // If this type is an explicit specialization, we're done.
1753 if (ClassTemplateSpecializationDecl *Spec
1754 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1755 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1756 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1757 ExplicitSpecLoc = Spec->getLocation();
1758 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001759 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001760 } else if (Record->getTemplateSpecializationKind()
1761 == TSK_ExplicitSpecialization) {
1762 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001763 break;
1764 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001765
1766 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1767 T = Context.getTypeDeclType(Parent);
1768 else
1769 T = QualType();
1770 continue;
1771 }
1772
1773 if (const TemplateSpecializationType *TST
1774 = T->getAs<TemplateSpecializationType>()) {
1775 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1776 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1777 T = Context.getTypeDeclType(Parent);
1778 else
1779 T = QualType();
1780 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001781 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001782 }
1783
1784 // Look one step prior in a dependent template specialization type.
1785 if (const DependentTemplateSpecializationType *DependentTST
1786 = T->getAs<DependentTemplateSpecializationType>()) {
1787 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1788 T = QualType(NNS->getAsType(), 0);
1789 else
1790 T = QualType();
1791 continue;
1792 }
1793
1794 // Look one step prior in a dependent name type.
1795 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1796 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1797 T = QualType(NNS->getAsType(), 0);
1798 else
1799 T = QualType();
1800 continue;
1801 }
1802
1803 // Retrieve the parent of an enumeration type.
1804 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1805 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1806 // check here.
1807 EnumDecl *Enum = EnumT->getDecl();
1808
1809 // Get to the parent type.
1810 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1811 T = Context.getTypeDeclType(Parent);
1812 else
1813 T = QualType();
1814 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001815 }
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregor972fe532011-05-10 18:27:06 +00001817 T = QualType();
1818 }
1819 // Reverse the nested types list, since we want to traverse from the outermost
1820 // to the innermost while checking template-parameter-lists.
1821 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001822
Douglas Gregor972fe532011-05-10 18:27:06 +00001823 // C++0x [temp.expl.spec]p17:
1824 // A member or a member template may be nested within many
1825 // enclosing class templates. In an explicit specialization for
1826 // such a member, the member declaration shall be preceded by a
1827 // template<> for each enclosing class template that is
1828 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001829 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001830
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001831 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001832 if (SawNonEmptyTemplateParameterList) {
1833 Diag(DeclLoc, diag::err_specialize_member_of_template)
1834 << !Recovery << Range;
1835 Invalid = true;
1836 IsExplicitSpecialization = false;
1837 return true;
1838 }
1839
1840 return false;
1841 };
1842
1843 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1844 // Check that we can have an explicit specialization here.
1845 if (CheckExplicitSpecialization(Range, true))
1846 return true;
1847
1848 // We don't have a template header, but we should.
1849 SourceLocation ExpectedTemplateLoc;
1850 if (!ParamLists.empty())
1851 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1852 else
1853 ExpectedTemplateLoc = DeclStartLoc;
1854
1855 Diag(DeclLoc, diag::err_template_spec_needs_header)
1856 << Range
1857 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1858 return false;
1859 };
1860
Douglas Gregor972fe532011-05-10 18:27:06 +00001861 unsigned ParamIdx = 0;
1862 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1863 ++TypeIdx) {
1864 T = NestedTypes[TypeIdx];
1865
1866 // Whether we expect a 'template<>' header.
1867 bool NeedEmptyTemplateHeader = false;
1868
1869 // Whether we expect a template header with parameters.
1870 bool NeedNonemptyTemplateHeader = false;
1871
1872 // For a dependent type, the set of template parameters that we
1873 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001874 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001875
Douglas Gregor373af9b2011-05-11 23:26:17 +00001876 // C++0x [temp.expl.spec]p15:
1877 // A member or a member template may be nested within many enclosing
1878 // class templates. In an explicit specialization for such a member, the
1879 // member declaration shall be preceded by a template<> for each
1880 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001881 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1882 if (ClassTemplatePartialSpecializationDecl *Partial
1883 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1884 ExpectedTemplateParams = Partial->getTemplateParameters();
1885 NeedNonemptyTemplateHeader = true;
1886 } else if (Record->isDependentType()) {
1887 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001888 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001889 ->getTemplateParameters();
1890 NeedNonemptyTemplateHeader = true;
1891 }
1892 } else if (ClassTemplateSpecializationDecl *Spec
1893 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1894 // C++0x [temp.expl.spec]p4:
1895 // Members of an explicitly specialized class template are defined
1896 // in the same manner as members of normal classes, and not using
1897 // the template<> syntax.
1898 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1899 NeedEmptyTemplateHeader = true;
1900 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001901 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001902 } else if (Record->getTemplateSpecializationKind()) {
1903 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001904 != TSK_ExplicitSpecialization &&
1905 TypeIdx == NumTypes - 1)
1906 IsExplicitSpecialization = true;
1907
1908 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001909 }
1910 } else if (const TemplateSpecializationType *TST
1911 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001912 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001913 ExpectedTemplateParams = Template->getTemplateParameters();
1914 NeedNonemptyTemplateHeader = true;
1915 }
1916 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1917 // FIXME: We actually could/should check the template arguments here
1918 // against the corresponding template parameter list.
1919 NeedNonemptyTemplateHeader = false;
1920 }
1921
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001922 // C++ [temp.expl.spec]p16:
1923 // In an explicit specialization declaration for a member of a class
1924 // template or a member template that ap- pears in namespace scope, the
1925 // member template and some of its enclosing class templates may remain
1926 // unspecialized, except that the declaration shall not explicitly
1927 // specialize a class member template if its en- closing class templates
1928 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001929 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001930 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001931 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1932 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001933 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001934 } else
1935 SawNonEmptyTemplateParameterList = true;
1936 }
1937
Douglas Gregor972fe532011-05-10 18:27:06 +00001938 if (NeedEmptyTemplateHeader) {
1939 // If we're on the last of the types, and we need a 'template<>' header
1940 // here, then it's an explicit specialization.
1941 if (TypeIdx == NumTypes - 1)
1942 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001943
1944 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001945 if (ParamLists[ParamIdx]->size() > 0) {
1946 // The header has template parameters when it shouldn't. Complain.
1947 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1948 diag::err_template_param_list_matches_nontemplate)
1949 << T
1950 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1951 ParamLists[ParamIdx]->getRAngleLoc())
1952 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1953 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001954 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001955 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001956
Douglas Gregor972fe532011-05-10 18:27:06 +00001957 // Consume this template header.
1958 ++ParamIdx;
1959 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001960 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001961
1962 if (!IsFriend)
1963 if (DiagnoseMissingExplicitSpecialization(
1964 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001965 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001966
Douglas Gregor972fe532011-05-10 18:27:06 +00001967 continue;
1968 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001969
Douglas Gregor972fe532011-05-10 18:27:06 +00001970 if (NeedNonemptyTemplateHeader) {
1971 // In friend declarations we can have template-ids which don't
1972 // depend on the corresponding template parameter lists. But
1973 // assume that empty parameter lists are supposed to match this
1974 // template-id.
1975 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001976 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001977 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001978 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001979 else
1980 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001981 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001982
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001983 if (ParamIdx < ParamLists.size()) {
1984 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001985 if (ExpectedTemplateParams &&
1986 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1987 ExpectedTemplateParams,
1988 true, TPL_TemplateMatch))
1989 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001990
Douglas Gregor972fe532011-05-10 18:27:06 +00001991 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001992 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001993 TPC_ClassTemplateMember))
1994 Invalid = true;
1995
1996 ++ParamIdx;
1997 continue;
1998 }
1999
2000 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2001 << T
2002 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2003 Invalid = true;
2004 continue;
2005 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00002006 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00002007
Douglas Gregord8d297c2009-07-21 23:53:31 +00002008 // If there were at least as many template-ids as there were template
2009 // parameter lists, then there are no template parameter lists remaining for
2010 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002011 if (ParamIdx >= ParamLists.size()) {
2012 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00002013 // We don't have a template header for the declaration itself, but we
2014 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00002015 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00002016 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2017 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00002018
2019 // Fabricate an empty template parameter list for the invented header.
2020 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00002021 SourceLocation(), None,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00002022 SourceLocation(), nullptr);
Richard Smith4b55a9c2014-04-17 03:29:33 +00002023 }
2024
Craig Topperc3ec1492014-05-26 06:22:03 +00002025 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002026 }
Mike Stump11289f42009-09-09 15:08:12 +00002027
Douglas Gregord8d297c2009-07-21 23:53:31 +00002028 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002029 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002030 bool HasAnyExplicitSpecHeader = false;
2031 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002032 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00002033 if (ParamLists[I]->size() == 0)
2034 HasAnyExplicitSpecHeader = true;
2035 else
2036 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002037 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002038
Douglas Gregor972fe532011-05-10 18:27:06 +00002039 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002040 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2041 : diag::err_template_spec_extra_headers)
2042 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2043 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00002044
2045 // If there was a specialization somewhere, such that 'template<>' is
2046 // not required, and there were any 'template<>' headers, note where the
2047 // specialization occurred.
2048 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2049 Diag(ExplicitSpecLoc,
2050 diag::note_explicit_template_spec_does_not_need_header)
2051 << NestedTypes.back();
2052
2053 // We have a template parameter list with no corresponding scope, which
2054 // means that the resulting template declaration can't be instantiated
2055 // properly (we'll end up with dependent nodes when we shouldn't).
2056 if (!AllExplicitSpecHeaders)
2057 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00002058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregor522d5eb2011-06-06 15:22:55 +00002060 // C++ [temp.expl.spec]p16:
2061 // In an explicit specialization declaration for a member of a class
2062 // template or a member template that ap- pears in namespace scope, the
2063 // member template and some of its enclosing class templates may remain
2064 // unspecialized, except that the declaration shall not explicitly
2065 // specialize a class member template if its en- closing class templates
2066 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002067 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002068 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2069 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002071
Douglas Gregord8d297c2009-07-21 23:53:31 +00002072 // Return the last template parameter list, which corresponds to the
2073 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002074 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002075}
2076
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002077void Sema::NoteAllFoundTemplates(TemplateName Name) {
2078 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2079 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002080 << (isa<FunctionTemplateDecl>(Template)
2081 ? 0
2082 : isa<ClassTemplateDecl>(Template)
2083 ? 1
2084 : isa<VarTemplateDecl>(Template)
2085 ? 2
2086 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2087 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002088 return;
2089 }
2090
2091 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2092 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2093 IEnd = OST->end();
2094 I != IEnd; ++I)
2095 Diag((*I)->getLocation(), diag::note_template_declared_here)
2096 << 0 << (*I)->getDeclName();
2097
2098 return;
2099 }
2100}
2101
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002102static QualType
2103checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2104 const SmallVectorImpl<TemplateArgument> &Converted,
2105 SourceLocation TemplateLoc,
2106 TemplateArgumentListInfo &TemplateArgs) {
2107 ASTContext &Context = SemaRef.getASTContext();
2108 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002109 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002110 // Specializations of __make_integer_seq<S, T, N> are treated like
2111 // S<T, 0, ..., N-1>.
2112
2113 // C++14 [inteseq.intseq]p1:
2114 // T shall be an integer type.
2115 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2116 SemaRef.Diag(TemplateArgs[1].getLocation(),
2117 diag::err_integer_sequence_integral_element_type);
2118 return QualType();
2119 }
2120
2121 // C++14 [inteseq.make]p1:
2122 // If N is negative the program is ill-formed.
2123 TemplateArgument NumArgsArg = Converted[2];
2124 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2125 if (NumArgs < 0) {
2126 SemaRef.Diag(TemplateArgs[2].getLocation(),
2127 diag::err_integer_sequence_negative_length);
2128 return QualType();
2129 }
2130
2131 QualType ArgTy = NumArgsArg.getIntegralType();
2132 TemplateArgumentListInfo SyntheticTemplateArgs;
2133 // The type argument gets reused as the first template argument in the
2134 // synthetic template argument list.
2135 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2136 // Expand N into 0 ... N-1.
2137 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2138 I < NumArgs; ++I) {
2139 TemplateArgument TA(Context, I, ArgTy);
Richard Smith7873de02016-08-11 22:25:46 +00002140 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2141 TA, ArgTy, TemplateArgs[2].getLocation()));
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002142 }
2143 // The first template argument will be reused as the template decl that
2144 // our synthetic template arguments will be applied to.
2145 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2146 TemplateLoc, SyntheticTemplateArgs);
2147 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002148
2149 case BTK__type_pack_element:
2150 // Specializations of
2151 // __type_pack_element<Index, T_1, ..., T_N>
2152 // are treated like T_Index.
2153 assert(Converted.size() == 2 &&
2154 "__type_pack_element should be given an index and a parameter pack");
2155
2156 // If the Index is out of bounds, the program is ill-formed.
2157 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2158 llvm::APSInt Index = IndexArg.getAsIntegral();
2159 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2160 "type std::size_t, and hence be non-negative");
2161 if (Index >= Ts.pack_size()) {
2162 SemaRef.Diag(TemplateArgs[0].getLocation(),
2163 diag::err_type_pack_element_out_of_bounds);
2164 return QualType();
2165 }
2166
2167 // We simply return the type at index `Index`.
2168 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2169 return Nth->getAsType();
2170 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002171 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2172}
2173
Douglas Gregordc572a32009-03-30 22:58:21 +00002174QualType Sema::CheckTemplateIdType(TemplateName Name,
2175 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002176 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002177 DependentTemplateName *DTN
2178 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002179 if (DTN && DTN->isIdentifier())
2180 // When building a template-id where the template-name is dependent,
2181 // assume the template is a type template. Either our assumption is
2182 // correct, or the code is ill-formed and will be diagnosed when the
2183 // dependent name is substituted.
2184 return Context.getDependentTemplateSpecializationType(ETK_None,
2185 DTN->getQualifier(),
2186 DTN->getIdentifier(),
2187 TemplateArgs);
2188
Douglas Gregordc572a32009-03-30 22:58:21 +00002189 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002190 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2191 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002192 // We might have a substituted template template parameter pack. If so,
2193 // build a template specialization type for it.
2194 if (Name.getAsSubstTemplateTemplateParmPack())
2195 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002196
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002197 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2198 << Name;
2199 NoteAllFoundTemplates(Name);
2200 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002201 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002202
Douglas Gregorc40290e2009-03-09 23:48:35 +00002203 // Check that the template argument list is well-formed for this
2204 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002205 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002206 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002207 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002208 return QualType();
2209
Douglas Gregorc40290e2009-03-09 23:48:35 +00002210 QualType CanonType;
2211
Douglas Gregor678d76c2011-07-01 01:22:09 +00002212 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002213 if (TypeAliasTemplateDecl *AliasTemplate =
2214 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002215 // Find the canonical type for this type alias template specialization.
2216 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2217 if (Pattern->isInvalidDecl())
2218 return QualType();
2219
2220 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002221 Converted);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002222
2223 // Only substitute for the innermost template argument list.
2224 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002225 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002226 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2227 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002228 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002229
Richard Smith802c4b72012-08-23 06:16:52 +00002230 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002231 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002232 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002233 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002234
Richard Smith3f1b5d02011-05-05 21:57:07 +00002235 CanonType = SubstType(Pattern->getUnderlyingType(),
2236 TemplateArgLists, AliasTemplate->getLocation(),
2237 AliasTemplate->getDeclName());
2238 if (CanonType.isNull())
2239 return QualType();
2240 } else if (Name.isDependent() ||
2241 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002242 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002243 // This class template specialization is a dependent
2244 // type. Therefore, its canonical type is another class template
2245 // specialization type that contains all of the converted
2246 // arguments in canonical form. This ensures that, e.g., A<T> and
2247 // A<T, T> have identical types when A is declared as:
2248 //
2249 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002250 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002251 CanonType = Context.getTemplateSpecializationType(CanonName,
David Majnemer6fbeee32016-07-07 04:43:07 +00002252 Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002253
Douglas Gregora8e02e72009-07-28 23:00:59 +00002254 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002255 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002256 // In the future, we need to teach getTemplateSpecializationType to only
2257 // build the canonical type and return that to us.
2258 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002259
2260 // This might work out to be a current instantiation, in which
2261 // case the canonical type needs to be the InjectedClassNameType.
2262 //
2263 // TODO: in theory this could be a simple hashtable lookup; most
2264 // changes to CurContext don't change the set of current
2265 // instantiations.
2266 if (isa<ClassTemplateDecl>(Template)) {
2267 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2268 // If we get out to a namespace, we're done.
2269 if (Ctx->isFileContext()) break;
2270
2271 // If this isn't a record, keep looking.
2272 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2273 if (!Record) continue;
2274
2275 // Look for one of the two cases with InjectedClassNameTypes
2276 // and check whether it's the same template.
2277 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2278 !Record->getDescribedClassTemplate())
2279 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280
John McCall2408e322010-04-27 00:57:59 +00002281 // Fetch the injected class name type and check whether its
2282 // injected type is equal to the type we just built.
2283 QualType ICNT = Context.getTypeDeclType(Record);
2284 QualType Injected = cast<InjectedClassNameType>(ICNT)
2285 ->getInjectedSpecializationType();
2286
2287 if (CanonType != Injected->getCanonicalTypeInternal())
2288 continue;
2289
2290 // If so, the canonical type of this TST is the injected
2291 // class name type of the record we just found.
2292 assert(ICNT.isCanonical());
2293 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002294 break;
2295 }
2296 }
Mike Stump11289f42009-09-09 15:08:12 +00002297 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002298 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002299 // Find the class template specialization declaration that
2300 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002301 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002302 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002303 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002304 if (!Decl) {
2305 // This is the first time we have referenced this class template
2306 // specialization. Create the canonical declaration and add it to
2307 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002308 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002309 ClassTemplate->getTemplatedDecl()->getTagKind(),
2310 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002311 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002312 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002313 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002314 Converted, nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002315 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002316 if (ClassTemplate->isOutOfLine())
2317 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002318 }
2319
Chandler Carruth2acfb222013-09-27 22:14:40 +00002320 // Diagnose uses of this specialization.
2321 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2322
Douglas Gregorc40290e2009-03-09 23:48:35 +00002323 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002324 assert(isa<RecordType>(CanonType) &&
2325 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002326 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2327 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2328 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002329 }
Mike Stump11289f42009-09-09 15:08:12 +00002330
Douglas Gregorc40290e2009-03-09 23:48:35 +00002331 // Build the fully-sugared type for this class template
2332 // specialization, which refers back to the class template
2333 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002334 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002335}
2336
John McCallfaf5fb42010-08-26 23:41:50 +00002337TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002338Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002339 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002340 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002341 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002342 SourceLocation RAngleLoc,
2343 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002344 if (SS.isInvalid())
2345 return true;
2346
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002347 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002348
Douglas Gregorc40290e2009-03-09 23:48:35 +00002349 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002350 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002351 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002352
Douglas Gregor5a064722011-02-28 17:23:35 +00002353 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002354 QualType T
2355 = Context.getDependentTemplateSpecializationType(ETK_None,
2356 DTN->getQualifier(),
2357 DTN->getIdentifier(),
2358 TemplateArgs);
2359 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002360 TypeLocBuilder TLB;
2361 DependentTemplateSpecializationTypeLoc SpecTL
2362 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002363 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2364 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002365 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002366 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002367 SpecTL.setLAngleLoc(LAngleLoc);
2368 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002369 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2370 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2371 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2372 }
2373
John McCall6b51f282009-11-23 01:53:49 +00002374 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002375
2376 if (Result.isNull())
2377 return true;
2378
Douglas Gregore7c20652011-03-02 00:47:37 +00002379 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002380 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002381 TemplateSpecializationTypeLoc SpecTL
2382 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002383 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002384 SpecTL.setTemplateNameLoc(TemplateLoc);
2385 SpecTL.setLAngleLoc(LAngleLoc);
2386 SpecTL.setRAngleLoc(RAngleLoc);
2387 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2388 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002389
Abramo Bagnara4244b432012-01-27 08:46:19 +00002390 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2391 // constructor or destructor name (in such a case, the scope specifier
2392 // will be attached to the enclosing Decl or Expr node).
2393 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002394 // Create an elaborated-type-specifier containing the nested-name-specifier.
2395 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2396 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002397 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002398 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2399 }
2400
2401 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002402}
John McCall06f6fe8d2009-09-04 01:14:41 +00002403
Douglas Gregore7c20652011-03-02 00:47:37 +00002404TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002405 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002406 SourceLocation TagLoc,
2407 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002408 SourceLocation TemplateKWLoc,
2409 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002410 SourceLocation TemplateLoc,
2411 SourceLocation LAngleLoc,
2412 ASTTemplateArgsPtr TemplateArgsIn,
2413 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002414 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002415
2416 // Translate the parser's template argument list in our AST format.
2417 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2418 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2419
2420 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002421 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002422 ElaboratedTypeKeyword Keyword
2423 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002424
Douglas Gregore7c20652011-03-02 00:47:37 +00002425 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2426 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2427 DTN->getQualifier(),
2428 DTN->getIdentifier(),
2429 TemplateArgs);
2430
2431 // Build type-source information.
2432 TypeLocBuilder TLB;
2433 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002434 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2435 SpecTL.setElaboratedKeywordLoc(TagLoc);
2436 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002437 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002438 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002439 SpecTL.setLAngleLoc(LAngleLoc);
2440 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002441 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2442 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2443 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2444 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002445
2446 if (TypeAliasTemplateDecl *TAT =
2447 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2448 // C++0x [dcl.type.elab]p2:
2449 // If the identifier resolves to a typedef-name or the simple-template-id
2450 // resolves to an alias template specialization, the
2451 // elaborated-type-specifier is ill-formed.
2452 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2453 Diag(TAT->getLocation(), diag::note_declared_at);
2454 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002455
2456 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2457 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002458 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002459
2460 // Check the tag kind
2461 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002462 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002463
John McCalld8fe9af2009-09-08 17:47:29 +00002464 IdentifierInfo *Id = D->getIdentifier();
2465 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002466
Richard Trieucaa33d32011-06-10 03:11:26 +00002467 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002468 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002469 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002470 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002471 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002472 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002473 }
2474 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002475
Douglas Gregore7c20652011-03-02 00:47:37 +00002476 // Provide source-location information for the template specialization.
2477 TypeLocBuilder TLB;
2478 TemplateSpecializationTypeLoc SpecTL
2479 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002480 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002481 SpecTL.setTemplateNameLoc(TemplateLoc);
2482 SpecTL.setLAngleLoc(LAngleLoc);
2483 SpecTL.setRAngleLoc(RAngleLoc);
2484 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2485 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002486
Douglas Gregore7c20652011-03-02 00:47:37 +00002487 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002488 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002489 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2490 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002491 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002492 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2493 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002494}
2495
Larisse Voufo39a1e502013-08-06 01:03:05 +00002496static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002497 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2498 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002499
2500static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2501 NamedDecl *PrevDecl,
2502 SourceLocation Loc,
2503 bool IsPartialSpecialization);
2504
2505static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002506
Richard Smith300e0c32013-09-24 04:49:23 +00002507static bool isTemplateArgumentTemplateParameter(
2508 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2509 switch (Arg.getKind()) {
2510 case TemplateArgument::Null:
2511 case TemplateArgument::NullPtr:
2512 case TemplateArgument::Integral:
2513 case TemplateArgument::Declaration:
2514 case TemplateArgument::Pack:
2515 case TemplateArgument::TemplateExpansion:
2516 return false;
2517
2518 case TemplateArgument::Type: {
2519 QualType Type = Arg.getAsType();
2520 const TemplateTypeParmType *TPT =
2521 Arg.getAsType()->getAs<TemplateTypeParmType>();
2522 return TPT && !Type.hasQualifiers() &&
2523 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2524 }
2525
2526 case TemplateArgument::Expression: {
2527 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2528 if (!DRE || !DRE->getDecl())
2529 return false;
2530 const NonTypeTemplateParmDecl *NTTP =
2531 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2532 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2533 }
2534
2535 case TemplateArgument::Template:
2536 const TemplateTemplateParmDecl *TTP =
2537 dyn_cast_or_null<TemplateTemplateParmDecl>(
2538 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2539 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2540 }
2541 llvm_unreachable("unexpected kind of template argument");
2542}
2543
2544static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2545 ArrayRef<TemplateArgument> Args) {
2546 if (Params->size() != Args.size())
2547 return false;
2548
2549 unsigned Depth = Params->getDepth();
2550
2551 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2552 TemplateArgument Arg = Args[I];
2553
2554 // If the parameter is a pack expansion, the argument must be a pack
2555 // whose only element is a pack expansion.
2556 if (Params->getParam(I)->isParameterPack()) {
2557 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2558 !Arg.pack_begin()->isPackExpansion())
2559 return false;
2560 Arg = Arg.pack_begin()->getPackExpansionPattern();
2561 }
2562
2563 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2564 return false;
2565 }
2566
2567 return true;
2568}
2569
Richard Smith4b55a9c2014-04-17 03:29:33 +00002570/// Convert the parser's template argument list representation into our form.
2571static TemplateArgumentListInfo
2572makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2573 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2574 TemplateId.RAngleLoc);
2575 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2576 TemplateId.NumArgs);
2577 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2578 return TemplateArgs;
2579}
2580
Larisse Voufo39a1e502013-08-06 01:03:05 +00002581DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002582 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002583 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002584 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002585 // D must be variable template id.
2586 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2587 "Variable template specialization is declared with a template it.");
2588
2589 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002590 TemplateArgumentListInfo TemplateArgs =
2591 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002592 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2593 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2594 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002595
Richard Smithbeef3452014-01-16 23:39:20 +00002596 TemplateName Name = TemplateId->Template.get();
2597
2598 // The template-id must name a variable template.
2599 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002600 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2601 if (!VarTemplate) {
2602 NamedDecl *FnTemplate;
2603 if (auto *OTS = Name.getAsOverloadedTemplate())
2604 FnTemplate = *OTS->begin();
2605 else
2606 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2607 if (FnTemplate)
2608 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2609 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002610 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2611 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002612 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002613
2614 // Check for unexpanded parameter packs in any of the template arguments.
2615 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2616 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2617 UPPC_PartialSpecialization))
2618 return true;
2619
2620 // Check that the template argument list is well-formed for this
2621 // template.
2622 SmallVector<TemplateArgument, 4> Converted;
2623 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2624 false, Converted))
2625 return true;
2626
Larisse Voufo39a1e502013-08-06 01:03:05 +00002627 // Find the variable template (partial) specialization declaration that
2628 // corresponds to these arguments.
2629 if (IsPartialSpecialization) {
2630 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002631 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2632 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002633 return true;
2634
2635 bool InstantiationDependent;
2636 if (!Name.isDependent() &&
2637 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00002638 TemplateArgs.arguments(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00002639 InstantiationDependent)) {
2640 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2641 << VarTemplate->getDeclName();
2642 IsPartialSpecialization = false;
2643 }
Richard Smith300e0c32013-09-24 04:49:23 +00002644
2645 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2646 Converted)) {
2647 // C++ [temp.class.spec]p9b3:
2648 //
2649 // -- The argument list of the specialization shall not be identical
2650 // to the implicit argument list of the primary template.
2651 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2652 << /*variable template*/ 1
2653 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2654 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2655 // FIXME: Recover from this by treating the declaration as a redeclaration
2656 // of the primary template.
2657 return true;
2658 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002659 }
2660
Craig Topperc3ec1492014-05-26 06:22:03 +00002661 void *InsertPos = nullptr;
2662 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002663
2664 if (IsPartialSpecialization)
2665 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002666 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002667 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002668 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002669
Craig Topperc3ec1492014-05-26 06:22:03 +00002670 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002671
2672 // Check whether we can declare a variable template specialization in
2673 // the current scope.
2674 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2675 TemplateNameLoc,
2676 IsPartialSpecialization))
2677 return true;
2678
2679 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2680 // Since the only prior variable template specialization with these
2681 // arguments was referenced but not declared, reuse that
2682 // declaration node as our own, updating its source location and
2683 // the list of outer template parameters to reflect our new declaration.
2684 Specialization = PrevDecl;
2685 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002686 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002687 } else if (IsPartialSpecialization) {
2688 // Create a new class template partial specialization declaration node.
2689 VarTemplatePartialSpecializationDecl *PrevPartial =
2690 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002691 VarTemplatePartialSpecializationDecl *Partial =
2692 VarTemplatePartialSpecializationDecl::Create(
2693 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2694 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
David Majnemer8b622692016-07-03 21:17:51 +00002695 Converted, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002696
2697 if (!PrevPartial)
2698 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2699 Specialization = Partial;
2700
2701 // If we are providing an explicit specialization of a member variable
2702 // template specialization, make a note of that.
2703 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002704 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002705
2706 // Check that all of the template parameters of the variable template
2707 // partial specialization are deducible from the template
2708 // arguments. If not, this variable template partial specialization
2709 // will never be used.
2710 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2711 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2712 TemplateParams->getDepth(), DeducibleParams);
2713
2714 if (!DeducibleParams.all()) {
2715 unsigned NumNonDeducible =
2716 DeducibleParams.size() - DeducibleParams.count();
2717 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002718 << /*variable template*/ 1 << (NumNonDeducible > 1)
2719 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002720 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2721 if (!DeducibleParams[I]) {
2722 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2723 if (Param->getDeclName())
2724 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2725 << Param->getDeclName();
2726 else
2727 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002728 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002729 }
2730 }
2731 }
2732 } else {
2733 // Create a new class template specialization declaration node for
2734 // this explicit specialization or friend declaration.
2735 Specialization = VarTemplateSpecializationDecl::Create(
2736 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
David Majnemer8b622692016-07-03 21:17:51 +00002737 VarTemplate, DI->getType(), DI, SC, Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002738 Specialization->setTemplateArgsInfo(TemplateArgs);
2739
2740 if (!PrevDecl)
2741 VarTemplate->AddSpecialization(Specialization, InsertPos);
2742 }
2743
2744 // C++ [temp.expl.spec]p6:
2745 // If a template, a member template or the member of a class template is
2746 // explicitly specialized then that specialization shall be declared
2747 // before the first use of that specialization that would cause an implicit
2748 // instantiation to take place, in every translation unit in which such a
2749 // use occurs; no diagnostic is required.
2750 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2751 bool Okay = false;
2752 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2753 // Is there any previous explicit specialization declaration?
2754 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2755 Okay = true;
2756 break;
2757 }
2758 }
2759
2760 if (!Okay) {
2761 SourceRange Range(TemplateNameLoc, RAngleLoc);
2762 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2763 << Name << Range;
2764
2765 Diag(PrevDecl->getPointOfInstantiation(),
2766 diag::note_instantiation_required_here)
2767 << (PrevDecl->getTemplateSpecializationKind() !=
2768 TSK_ImplicitInstantiation);
2769 return true;
2770 }
2771 }
2772
2773 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2774 Specialization->setLexicalDeclContext(CurContext);
2775
2776 // Add the specialization into its lexical context, so that it can
2777 // be seen when iterating through the list of declarations in that
2778 // context. However, specializations are not found by name lookup.
2779 CurContext->addDecl(Specialization);
2780
2781 // Note that this is an explicit specialization.
2782 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2783
2784 if (PrevDecl) {
2785 // Check that this isn't a redefinition of this specialization,
2786 // merging with previous declarations.
2787 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2788 ForRedeclaration);
2789 PrevSpec.addDecl(PrevDecl);
2790 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002791 } else if (Specialization->isStaticDataMember() &&
2792 Specialization->isOutOfLine()) {
2793 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002794 }
2795
2796 // Link instantiations of static data members back to the template from
2797 // which they were instantiated.
2798 if (Specialization->isStaticDataMember())
2799 Specialization->setInstantiationOfStaticDataMember(
2800 VarTemplate->getTemplatedDecl(),
2801 Specialization->getSpecializationKind());
2802
2803 return Specialization;
2804}
2805
2806namespace {
2807/// \brief A partial specialization whose template arguments have matched
2808/// a given template-id.
2809struct PartialSpecMatchResult {
2810 VarTemplatePartialSpecializationDecl *Partial;
2811 TemplateArgumentList *Args;
2812};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002813} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002814
2815DeclResult
2816Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2817 SourceLocation TemplateNameLoc,
2818 const TemplateArgumentListInfo &TemplateArgs) {
2819 assert(Template && "A variable template id without template?");
2820
2821 // Check that the template argument list is well-formed for this template.
2822 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002823 if (CheckTemplateArgumentList(
2824 Template, TemplateNameLoc,
2825 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002826 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002827 return true;
2828
2829 // Find the variable template specialization declaration that
2830 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002831 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002832 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002833 Converted, InsertPos)) {
2834 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002835 // If we already have a variable template specialization, return it.
2836 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002837 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002838
2839 // This is the first time we have referenced this variable template
2840 // specialization. Create the canonical declaration and add it to
2841 // the set of specializations, based on the closest partial specialization
2842 // that it represents. That is,
2843 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2844 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00002845 Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002846 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2847 bool AmbiguousPartialSpec = false;
2848 typedef PartialSpecMatchResult MatchResult;
2849 SmallVector<MatchResult, 4> Matched;
2850 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002851 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2852 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002853
2854 // 1. Attempt to find the closest partial specialization that this
2855 // specializes, if any.
2856 // If any of the template arguments is dependent, then this is probably
2857 // a placeholder for an incomplete declarative context; which must be
2858 // complete by instantiation time. Thus, do not search through the partial
2859 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002860 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2861 // Perhaps better after unification of DeduceTemplateArguments() and
2862 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002863 bool InstantiationDependent = false;
2864 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2865 TemplateArgs, InstantiationDependent)) {
2866
2867 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2868 Template->getPartialSpecializations(PartialSpecs);
2869
2870 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2871 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2872 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2873
2874 if (TemplateDeductionResult Result =
2875 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2876 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002877 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002878 FailedCandidates.addCandidate().set(
2879 DeclAccessPair::make(Template, AS_public), Partial,
2880 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002881 (void)Result;
2882 } else {
2883 Matched.push_back(PartialSpecMatchResult());
2884 Matched.back().Partial = Partial;
2885 Matched.back().Args = Info.take();
2886 }
2887 }
2888
Larisse Voufo39a1e502013-08-06 01:03:05 +00002889 if (Matched.size() >= 1) {
2890 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2891 if (Matched.size() == 1) {
2892 // -- If exactly one matching specialization is found, the
2893 // instantiation is generated from that specialization.
2894 // We don't need to do anything for this.
2895 } else {
2896 // -- If more than one matching specialization is found, the
2897 // partial order rules (14.5.4.2) are used to determine
2898 // whether one of the specializations is more specialized
2899 // than the others. If none of the specializations is more
2900 // specialized than all of the other matching
2901 // specializations, then the use of the variable template is
2902 // ambiguous and the program is ill-formed.
2903 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2904 PEnd = Matched.end();
2905 P != PEnd; ++P) {
2906 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2907 PointOfInstantiation) ==
2908 P->Partial)
2909 Best = P;
2910 }
2911
2912 // Determine if the best partial specialization is more specialized than
2913 // the others.
2914 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2915 PEnd = Matched.end();
2916 P != PEnd; ++P) {
2917 if (P != Best && getMoreSpecializedPartialSpecialization(
2918 P->Partial, Best->Partial,
2919 PointOfInstantiation) != Best->Partial) {
2920 AmbiguousPartialSpec = true;
2921 break;
2922 }
2923 }
2924 }
2925
2926 // Instantiate using the best variable template partial specialization.
2927 InstantiationPattern = Best->Partial;
2928 InstantiationArgs = Best->Args;
2929 } else {
2930 // -- If no match is found, the instantiation is generated
2931 // from the primary template.
2932 // InstantiationPattern = Template->getTemplatedDecl();
2933 }
2934 }
2935
Larisse Voufo39a1e502013-08-06 01:03:05 +00002936 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00002937 // Note that we do not instantiate a definition until we see an odr-use
2938 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002939 // FIXME: LateAttrs et al.?
2940 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2941 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2942 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2943 if (!Decl)
2944 return true;
2945
2946 if (AmbiguousPartialSpec) {
2947 // Partial ordering did not produce a clear winner. Complain.
2948 Decl->setInvalidDecl();
2949 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2950 << Decl;
2951
2952 // Print the matching partial specializations.
2953 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2954 PEnd = Matched.end();
2955 P != PEnd; ++P)
2956 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2957 << getTemplateArgumentBindingsText(
2958 P->Partial->getTemplateParameters(), *P->Args);
2959 return true;
2960 }
2961
2962 if (VarTemplatePartialSpecializationDecl *D =
2963 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2964 Decl->setInstantiationOf(D, InstantiationArgs);
2965
Richard Smith6739a102016-05-05 00:56:12 +00002966 checkSpecializationVisibility(TemplateNameLoc, Decl);
2967
Larisse Voufo39a1e502013-08-06 01:03:05 +00002968 assert(Decl && "No variable template specialization?");
2969 return Decl;
2970}
2971
2972ExprResult
2973Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2974 const DeclarationNameInfo &NameInfo,
2975 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2976 const TemplateArgumentListInfo *TemplateArgs) {
2977
2978 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2979 *TemplateArgs);
2980 if (Decl.isInvalid())
2981 return ExprError();
2982
2983 VarDecl *Var = cast<VarDecl>(Decl.get());
2984 if (!Var->getTemplateSpecializationKind())
2985 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2986 NameInfo.getLoc());
2987
2988 // Build an ordinary singleton decl ref.
2989 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002990 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002991}
2992
John McCalldadc5752010-08-24 06:29:42 +00002993ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002994 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002995 LookupResult &R,
2996 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002997 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002998 // FIXME: Can we do any checking at this point? I guess we could check the
2999 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00003000 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00003001 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00003002 // foo<int> could identify a single function unambiguously
3003 // This approach does NOT work, since f<int>(1);
3004 // gets resolved prior to resorting to overload resolution
3005 // i.e., template<class T> void f(double);
3006 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00003007
3008 // These should be filtered out by our callers.
3009 assert(!R.empty() && "empty lookup results when building templateid");
3010 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3011
Larisse Voufo39a1e502013-08-06 01:03:05 +00003012 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00003013 bool InstantiationDependent;
3014 if (R.getAsSingle<VarTemplateDecl>() &&
3015 !TemplateSpecializationType::anyDependentTemplateArguments(
3016 *TemplateArgs, InstantiationDependent)) {
3017 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3018 R.getAsSingle<VarTemplateDecl>(),
3019 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003020 }
3021
John McCall58cc69d2010-01-27 01:50:18 +00003022 // We don't want lookup warnings at this point.
3023 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024
John McCalle66edc12009-11-24 19:00:30 +00003025 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00003026 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00003027 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003028 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003029 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003031 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00003032
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003033 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00003034}
3035
John McCalle66edc12009-11-24 19:00:30 +00003036// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00003037ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003038Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003039 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003040 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003041 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003042
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00003043 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00003044 DeclContext *DC;
3045 if (!(DC = computeDeclContext(SS, false)) ||
3046 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00003047 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00003048 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003049
Douglas Gregor786123d2010-05-21 23:18:07 +00003050 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003051 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00003052 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00003053 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00003054
John McCalle66edc12009-11-24 19:00:30 +00003055 if (R.isAmbiguous())
3056 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057
John McCalle66edc12009-11-24 19:00:30 +00003058 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003059 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3060 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003061 return ExprError();
3062 }
3063
3064 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003065 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003066 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003067 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003068 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3069 return ExprError();
3070 }
3071
Abramo Bagnara7945c982012-01-27 09:46:47 +00003072 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003073}
3074
Douglas Gregorb67535d2009-03-31 00:43:58 +00003075/// \brief Form a dependent template name.
3076///
3077/// This action forms a dependent template name given the template
3078/// name and its (presumably dependent) scope specifier. For
3079/// example, given "MetaFun::template apply", the scope specifier \p
3080/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3081/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003083 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003084 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003085 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003086 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003087 bool EnteringContext,
3088 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003089 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3090 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003091 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003092 diag::warn_cxx98_compat_template_outside_of_template :
3093 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094 << FixItHint::CreateRemoval(TemplateKWLoc);
3095
Craig Topperc3ec1492014-05-26 06:22:03 +00003096 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003097 if (SS.isSet())
3098 LookupCtx = computeDeclContext(SS, EnteringContext);
3099 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003100 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003101 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003102 // C++0x [temp.names]p5:
3103 // If a name prefixed by the keyword template is not the name of
3104 // a template, the program is ill-formed. [Note: the keyword
3105 // template may not be applied to non-template members of class
3106 // templates. -end note ] [ Note: as is the case with the
3107 // typename prefix, the template prefix is allowed in cases
3108 // where it is not strictly necessary; i.e., when the
3109 // nested-name-specifier or the expression on the left of the ->
3110 // or . is not dependent on a template-parameter, or the use
3111 // does not appear in the scope of a template. -end note]
3112 //
3113 // Note: C++03 was more strict here, because it banned the use of
3114 // the "template" keyword prior to a template-name that was not a
3115 // dependent name. C++ DR468 relaxed this requirement (the
3116 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003117 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003118 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003119 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003120 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003121 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003122 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3123 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003124 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3125 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003126 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003127 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003128 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003129 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003130 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003131 << Name.getSourceRange()
3132 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003133 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003134 } else {
3135 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003136 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003137 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003138 }
3139
Aaron Ballman4a979672014-01-03 13:56:08 +00003140 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141
Douglas Gregor3cf81312009-11-03 23:16:33 +00003142 switch (Name.getKind()) {
3143 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003144 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003145 Name.Identifier));
3146 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003147
Douglas Gregor71395fa2009-11-04 00:56:37 +00003148 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003149 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003150 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003151 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003152
3153 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003154 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003155
Douglas Gregor3cf81312009-11-03 23:16:33 +00003156 default:
3157 break;
3158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003160 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003161 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003162 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003163 << Name.getSourceRange()
3164 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003165 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003166}
3167
Mike Stump11289f42009-09-09 15:08:12 +00003168bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003169 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003170 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003171 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003172 QualType ArgType;
3173 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003174
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003175 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003176 switch(Arg.getKind()) {
3177 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003178 // C++ [temp.arg.type]p1:
3179 // A template-argument for a template-parameter which is a
3180 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003181 ArgType = Arg.getAsType();
3182 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003183 break;
3184 case TemplateArgument::Template: {
3185 // We have a template type parameter but the template argument
3186 // is a template without any arguments.
3187 SourceRange SR = AL.getSourceRange();
3188 TemplateName Name = Arg.getAsTemplate();
3189 Diag(SR.getBegin(), diag::err_template_missing_args)
3190 << Name << SR;
3191 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3192 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003193
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003194 return true;
3195 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003196 case TemplateArgument::Expression: {
3197 // We have a template type parameter but the template argument is an
3198 // expression; see if maybe it is missing the "typename" keyword.
3199 CXXScopeSpec SS;
3200 DeclarationNameInfo NameInfo;
3201
3202 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3203 SS.Adopt(ArgExpr->getQualifierLoc());
3204 NameInfo = ArgExpr->getNameInfo();
3205 } else if (DependentScopeDeclRefExpr *ArgExpr =
3206 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3207 SS.Adopt(ArgExpr->getQualifierLoc());
3208 NameInfo = ArgExpr->getNameInfo();
3209 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3210 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003211 if (ArgExpr->isImplicitAccess()) {
3212 SS.Adopt(ArgExpr->getQualifierLoc());
3213 NameInfo = ArgExpr->getMemberNameInfo();
3214 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003215 }
3216
Reid Kleckner377c1592014-06-10 23:29:48 +00003217 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003218 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3219 LookupParsedName(Result, CurScope, &SS);
3220
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003221 if (Result.getAsSingle<TypeDecl>() ||
3222 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003223 LookupResult::NotFoundInCurrentInstantiation) {
3224 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003225 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003226 Diag(Loc, getLangOpts().MSVCCompat
3227 ? diag::ext_ms_template_type_arg_missing_typename
3228 : diag::err_template_arg_must_be_type_suggest)
3229 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003230 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003231
3232 // Recover by synthesizing a type using the location information that we
3233 // already have.
3234 ArgType =
3235 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3236 TypeLocBuilder TLB;
3237 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3238 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3239 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3240 TL.setNameLoc(NameInfo.getLoc());
3241 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3242
3243 // Overwrite our input TemplateArgumentLoc so that we can recover
3244 // properly.
3245 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3246 TemplateArgumentLocInfo(TSI));
3247
3248 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003249 }
3250 }
3251 // fallthrough
3252 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003253 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003254 // We have a template type parameter but the template argument
3255 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003256 SourceRange SR = AL.getSourceRange();
3257 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003258 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003259
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003260 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003261 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003262 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003263
Reid Kleckner377c1592014-06-10 23:29:48 +00003264 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003265 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003266
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003267 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003268 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003269
3270 // Objective-C ARC:
3271 // If an explicitly-specified template argument type is a lifetime type
3272 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003273 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003274 ArgType->isObjCLifetimeType() &&
3275 !ArgType.getObjCLifetime()) {
3276 Qualifiers Qs;
3277 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3278 ArgType = Context.getQualifiedType(ArgType, Qs);
3279 }
3280
3281 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003282 return false;
3283}
3284
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003285/// \brief Substitute template arguments into the default template argument for
3286/// the given template type parameter.
3287///
3288/// \param SemaRef the semantic analysis object for which we are performing
3289/// the substitution.
3290///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003292/// for.
3293///
3294/// \param TemplateLoc the location of the template name that started the
3295/// template-id we are checking.
3296///
3297/// \param RAngleLoc the location of the right angle bracket ('>') that
3298/// terminates the template-id.
3299///
3300/// \param Param the template template parameter whose default we are
3301/// substituting into.
3302///
3303/// \param Converted the list of template arguments provided for template
3304/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003305/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003306static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003307SubstDefaultTemplateArgument(Sema &SemaRef,
3308 TemplateDecl *Template,
3309 SourceLocation TemplateLoc,
3310 SourceLocation RAngleLoc,
3311 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003312 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003313 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003314
3315 // If the argument type is dependent, instantiate it now based
3316 // on the previously-computed template arguments.
3317 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003318 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003319 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003320 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003321 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003322 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323
David Majnemer8b622692016-07-03 21:17:51 +00003324 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003325
3326 // Only substitute for the innermost template argument list.
3327 MultiLevelTemplateArgumentList TemplateArgLists;
3328 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3329 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3330 TemplateArgLists.addOuterTemplateArguments(None);
3331
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003332 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003333 ArgType =
3334 SemaRef.SubstType(ArgType, TemplateArgLists,
3335 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003336 }
3337
3338 return ArgType;
3339}
3340
3341/// \brief Substitute template arguments into the default template argument for
3342/// the given non-type template parameter.
3343///
3344/// \param SemaRef the semantic analysis object for which we are performing
3345/// the substitution.
3346///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003348/// for.
3349///
3350/// \param TemplateLoc the location of the template name that started the
3351/// template-id we are checking.
3352///
3353/// \param RAngleLoc the location of the right angle bracket ('>') that
3354/// terminates the template-id.
3355///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003356/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003357/// substituting into.
3358///
3359/// \param Converted the list of template arguments provided for template
3360/// parameters that precede \p Param in the template parameter list.
3361///
3362/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003363static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003364SubstDefaultTemplateArgument(Sema &SemaRef,
3365 TemplateDecl *Template,
3366 SourceLocation TemplateLoc,
3367 SourceLocation RAngleLoc,
3368 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003369 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003370 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003371 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003372 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003373 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003374 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003375
David Majnemer8b622692016-07-03 21:17:51 +00003376 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003377
3378 // Only substitute for the innermost template argument list.
3379 MultiLevelTemplateArgumentList TemplateArgLists;
3380 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3381 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3382 TemplateArgLists.addOuterTemplateArguments(None);
3383
Faisal Vali48401eb2015-11-19 19:20:17 +00003384 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3385 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003386 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003387}
3388
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003389/// \brief Substitute template arguments into the default template argument for
3390/// the given template template parameter.
3391///
3392/// \param SemaRef the semantic analysis object for which we are performing
3393/// the substitution.
3394///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003396/// for.
3397///
3398/// \param TemplateLoc the location of the template name that started the
3399/// template-id we are checking.
3400///
3401/// \param RAngleLoc the location of the right angle bracket ('>') that
3402/// terminates the template-id.
3403///
3404/// \param Param the template template parameter whose default we are
3405/// substituting into.
3406///
3407/// \param Converted the list of template arguments provided for template
3408/// parameters that precede \p Param in the template parameter list.
3409///
Douglas Gregordf846d12011-03-02 18:46:51 +00003410/// \param QualifierLoc Will be set to the nested-name-specifier (with
3411/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003412///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003413/// \returns the substituted template argument, or NULL if an error occurred.
3414static TemplateName
3415SubstDefaultTemplateArgument(Sema &SemaRef,
3416 TemplateDecl *Template,
3417 SourceLocation TemplateLoc,
3418 SourceLocation RAngleLoc,
3419 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003420 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003421 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003422 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003423 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003424 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003425 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
David Majnemer8b622692016-07-03 21:17:51 +00003427 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
David Majnemer89189202013-08-28 23:48:32 +00003428
3429 // Only substitute for the innermost template argument list.
3430 MultiLevelTemplateArgumentList TemplateArgLists;
3431 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3432 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3433 TemplateArgLists.addOuterTemplateArguments(None);
3434
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003435 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003436 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003437 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003438 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003439 QualifierLoc =
3440 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003441 if (!QualifierLoc)
3442 return TemplateName();
3443 }
David Majnemer89189202013-08-28 23:48:32 +00003444
3445 return SemaRef.SubstTemplateName(
3446 QualifierLoc,
3447 Param->getDefaultArgument().getArgument().getAsTemplate(),
3448 Param->getDefaultArgument().getTemplateNameLoc(),
3449 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003450}
3451
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003452/// \brief If the given template parameter has a default template
3453/// argument, substitute into that default template argument and
3454/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003456Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3457 SourceLocation TemplateLoc,
3458 SourceLocation RAngleLoc,
3459 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003460 SmallVectorImpl<TemplateArgument>
3461 &Converted,
3462 bool &HasDefaultArg) {
3463 HasDefaultArg = false;
3464
3465 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003466 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003467 return TemplateArgumentLoc();
3468
Richard Smithc87b9382013-07-04 01:01:24 +00003469 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003470 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003471 TemplateLoc,
3472 RAngleLoc,
3473 TypeParm,
3474 Converted);
3475 if (DI)
3476 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3477
3478 return TemplateArgumentLoc();
3479 }
3480
3481 if (NonTypeTemplateParmDecl *NonTypeParm
3482 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003483 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003484 return TemplateArgumentLoc();
3485
Richard Smithc87b9382013-07-04 01:01:24 +00003486 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003487 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003488 TemplateLoc,
3489 RAngleLoc,
3490 NonTypeParm,
3491 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003492 if (Arg.isInvalid())
3493 return TemplateArgumentLoc();
3494
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003495 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003496 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3497 }
3498
3499 TemplateTemplateParmDecl *TempTempParm
3500 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003501 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003502 return TemplateArgumentLoc();
3503
Richard Smithc87b9382013-07-04 01:01:24 +00003504 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003505 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003506 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003508 RAngleLoc,
3509 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003510 Converted,
3511 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003512 if (TName.isNull())
3513 return TemplateArgumentLoc();
3514
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003516 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003517 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3518}
3519
Douglas Gregorda0fb532009-11-11 19:31:23 +00003520/// \brief Check that the given template argument corresponds to the given
3521/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003522///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003524/// checked.
3525///
Richard Trieu15b66532015-01-24 02:48:32 +00003526/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003527///
3528/// \param Template The template in which the template argument resides.
3529///
3530/// \param TemplateLoc The location of the template name for the template
3531/// whose argument list we're matching.
3532///
3533/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3534/// the template argument list.
3535///
3536/// \param ArgumentPackIndex The index into the argument pack where this
3537/// argument will be placed. Only valid if the parameter is a parameter pack.
3538///
3539/// \param Converted The checked, converted argument will be added to the
3540/// end of this small vector.
3541///
3542/// \param CTAK Describes how we arrived at this particular template argument:
3543/// explicitly written, deduced, etc.
3544///
3545/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003546bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003547 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003548 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003549 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003550 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003551 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003552 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003553 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003554 // Check template type parameters.
3555 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003556 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557
Douglas Gregoreebed722009-11-11 19:41:09 +00003558 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003561 // with the template arguments we've seen thus far. But if the
3562 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003563 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003564 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3565 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Peter Collingbourne01687632010-12-10 17:08:53 +00003567 if (NTTPType->isDependentType() &&
3568 !isa<TemplateTemplateParmDecl>(Template) &&
3569 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003570 // Do substitution on the type of the non-type template parameter.
3571 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003572 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003573 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003574 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003575 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003576
3577 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
David Majnemer8b622692016-07-03 21:17:51 +00003578 Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003579 NTTPType = SubstType(NTTPType,
3580 MultiLevelTemplateArgumentList(TemplateArgs),
3581 NTTP->getLocation(),
3582 NTTP->getDeclName());
3583 // If that worked, check the non-type template parameter type
3584 // for validity.
3585 if (!NTTPType.isNull())
3586 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3587 NTTP->getLocation());
3588 if (NTTPType.isNull())
3589 return true;
3590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591
Douglas Gregorda0fb532009-11-11 19:31:23 +00003592 switch (Arg.getArgument().getKind()) {
3593 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003594 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595
Douglas Gregorda0fb532009-11-11 19:31:23 +00003596 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003597 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003598 ExprResult Res =
3599 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3600 Result, CTAK);
3601 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003602 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Richard Trieu15b66532015-01-24 02:48:32 +00003604 // If the resulting expression is new, then use it in place of the
3605 // old expression in the template argument.
3606 if (Res.get() != Arg.getArgument().getAsExpr()) {
3607 TemplateArgument TA(Res.get());
3608 Arg = TemplateArgumentLoc(TA, Res.get());
3609 }
3610
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003611 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003612 break;
3613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614
Douglas Gregorda0fb532009-11-11 19:31:23 +00003615 case TemplateArgument::Declaration:
3616 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003617 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003618 // We've already checked this template argument, so just copy
3619 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003620 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
Douglas Gregorda0fb532009-11-11 19:31:23 +00003623 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003624 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003625 // We were given a template template argument. It may not be ill-formed;
3626 // see below.
3627 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003628 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3629 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003630 // We have a template argument such as \c T::template X, which we
3631 // parsed as a template template argument. However, since we now
3632 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003633 // template name into an expression.
3634
3635 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3636 Arg.getTemplateNameLoc());
3637
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003638 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003639 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003640 // FIXME: the template-template arg was a DependentTemplateName,
3641 // so it was provided with a template keyword. However, its source
3642 // location is not stored in the template argument structure.
3643 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003644 ExprResult E = DependentScopeDeclRefExpr::Create(
3645 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3646 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003648 // If we parsed the template argument as a pack expansion, create a
3649 // pack expansion expression.
3650 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003651 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003652 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003653 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Douglas Gregorda0fb532009-11-11 19:31:23 +00003656 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003657 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003658 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003659 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003661 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003662 break;
3663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Douglas Gregorda0fb532009-11-11 19:31:23 +00003665 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003666 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003667 // therefore cannot be a non-type template argument.
3668 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3669 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670
Douglas Gregorda0fb532009-11-11 19:31:23 +00003671 Diag(Param->getLocation(), diag::note_template_param_here);
3672 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
Douglas Gregorda0fb532009-11-11 19:31:23 +00003674 case TemplateArgument::Type: {
3675 // We have a non-type template parameter but the template
3676 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677
Douglas Gregorda0fb532009-11-11 19:31:23 +00003678 // C++ [temp.arg]p2:
3679 // In a template-argument, an ambiguity between a type-id and
3680 // an expression is resolved to a type-id, regardless of the
3681 // form of the corresponding template-parameter.
3682 //
3683 // We warn specifically about this case, since it can be rather
3684 // confusing for users.
3685 QualType T = Arg.getArgument().getAsType();
3686 SourceRange SR = Arg.getSourceRange();
3687 if (T->isFunctionType())
3688 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3689 else
3690 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3691 Diag(Param->getLocation(), diag::note_template_param_here);
3692 return true;
3693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694
Douglas Gregorda0fb532009-11-11 19:31:23 +00003695 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003696 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003697 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698
Douglas Gregorda0fb532009-11-11 19:31:23 +00003699 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700 }
3701
3702
Douglas Gregorda0fb532009-11-11 19:31:23 +00003703 // Check template template parameters.
3704 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705
Douglas Gregorda0fb532009-11-11 19:31:23 +00003706 // Substitute into the template parameter list of the template
3707 // template parameter, since previously-supplied template arguments
3708 // may appear within the template template parameter.
3709 {
3710 // Set up a template instantiation context.
3711 LocalInstantiationScope Scope(*this);
3712 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003713 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003714 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003715 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003716 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717
David Majnemer8b622692016-07-03 21:17:51 +00003718 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003719 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003721 MultiLevelTemplateArgumentList(TemplateArgs)));
3722 if (!TempParm)
3723 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725
Douglas Gregorda0fb532009-11-11 19:31:23 +00003726 switch (Arg.getArgument().getKind()) {
3727 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003728 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Douglas Gregorda0fb532009-11-11 19:31:23 +00003730 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003731 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003732 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003733 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003734
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003735 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Douglas Gregorda0fb532009-11-11 19:31:23 +00003738 case TemplateArgument::Expression:
3739 case TemplateArgument::Type:
3740 // We have a template template parameter but the template
3741 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003742 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003743 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003744 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Douglas Gregorda0fb532009-11-11 19:31:23 +00003746 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003747 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003748 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003749 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003750 case TemplateArgument::NullPtr:
3751 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
Douglas Gregorda0fb532009-11-11 19:31:23 +00003753 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003754 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756
Douglas Gregorda0fb532009-11-11 19:31:23 +00003757 return false;
3758}
3759
Douglas Gregor8e072612012-02-03 07:34:46 +00003760/// \brief Diagnose an arity mismatch in the
3761static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3762 SourceLocation TemplateLoc,
3763 TemplateArgumentListInfo &TemplateArgs) {
3764 TemplateParameterList *Params = Template->getTemplateParameters();
3765 unsigned NumParams = Params->size();
3766 unsigned NumArgs = TemplateArgs.size();
3767
3768 SourceRange Range;
3769 if (NumArgs > NumParams)
3770 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3771 TemplateArgs.getRAngleLoc());
3772 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3773 << (NumArgs > NumParams)
3774 << (isa<ClassTemplateDecl>(Template)? 0 :
3775 isa<FunctionTemplateDecl>(Template)? 1 :
3776 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3777 << Template << Range;
3778 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3779 << Params->getSourceRange();
3780 return true;
3781}
3782
Richard Smith1fde8ec2012-09-07 02:06:42 +00003783/// \brief Check whether the template parameter is a pack expansion, and if so,
3784/// determine the number of parameters produced by that expansion. For instance:
3785///
3786/// \code
3787/// template<typename ...Ts> struct A {
3788/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3789/// };
3790/// \endcode
3791///
3792/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3793/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003794static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003795 if (NonTypeTemplateParmDecl *NTTP
3796 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3797 if (NTTP->isExpandedParameterPack())
3798 return NTTP->getNumExpansionTypes();
3799 }
3800
3801 if (TemplateTemplateParmDecl *TTP
3802 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3803 if (TTP->isExpandedParameterPack())
3804 return TTP->getNumExpansionTemplateParameters();
3805 }
3806
David Blaikie7a30dc52013-02-21 01:47:18 +00003807 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003808}
3809
Richard Smith35c1df52015-06-17 20:16:32 +00003810/// Diagnose a missing template argument.
3811template<typename TemplateParmDecl>
3812static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3813 TemplateDecl *TD,
3814 const TemplateParmDecl *D,
3815 TemplateArgumentListInfo &Args) {
3816 // Dig out the most recent declaration of the template parameter; there may be
3817 // declarations of the template that are more recent than TD.
3818 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3819 ->getTemplateParameters()
3820 ->getParam(D->getIndex()));
3821
3822 // If there's a default argument that's not visible, diagnose that we're
3823 // missing a module import.
3824 llvm::SmallVector<Module*, 8> Modules;
3825 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3826 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3827 D->getDefaultArgumentLoc(), Modules,
3828 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003829 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003830 return true;
3831 }
3832
3833 // FIXME: If there's a more recent default argument that *is* visible,
3834 // diagnose that it was declared too late.
3835
3836 return diagnoseArityMismatch(S, TD, Loc, Args);
3837}
3838
Douglas Gregord32e0282009-02-09 23:23:08 +00003839/// \brief Check that the given template argument list is well-formed
3840/// for specializing the given template.
3841bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3842 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003843 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003844 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003845 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003846 // Make a copy of the template arguments for processing. Only make the
3847 // changes at the end when successful in matching the arguments to the
3848 // template.
3849 TemplateArgumentListInfo NewArgs = TemplateArgs;
3850
Douglas Gregord32e0282009-02-09 23:23:08 +00003851 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003852
Richard Trieu15b66532015-01-24 02:48:32 +00003853 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003854
Mike Stump11289f42009-09-09 15:08:12 +00003855 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003856 // [...] The type and form of each template-argument specified in
3857 // a template-id shall match the type and form specified for the
3858 // corresponding parameter declared by the template in its
3859 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003860 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003861 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003862 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003863 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003864 for (TemplateParameterList::iterator Param = Params->begin(),
3865 ParamEnd = Params->end();
3866 Param != ParamEnd; /* increment in loop */) {
3867 // If we have an expanded parameter pack, make sure we don't have too
3868 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003869 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003870 if (*Expansions == ArgumentPack.size()) {
3871 // We're done with this parameter pack. Pack up its arguments and add
3872 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003873 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003874 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003875 ArgumentPack.clear();
3876
Richard Smith1fde8ec2012-09-07 02:06:42 +00003877 // This argument is assigned to the next parameter.
3878 ++Param;
3879 continue;
3880 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3881 // Not enough arguments for this parameter pack.
3882 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3883 << false
3884 << (isa<ClassTemplateDecl>(Template)? 0 :
3885 isa<FunctionTemplateDecl>(Template)? 1 :
3886 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3887 << Template;
3888 Diag(Template->getLocation(), diag::note_template_decl_here)
3889 << Params->getSourceRange();
3890 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003891 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
Richard Smith1fde8ec2012-09-07 02:06:42 +00003894 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003895 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003896 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003898 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003899 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900
Richard Smith96d71c32014-11-12 23:38:38 +00003901 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003902 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003903 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3904 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003905 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003906 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003907 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003908 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003909 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003910 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003911 Diag((*Param)->getLocation(), diag::note_template_param_here);
3912 return true;
3913 }
3914
Richard Smith1fde8ec2012-09-07 02:06:42 +00003915 // We're now done with this argument.
3916 ++ArgIdx;
3917
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003918 if ((*Param)->isTemplateParameterPack()) {
3919 // The template parameter was a template parameter pack, so take the
3920 // deduced argument and place it on the argument pack. Note that we
3921 // stay on the same template parameter so that we can deduce more
3922 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003923 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003924 } else {
3925 // Move to the next template parameter.
3926 ++Param;
3927 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003928
Richard Smith96d71c32014-11-12 23:38:38 +00003929 // If we just saw a pack expansion into a non-pack, then directly convert
3930 // the remaining arguments, because we don't know what parameters they'll
3931 // match up with.
3932 if (PackExpansionIntoNonPack) {
3933 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003934 // If we were part way through filling in an expanded parameter pack,
3935 // fall back to just producing individual arguments.
3936 Converted.insert(Converted.end(),
3937 ArgumentPack.begin(), ArgumentPack.end());
3938 ArgumentPack.clear();
3939 }
3940
3941 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003942 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003943 ++ArgIdx;
3944 }
3945
Richard Smith1fde8ec2012-09-07 02:06:42 +00003946 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003947 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003948
Douglas Gregor84d49a22009-11-11 21:54:23 +00003949 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951
Douglas Gregor2f157c92011-06-03 02:59:40 +00003952 // If we're checking a partial template argument list, we're done.
3953 if (PartialTemplateArgs) {
3954 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003955 Converted.push_back(
3956 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3957
Richard Smith1fde8ec2012-09-07 02:06:42 +00003958 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003959 }
3960
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003962 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003963 if ((*Param)->isTemplateParameterPack()) {
3964 assert(!getExpandedPackSize(*Param) &&
3965 "Should have dealt with this already");
3966
3967 // A non-expanded parameter pack before the end of the parameter list
3968 // only occurs for an ill-formed template parameter list, unless we've
3969 // got a partial argument list for a function template, so just bail out.
3970 if (Param + 1 != ParamEnd)
3971 return true;
3972
Benjamin Kramercce63472015-08-05 09:40:22 +00003973 Converted.push_back(
3974 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003975 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003976
3977 ++Param;
3978 continue;
3979 }
3980
Douglas Gregor8e072612012-02-03 07:34:46 +00003981 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003982 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983
Douglas Gregor84d49a22009-11-11 21:54:23 +00003984 // Retrieve the default template argument from the template
3985 // parameter. For each kind of template parameter, we substitute the
3986 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003987 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003988 // the default argument.
3989 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003990 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003991 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3992 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003993
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003994 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003995 Template,
3996 TemplateLoc,
3997 RAngleLoc,
3998 TTP,
3999 Converted);
4000 if (!ArgType)
4001 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregor84d49a22009-11-11 21:54:23 +00004003 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4004 ArgType);
4005 } else if (NonTypeTemplateParmDecl *NTTP
4006 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00004007 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00004008 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4009 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004010
John McCalldadc5752010-08-24 06:29:42 +00004011 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004012 TemplateLoc,
4013 RAngleLoc,
4014 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004015 Converted);
4016 if (E.isInvalid())
4017 return true;
4018
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004019 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00004020 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4021 } else {
4022 TemplateTemplateParmDecl *TempParm
4023 = cast<TemplateTemplateParmDecl>(*Param);
4024
Richard Smith95d83952015-06-10 20:36:34 +00004025 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00004026 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4027 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004028
Douglas Gregordf846d12011-03-02 18:46:51 +00004029 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00004030 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031 TemplateLoc,
4032 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00004033 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00004034 Converted,
4035 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00004036 if (Name.isNull())
4037 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004038
Douglas Gregor9d802122011-03-02 17:09:35 +00004039 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4040 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00004041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
Douglas Gregor84d49a22009-11-11 21:54:23 +00004043 // Introduce an instantiation record that describes where we are using
4044 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00004045 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4046 SourceRange(TemplateLoc, RAngleLoc));
4047 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004048 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049
Douglas Gregor84d49a22009-11-11 21:54:23 +00004050 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00004051 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00004052 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00004053 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054
Richard Trieu15b66532015-01-24 02:48:32 +00004055 // Core issue 150 (assumed resolution): if this is a template template
4056 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004057 // template definition.
4058 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004059 NewArgs.addArgument(Arg);
4060
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004061 // Move to the next template parameter and argument.
4062 ++Param;
4063 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Richard Smith07f79912014-06-06 16:00:50 +00004066 // If we're performing a partial argument substitution, allow any trailing
4067 // pack expansions; they might be empty. This can happen even if
4068 // PartialTemplateArgs is false (the list of arguments is complete but
4069 // still dependent).
4070 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4071 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004072 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4073 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004074 }
4075
Douglas Gregor8e072612012-02-03 07:34:46 +00004076 // If we have any leftover arguments, then there were too many arguments.
4077 // Complain and fail.
4078 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004079 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4080
4081 // No problems found with the new argument list, propagate changes back
4082 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004083 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084
Richard Smith1fde8ec2012-09-07 02:06:42 +00004085 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004086}
4087
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004088namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004089 class UnnamedLocalNoLinkageFinder
4090 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004091 {
4092 Sema &S;
4093 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004094
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004095 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004097 public:
4098 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4099
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100 bool Visit(QualType T) {
4101 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004104#define TYPE(Class, Parent) \
4105 bool Visit##Class##Type(const Class##Type *);
4106#define ABSTRACT_TYPE(Class, Parent) \
4107 bool Visit##Class##Type(const Class##Type *) { return false; }
4108#define NON_CANONICAL_TYPE(Class, Parent) \
4109 bool Visit##Class##Type(const Class##Type *) { return false; }
4110#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004112 bool VisitTagDecl(const TagDecl *Tag);
4113 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4114 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004115} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004116
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004118 return false;
4119}
4120
4121bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4122 return Visit(T->getElementType());
4123}
4124
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004125bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004126 return Visit(T->getPointeeType());
4127}
4128
4129bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004130 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004131 return Visit(T->getPointeeType());
4132}
4133
4134bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004136 return Visit(T->getPointeeType());
4137}
4138
4139bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004140 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004141 return Visit(T->getPointeeType());
4142}
4143
4144bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004146 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4147}
4148
4149bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004151 return Visit(T->getElementType());
4152}
4153
4154bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004156 return Visit(T->getElementType());
4157}
4158
4159bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004161 return Visit(T->getElementType());
4162}
4163
4164bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004166 return Visit(T->getElementType());
4167}
4168
4169bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004171 return Visit(T->getElementType());
4172}
4173
4174bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4175 return Visit(T->getElementType());
4176}
4177
4178bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4179 return Visit(T->getElementType());
4180}
4181
4182bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4183 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004184 for (const auto &A : T->param_types()) {
4185 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004186 return true;
4187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
Alp Toker314cc812014-01-25 16:55:45 +00004189 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004190}
4191
4192bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4193 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004194 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004195}
4196
4197bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4198 const UnresolvedUsingType*) {
4199 return false;
4200}
4201
4202bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4203 return false;
4204}
4205
4206bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4207 return Visit(T->getUnderlyingType());
4208}
4209
4210bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4211 return false;
4212}
4213
Alexis Hunte852b102011-05-24 22:41:36 +00004214bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4215 const UnaryTransformType*) {
4216 return false;
4217}
4218
Richard Smith30482bc2011-02-20 03:19:35 +00004219bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4220 return Visit(T->getDeducedType());
4221}
4222
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004223bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4224 return VisitTagDecl(T->getDecl());
4225}
4226
4227bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4228 return VisitTagDecl(T->getDecl());
4229}
4230
4231bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4232 const TemplateTypeParmType*) {
4233 return false;
4234}
4235
Douglas Gregorada4b792011-01-14 02:55:32 +00004236bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4237 const SubstTemplateTypeParmPackType *) {
4238 return false;
4239}
4240
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004241bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4242 const TemplateSpecializationType*) {
4243 return false;
4244}
4245
4246bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4247 const InjectedClassNameType* T) {
4248 return VisitTagDecl(T->getDecl());
4249}
4250
4251bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4252 const DependentNameType* T) {
4253 return VisitNestedNameSpecifier(T->getQualifier());
4254}
4255
4256bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4257 const DependentTemplateSpecializationType* T) {
4258 return VisitNestedNameSpecifier(T->getQualifier());
4259}
4260
Douglas Gregord2fa7662010-12-20 02:24:11 +00004261bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4262 const PackExpansionType* T) {
4263 return Visit(T->getPattern());
4264}
4265
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004266bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4267 return false;
4268}
4269
4270bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4271 const ObjCInterfaceType *) {
4272 return false;
4273}
4274
4275bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4276 const ObjCObjectPointerType *) {
4277 return false;
4278}
4279
Eli Friedman0dfb8892011-10-06 23:00:33 +00004280bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4281 return Visit(T->getValueType());
4282}
4283
Xiuli Pan9c14e282016-01-09 12:53:17 +00004284bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4285 return false;
4286}
4287
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004288bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4289 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004290 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004291 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004292 diag::warn_cxx98_compat_template_arg_local_type :
4293 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004294 << S.Context.getTypeDeclType(Tag) << SR;
4295 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296 }
4297
John McCall5ea95772013-03-09 00:54:27 +00004298 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004299 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004300 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004301 diag::warn_cxx98_compat_template_arg_unnamed_type :
4302 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004303 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4304 return true;
4305 }
4306
4307 return false;
4308}
4309
4310bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4311 NestedNameSpecifier *NNS) {
4312 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4313 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004315 switch (NNS->getKind()) {
4316 case NestedNameSpecifier::Identifier:
4317 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004318 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004319 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004320 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004321 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004323 case NestedNameSpecifier::TypeSpec:
4324 case NestedNameSpecifier::TypeSpecWithTemplate:
4325 return Visit(QualType(NNS->getAsType(), 0));
4326 }
David Blaikie8a40f702012-01-17 06:56:22 +00004327 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004328}
4329
Douglas Gregord32e0282009-02-09 23:23:08 +00004330/// \brief Check a template argument against its corresponding
4331/// template type parameter.
4332///
4333/// This routine implements the semantics of C++ [temp.arg.type]. It
4334/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004335bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004336 TypeSourceInfo *ArgInfo) {
4337 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004338 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004339 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004340
4341 if (Arg->isVariablyModifiedType()) {
4342 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004343 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004344 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004345 }
4346
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004347 // C++03 [temp.arg.type]p2:
4348 // A local type, a type with no linkage, an unnamed type or a type
4349 // compounded from any of these types shall not be used as a
4350 // template-argument for a template type-parameter.
4351 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004352 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004353 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004354 bool NeedsCheck;
4355 if (LangOpts.CPlusPlus11)
4356 NeedsCheck =
4357 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4358 SR.getBegin()) ||
4359 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4360 SR.getBegin());
4361 else
4362 NeedsCheck = Arg->hasUnnamedOrLocalType();
4363
4364 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004365 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4366 (void)Finder.Visit(Context.getCanonicalType(Arg));
4367 }
4368
Douglas Gregord32e0282009-02-09 23:23:08 +00004369 return false;
4370}
4371
Douglas Gregor20fdef32012-04-10 17:08:25 +00004372enum NullPointerValueKind {
4373 NPV_NotNullPointer,
4374 NPV_NullPointer,
4375 NPV_Error
4376};
4377
4378/// \brief Determine whether the given template argument is a null pointer
4379/// value of the appropriate type.
4380static NullPointerValueKind
4381isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4382 QualType ParamType, Expr *Arg) {
4383 if (Arg->isValueDependent() || Arg->isTypeDependent())
4384 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004385
Richard Smithdb0ac552015-12-18 22:40:25 +00004386 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004387 llvm_unreachable(
4388 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004389
David Majnemer5c734ad2014-08-14 00:49:23 +00004390 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004391 return NPV_NotNullPointer;
4392
4393 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004394 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4395 if (ArgRV.isInvalid())
4396 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004397 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004398
Douglas Gregor20fdef32012-04-10 17:08:25 +00004399 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004400 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004401 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004402 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004403 EvalResult.HasSideEffects) {
4404 SourceLocation DiagLoc = Arg->getExprLoc();
4405
4406 // If our only note is the usual "invalid subexpression" note, just point
4407 // the caret at its location rather than producing an essentially
4408 // redundant note.
4409 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4410 diag::note_invalid_subexpr_in_const_expr) {
4411 DiagLoc = Notes[0].first;
4412 Notes.clear();
4413 }
4414
4415 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4416 << Arg->getType() << Arg->getSourceRange();
4417 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4418 S.Diag(Notes[I].first, Notes[I].second);
4419
4420 S.Diag(Param->getLocation(), diag::note_template_param_here);
4421 return NPV_Error;
4422 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004423
4424 // C++11 [temp.arg.nontype]p1:
4425 // - an address constant expression of type std::nullptr_t
4426 if (Arg->getType()->isNullPtrType())
4427 return NPV_NullPointer;
4428
4429 // - a constant expression that evaluates to a null pointer value (4.10); or
4430 // - a constant expression that evaluates to a null member pointer value
4431 // (4.11); or
4432 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4433 (EvalResult.Val.isMemberPointer() &&
4434 !EvalResult.Val.getMemberPointerDecl())) {
4435 // If our expression has an appropriate type, we've succeeded.
4436 bool ObjCLifetimeConversion;
4437 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4438 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4439 ObjCLifetimeConversion))
4440 return NPV_NullPointer;
4441
4442 // The types didn't match, but we know we got a null pointer; complain,
4443 // then recover as if the types were correct.
4444 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4445 << Arg->getType() << ParamType << Arg->getSourceRange();
4446 S.Diag(Param->getLocation(), diag::note_template_param_here);
4447 return NPV_NullPointer;
4448 }
4449
4450 // If we don't have a null pointer value, but we do have a NULL pointer
4451 // constant, suggest a cast to the appropriate type.
4452 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4453 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4454 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004455 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4456 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4457 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004458 S.Diag(Param->getLocation(), diag::note_template_param_here);
4459 return NPV_NullPointer;
4460 }
4461
4462 // FIXME: If we ever want to support general, address-constant expressions
4463 // as non-type template arguments, we should return the ExprResult here to
4464 // be interpreted by the caller.
4465 return NPV_NotNullPointer;
4466}
4467
David Majnemer61c39a12013-08-23 05:39:39 +00004468/// \brief Checks whether the given template argument is compatible with its
4469/// template parameter.
4470static bool CheckTemplateArgumentIsCompatibleWithParameter(
4471 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4472 Expr *Arg, QualType ArgType) {
4473 bool ObjCLifetimeConversion;
4474 if (ParamType->isPointerType() &&
4475 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4476 S.IsQualificationConversion(ArgType, ParamType, false,
4477 ObjCLifetimeConversion)) {
4478 // For pointer-to-object types, qualification conversions are
4479 // permitted.
4480 } else {
4481 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4482 if (!ParamRef->getPointeeType()->isFunctionType()) {
4483 // C++ [temp.arg.nontype]p5b3:
4484 // For a non-type template-parameter of type reference to
4485 // object, no conversions apply. The type referred to by the
4486 // reference may be more cv-qualified than the (otherwise
4487 // identical) type of the template- argument. The
4488 // template-parameter is bound directly to the
4489 // template-argument, which shall be an lvalue.
4490
4491 // FIXME: Other qualifiers?
4492 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4493 unsigned ArgQuals = ArgType.getCVRQualifiers();
4494
4495 if ((ParamQuals | ArgQuals) != ParamQuals) {
4496 S.Diag(Arg->getLocStart(),
4497 diag::err_template_arg_ref_bind_ignores_quals)
4498 << ParamType << Arg->getType() << Arg->getSourceRange();
4499 S.Diag(Param->getLocation(), diag::note_template_param_here);
4500 return true;
4501 }
4502 }
4503 }
4504
4505 // At this point, the template argument refers to an object or
4506 // function with external linkage. We now need to check whether the
4507 // argument and parameter types are compatible.
4508 if (!S.Context.hasSameUnqualifiedType(ArgType,
4509 ParamType.getNonReferenceType())) {
4510 // We can't perform this conversion or binding.
4511 if (ParamType->isReferenceType())
4512 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4513 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4514 else
4515 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4516 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4517 S.Diag(Param->getLocation(), diag::note_template_param_here);
4518 return true;
4519 }
4520 }
4521
4522 return false;
4523}
4524
Douglas Gregorccb07762009-02-11 19:52:55 +00004525/// \brief Checks whether the given template argument is the address
4526/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004528CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4529 NonTypeTemplateParmDecl *Param,
4530 QualType ParamType,
4531 Expr *ArgIn,
4532 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004533 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004534 Expr *Arg = ArgIn;
4535 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004536
Douglas Gregorb242683d2010-04-01 18:32:35 +00004537 bool AddressTaken = false;
4538 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004539 if (S.getLangOpts().MicrosoftExt) {
4540 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4541 // dereference and address-of operators.
4542 Arg = Arg->IgnoreParenCasts();
4543
4544 bool ExtWarnMSTemplateArg = false;
4545 UnaryOperatorKind FirstOpKind;
4546 SourceLocation FirstOpLoc;
4547 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4548 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4549 if (UnOpKind == UO_Deref)
4550 ExtWarnMSTemplateArg = true;
4551 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4552 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4553 if (!AddrOpLoc.isValid()) {
4554 FirstOpKind = UnOpKind;
4555 FirstOpLoc = UnOp->getOperatorLoc();
4556 }
4557 } else
4558 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004559 }
David Majnemer61c39a12013-08-23 05:39:39 +00004560 if (FirstOpLoc.isValid()) {
4561 if (ExtWarnMSTemplateArg)
4562 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4563 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004564
David Majnemer61c39a12013-08-23 05:39:39 +00004565 if (FirstOpKind == UO_AddrOf)
4566 AddressTaken = true;
4567 else if (Arg->getType()->isPointerType()) {
4568 // We cannot let pointers get dereferenced here, that is obviously not a
4569 // constant expression.
4570 assert(FirstOpKind == UO_Deref);
4571 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4572 << Arg->getSourceRange();
4573 }
4574 }
4575 } else {
4576 // See through any implicit casts we added to fix the type.
4577 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004578
David Majnemer61c39a12013-08-23 05:39:39 +00004579 // C++ [temp.arg.nontype]p1:
4580 //
4581 // A template-argument for a non-type, non-template
4582 // template-parameter shall be one of: [...]
4583 //
4584 // -- the address of an object or function with external
4585 // linkage, including function templates and function
4586 // template-ids but excluding non-static class members,
4587 // expressed as & id-expression where the & is optional if
4588 // the name refers to a function or array, or if the
4589 // corresponding template-parameter is a reference; or
4590
4591 // In C++98/03 mode, give an extension warning on any extra parentheses.
4592 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4593 bool ExtraParens = false;
4594 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4595 if (!Invalid && !ExtraParens) {
4596 S.Diag(Arg->getLocStart(),
4597 S.getLangOpts().CPlusPlus11
4598 ? diag::warn_cxx98_compat_template_arg_extra_parens
4599 : diag::ext_template_arg_extra_parens)
4600 << Arg->getSourceRange();
4601 ExtraParens = true;
4602 }
4603
4604 Arg = Parens->getSubExpr();
4605 }
4606
4607 while (SubstNonTypeTemplateParmExpr *subst =
4608 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4609 Arg = subst->getReplacement()->IgnoreImpCasts();
4610
4611 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4612 if (UnOp->getOpcode() == UO_AddrOf) {
4613 Arg = UnOp->getSubExpr();
4614 AddressTaken = true;
4615 AddrOpLoc = UnOp->getOperatorLoc();
4616 }
4617 }
4618
4619 while (SubstNonTypeTemplateParmExpr *subst =
4620 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4621 Arg = subst->getReplacement()->IgnoreImpCasts();
4622 }
John McCall7c454bb2011-07-15 05:09:51 +00004623
David Majnemer07910d62014-06-26 07:48:46 +00004624 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4625 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4626
4627 // If our parameter has pointer type, check for a null template value.
4628 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4629 NullPointerValueKind NPV;
4630 // dllimport'd entities aren't constant but are available inside of template
4631 // arguments.
4632 if (Entity && Entity->hasAttr<DLLImportAttr>())
4633 NPV = NPV_NotNullPointer;
4634 else
4635 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4636 switch (NPV) {
4637 case NPV_NullPointer:
4638 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004639 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4640 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004641 return false;
4642
4643 case NPV_Error:
4644 return true;
4645
4646 case NPV_NotNullPointer:
4647 break;
4648 }
4649 }
4650
Chandler Carruth724a8a12010-01-31 10:01:20 +00004651 // Stop checking the precise nature of the argument if it is value dependent,
4652 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004653 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004654 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004655 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004656 }
David Majnemer61c39a12013-08-23 05:39:39 +00004657
4658 if (isa<CXXUuidofExpr>(Arg)) {
4659 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4660 ArgIn, Arg, ArgType))
4661 return true;
4662
4663 Converted = TemplateArgument(ArgIn);
4664 return false;
4665 }
4666
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004667 if (!DRE) {
4668 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4669 << Arg->getSourceRange();
4670 S.Diag(Param->getLocation(), diag::note_template_param_here);
4671 return true;
4672 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004673
Douglas Gregorccb07762009-02-11 19:52:55 +00004674 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004675 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004676 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004677 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004678 S.Diag(Param->getLocation(), diag::note_template_param_here);
4679 return true;
4680 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004681
4682 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004683 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004684 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004685 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004686 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004687 S.Diag(Param->getLocation(), diag::note_template_param_here);
4688 return true;
4689 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004690 }
Mike Stump11289f42009-09-09 15:08:12 +00004691
Richard Smith9380e0e2012-04-04 21:11:30 +00004692 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4693 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004694
Richard Smith9380e0e2012-04-04 21:11:30 +00004695 // A non-type template argument must refer to an object or function.
4696 if (!Func && !Var) {
4697 // We found something, but we don't know specifically what it is.
4698 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4699 << Arg->getSourceRange();
4700 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4701 return true;
4702 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004703
Richard Smith9380e0e2012-04-04 21:11:30 +00004704 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004705 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004706 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004707 diag::warn_cxx98_compat_template_arg_object_internal :
4708 diag::ext_template_arg_object_internal)
4709 << !Func << Entity << Arg->getSourceRange();
4710 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4711 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004712 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004713 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4714 << !Func << Entity << Arg->getSourceRange();
4715 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4716 << !Func;
4717 return true;
4718 }
4719
4720 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004721 // If the template parameter has pointer type, the function decays.
4722 if (ParamType->isPointerType() && !AddressTaken)
4723 ArgType = S.Context.getPointerType(Func->getType());
4724 else if (AddressTaken && ParamType->isReferenceType()) {
4725 // If we originally had an address-of operator, but the
4726 // parameter has reference type, complain and (if things look
4727 // like they will work) drop the address-of operator.
4728 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4729 ParamType.getNonReferenceType())) {
4730 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4731 << ParamType;
4732 S.Diag(Param->getLocation(), diag::note_template_param_here);
4733 return true;
4734 }
4735
4736 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4737 << ParamType
4738 << FixItHint::CreateRemoval(AddrOpLoc);
4739 S.Diag(Param->getLocation(), diag::note_template_param_here);
4740
4741 ArgType = Func->getType();
4742 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004743 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004744 // A value of reference type is not an object.
4745 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004746 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004747 diag::err_template_arg_reference_var)
4748 << Var->getType() << Arg->getSourceRange();
4749 S.Diag(Param->getLocation(), diag::note_template_param_here);
4750 return true;
4751 }
4752
Richard Smith9380e0e2012-04-04 21:11:30 +00004753 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004754 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004755 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4756 << Arg->getSourceRange();
4757 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4758 return true;
4759 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004760
4761 // If the template parameter has pointer type, we must have taken
4762 // the address of this object.
4763 if (ParamType->isReferenceType()) {
4764 if (AddressTaken) {
4765 // If we originally had an address-of operator, but the
4766 // parameter has reference type, complain and (if things look
4767 // like they will work) drop the address-of operator.
4768 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4769 ParamType.getNonReferenceType())) {
4770 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4771 << ParamType;
4772 S.Diag(Param->getLocation(), diag::note_template_param_here);
4773 return true;
4774 }
4775
4776 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4777 << ParamType
4778 << FixItHint::CreateRemoval(AddrOpLoc);
4779 S.Diag(Param->getLocation(), diag::note_template_param_here);
4780
4781 ArgType = Var->getType();
4782 }
4783 } else if (!AddressTaken && ParamType->isPointerType()) {
4784 if (Var->getType()->isArrayType()) {
4785 // Array-to-pointer decay.
4786 ArgType = S.Context.getArrayDecayedType(Var->getType());
4787 } else {
4788 // If the template parameter has pointer type but the address of
4789 // this object was not taken, complain and (possibly) recover by
4790 // taking the address of the entity.
4791 ArgType = S.Context.getPointerType(Var->getType());
4792 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4793 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4794 << ParamType;
4795 S.Diag(Param->getLocation(), diag::note_template_param_here);
4796 return true;
4797 }
4798
4799 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4800 << ParamType
4801 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4802
4803 S.Diag(Param->getLocation(), diag::note_template_param_here);
4804 }
4805 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004806 }
Mike Stump11289f42009-09-09 15:08:12 +00004807
David Majnemer61c39a12013-08-23 05:39:39 +00004808 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4809 Arg, ArgType))
4810 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004811
4812 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004813 Converted =
4814 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004815 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004816 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004817}
4818
4819/// \brief Checks whether the given template argument is a pointer to
4820/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004821static bool CheckTemplateArgumentPointerToMember(Sema &S,
4822 NonTypeTemplateParmDecl *Param,
4823 QualType ParamType,
4824 Expr *&ResultArg,
4825 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004826 bool Invalid = false;
4827
Douglas Gregor20fdef32012-04-10 17:08:25 +00004828 // Check for a null pointer value.
4829 Expr *Arg = ResultArg;
4830 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4831 case NPV_Error:
4832 return true;
4833 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004834 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004835 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4836 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004837 return false;
4838 case NPV_NotNullPointer:
4839 break;
4840 }
4841
4842 bool ObjCLifetimeConversion;
4843 if (S.IsQualificationConversion(Arg->getType(),
4844 ParamType.getNonReferenceType(),
4845 false, ObjCLifetimeConversion)) {
4846 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004847 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004848 ResultArg = Arg;
4849 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4850 ParamType.getNonReferenceType())) {
4851 // We can't perform this conversion.
4852 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4853 << Arg->getType() << ParamType << Arg->getSourceRange();
4854 S.Diag(Param->getLocation(), diag::note_template_param_here);
4855 return true;
4856 }
4857
Douglas Gregorccb07762009-02-11 19:52:55 +00004858 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004859 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004860 Arg = Cast->getSubExpr();
4861
4862 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004863 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004864 // A template-argument for a non-type, non-template
4865 // template-parameter shall be one of: [...]
4866 //
4867 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004868 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004869
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004870 // In C++98/03 mode, give an extension warning on any extra parentheses.
4871 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4872 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004873 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004874 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004875 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004876 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004877 diag::warn_cxx98_compat_template_arg_extra_parens :
4878 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004879 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004880 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004881 }
4882
4883 Arg = Parens->getSubExpr();
4884 }
4885
John McCall7c454bb2011-07-15 05:09:51 +00004886 while (SubstNonTypeTemplateParmExpr *subst =
4887 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4888 Arg = subst->getReplacement()->IgnoreImpCasts();
4889
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004890 // A pointer-to-member constant written &Class::member.
4891 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004892 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004893 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4894 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004895 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004897 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004898 // A constant of pointer-to-member type.
4899 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4900 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4901 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004902 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004903 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004904 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004905 } else {
4906 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004907 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004908 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004909 return Invalid;
4910 }
4911 }
4912 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004913
Craig Topperc3ec1492014-05-26 06:22:03 +00004914 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916
Douglas Gregorccb07762009-02-11 19:52:55 +00004917 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004918 return S.Diag(Arg->getLocStart(),
4919 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004920 << Arg->getSourceRange();
4921
David Majnemer3ac84e62013-10-22 21:56:38 +00004922 if (isa<FieldDecl>(DRE->getDecl()) ||
4923 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4924 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004925 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004926 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004927 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4928 "Only non-static member pointers can make it here");
4929
4930 // Okay: this is the address of a non-static member, and therefore
4931 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004932 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004933 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004934 } else {
4935 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004936 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004937 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004938 return Invalid;
4939 }
4940
4941 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004942 S.Diag(Arg->getLocStart(),
4943 diag::err_template_arg_not_pointer_to_member_form)
4944 << Arg->getSourceRange();
4945 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004946 return true;
4947}
4948
Douglas Gregord32e0282009-02-09 23:23:08 +00004949/// \brief Check a template argument against its corresponding
4950/// non-type template parameter.
4951///
Douglas Gregor463421d2009-03-03 04:44:36 +00004952/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004953/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004954/// returns the converted template argument. \p ParamType is the
4955/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004956ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004957 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004958 TemplateArgument &Converted,
4959 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004960 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004961
Douglas Gregor86560402009-02-10 23:36:10 +00004962 // If either the parameter has a dependent type or the argument is
4963 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004964 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004965 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004966 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004967 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004968 }
Douglas Gregor86560402009-02-10 23:36:10 +00004969
Richard Smithd663fdd2014-12-17 20:42:37 +00004970 // We should have already dropped all cv-qualifiers by now.
4971 assert(!ParamType.hasQualifiers() &&
4972 "non-type template parameter type cannot be qualified");
4973
4974 if (CTAK == CTAK_Deduced &&
4975 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4976 // C++ [temp.deduct.type]p17:
4977 // If, in the declaration of a function template with a non-type
4978 // template-parameter, the non-type template-parameter is used
4979 // in an expression in the function parameter-list and, if the
4980 // corresponding template-argument is deduced, the
4981 // template-argument type shall match the type of the
4982 // template-parameter exactly, except that a template-argument
4983 // deduced from an array bound may be of any integral type.
4984 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4985 << Arg->getType().getUnqualifiedType()
4986 << ParamType.getUnqualifiedType();
4987 Diag(Param->getLocation(), diag::note_template_param_here);
4988 return ExprError();
4989 }
4990
Richard Smith410cc892014-11-26 03:26:53 +00004991 if (getLangOpts().CPlusPlus1z) {
4992 // FIXME: We can do some limited checking for a value-dependent but not
4993 // type-dependent argument.
4994 if (Arg->isValueDependent()) {
4995 Converted = TemplateArgument(Arg);
4996 return Arg;
4997 }
4998
4999 // C++1z [temp.arg.nontype]p1:
5000 // A template-argument for a non-type template parameter shall be
5001 // a converted constant expression of the type of the template-parameter.
5002 APValue Value;
5003 ExprResult ArgResult = CheckConvertedConstantExpression(
5004 Arg, ParamType, Value, CCEK_TemplateArg);
5005 if (ArgResult.isInvalid())
5006 return ExprError();
5007
Richard Smithd663fdd2014-12-17 20:42:37 +00005008 QualType CanonParamType = Context.getCanonicalType(ParamType);
5009
Richard Smith410cc892014-11-26 03:26:53 +00005010 // Convert the APValue to a TemplateArgument.
5011 switch (Value.getKind()) {
5012 case APValue::Uninitialized:
5013 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005014 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005015 break;
5016 case APValue::Int:
5017 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00005018 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00005019 break;
5020 case APValue::MemberPointer: {
5021 assert(ParamType->isMemberPointerType());
5022
5023 // FIXME: We need TemplateArgument representation and mangling for these.
5024 if (!Value.getMemberPointerPath().empty()) {
5025 Diag(Arg->getLocStart(),
5026 diag::err_template_arg_member_ptr_base_derived_not_supported)
5027 << Value.getMemberPointerDecl() << ParamType
5028 << Arg->getSourceRange();
5029 return ExprError();
5030 }
5031
5032 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00005033 Converted = VD ? TemplateArgument(VD, CanonParamType)
5034 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005035 break;
5036 }
5037 case APValue::LValue: {
5038 // For a non-type template-parameter of pointer or reference type,
5039 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00005040 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5041 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00005042 // -- a temporary object
5043 // -- a string literal
5044 // -- the result of a typeid expression, or
5045 // -- a predefind __func__ variable
5046 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5047 if (isa<CXXUuidofExpr>(E)) {
5048 Converted = TemplateArgument(const_cast<Expr*>(E));
5049 break;
5050 }
5051 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5052 << Arg->getSourceRange();
5053 return ExprError();
5054 }
5055 auto *VD = const_cast<ValueDecl *>(
5056 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5057 // -- a subobject
5058 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5059 VD && VD->getType()->isArrayType() &&
5060 Value.getLValuePath()[0].ArrayIndex == 0 &&
5061 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5062 // Per defect report (no number yet):
5063 // ... other than a pointer to the first element of a complete array
5064 // object.
5065 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5066 Value.isLValueOnePastTheEnd()) {
5067 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5068 << Value.getAsString(Context, ParamType);
5069 return ExprError();
5070 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005071 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005072 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005073 assert((!VD || !ParamType->isNullPtrType()) &&
5074 "non-null value of type nullptr_t?");
5075 Converted = VD ? TemplateArgument(VD, CanonParamType)
5076 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005077 break;
5078 }
5079 case APValue::AddrLabelDiff:
5080 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5081 case APValue::Float:
5082 case APValue::ComplexInt:
5083 case APValue::ComplexFloat:
5084 case APValue::Vector:
5085 case APValue::Array:
5086 case APValue::Struct:
5087 case APValue::Union:
5088 llvm_unreachable("invalid kind for template argument");
5089 }
5090
5091 return ArgResult.get();
5092 }
5093
Douglas Gregor86560402009-02-10 23:36:10 +00005094 // C++ [temp.arg.nontype]p5:
5095 // The following conversions are performed on each expression used
5096 // as a non-type template-argument. If a non-type
5097 // template-argument cannot be converted to the type of the
5098 // corresponding template-parameter then the program is
5099 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005100 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005101 // C++11:
5102 // -- for a non-type template-parameter of integral or
5103 // enumeration type, conversions permitted in a converted
5104 // constant expression are applied.
5105 //
5106 // C++98:
5107 // -- for a non-type template-parameter of integral or
5108 // enumeration type, integral promotions (4.5) and integral
5109 // conversions (4.7) are applied.
5110
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005111 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005112 // We can't check arbitrary value-dependent arguments.
5113 // FIXME: If there's no viable conversion to the template parameter type,
5114 // we should be able to diagnose that prior to instantiation.
5115 if (Arg->isValueDependent()) {
5116 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005117 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005118 }
5119
5120 // C++ [temp.arg.nontype]p1:
5121 // A template-argument for a non-type, non-template template-parameter
5122 // shall be one of:
5123 //
5124 // -- for a non-type template-parameter of integral or enumeration
5125 // type, a converted constant expression of the type of the
5126 // template-parameter; or
5127 llvm::APSInt Value;
5128 ExprResult ArgResult =
5129 CheckConvertedConstantExpression(Arg, ParamType, Value,
5130 CCEK_TemplateArg);
5131 if (ArgResult.isInvalid())
5132 return ExprError();
5133
5134 // Widen the argument value to sizeof(parameter type). This is almost
5135 // always a no-op, except when the parameter type is bool. In
5136 // that case, this may extend the argument from 1 bit to 8 bits.
5137 QualType IntegerType = ParamType;
5138 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5139 IntegerType = Enum->getDecl()->getIntegerType();
5140 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5141
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005142 Converted = TemplateArgument(Context, Value,
5143 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005144 return ArgResult;
5145 }
5146
Richard Smith08b12f12011-10-27 22:11:44 +00005147 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5148 if (ArgResult.isInvalid())
5149 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005150 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005151
5152 QualType ArgType = Arg->getType();
5153
Douglas Gregor86560402009-02-10 23:36:10 +00005154 // C++ [temp.arg.nontype]p1:
5155 // A template-argument for a non-type, non-template
5156 // template-parameter shall be one of:
5157 //
5158 // -- an integral constant-expression of integral or enumeration
5159 // type; or
5160 // -- the name of a non-type template-parameter; or
5161 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005162 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005163 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005164 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005165 diag::err_template_arg_not_integral_or_enumeral)
5166 << ArgType << Arg->getSourceRange();
5167 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005168 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005169 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005170 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5171 QualType T;
5172
5173 public:
5174 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005175
5176 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5177 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005178 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5179 }
5180 } Diagnoser(ArgType);
5181
5182 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005183 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005184 if (!Arg)
5185 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005186 }
5187
Richard Smithd663fdd2014-12-17 20:42:37 +00005188 // From here on out, all we care about is the unqualified form
5189 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005190 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005191
5192 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005193 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005194 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005195 } else if (ParamType->isBooleanType()) {
5196 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005197 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005198 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5199 !ParamType->isEnumeralType()) {
5200 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005201 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005202 } else {
5203 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005204 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005205 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005206 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005207 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005208 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005209 }
5210
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005211 // Add the value of this argument to the list of converted
5212 // arguments. We use the bitwidth and signedness of the template
5213 // parameter.
5214 if (Arg->isValueDependent()) {
5215 // The argument is value-dependent. Create a new
5216 // TemplateArgument with the converted expression.
5217 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005218 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005219 }
5220
Douglas Gregor52aba872009-03-14 00:20:21 +00005221 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005222 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005223 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005224
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005225 if (ParamType->isBooleanType()) {
5226 // Value must be zero or one.
5227 Value = Value != 0;
5228 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5229 if (Value.getBitWidth() != AllowedBits)
5230 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005231 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005232 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005233 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005234
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005235 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005236 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005237 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005238 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005239 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005240 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005241
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005242 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005243 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005244 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005245 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005246 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5247 << Arg->getSourceRange();
5248 Diag(Param->getLocation(), diag::note_template_param_here);
5249 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005250
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005251 // Complain if we overflowed the template parameter's type.
5252 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005253 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005254 RequiredBits = OldValue.getActiveBits();
5255 else if (OldValue.isUnsigned())
5256 RequiredBits = OldValue.getActiveBits() + 1;
5257 else
5258 RequiredBits = OldValue.getMinSignedBits();
5259 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005260 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005261 diag::warn_template_arg_too_large)
5262 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5263 << Arg->getSourceRange();
5264 Diag(Param->getLocation(), diag::note_template_param_here);
5265 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005266 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005267
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005268 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005269 ParamType->isEnumeralType()
5270 ? Context.getCanonicalType(ParamType)
5271 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005272 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005273 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005274
Richard Smith08b12f12011-10-27 22:11:44 +00005275 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005276 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5277
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005278 // Handle pointer-to-function, reference-to-function, and
5279 // pointer-to-member-function all in (roughly) the same way.
5280 if (// -- For a non-type template-parameter of type pointer to
5281 // function, only the function-to-pointer conversion (4.3) is
5282 // applied. If the template-argument represents a set of
5283 // overloaded functions (or a pointer to such), the matching
5284 // function is selected from the set (13.4).
5285 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005286 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005287 // -- For a non-type template-parameter of type reference to
5288 // function, no conversions apply. If the template-argument
5289 // represents a set of overloaded functions, the matching
5290 // function is selected from the set (13.4).
5291 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005292 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005293 // -- For a non-type template-parameter of type pointer to
5294 // member function, no conversions apply. If the
5295 // template-argument represents a set of overloaded member
5296 // functions, the matching member function is selected from
5297 // the set (13.4).
5298 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005299 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005300 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005301
Douglas Gregor064fdb22010-04-14 23:11:21 +00005302 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005304 true,
5305 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005306 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005307 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005308
5309 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5310 ArgType = Arg->getType();
5311 } else
John Wiegley01296292011-04-08 18:41:53 +00005312 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005314
John Wiegley01296292011-04-08 18:41:53 +00005315 if (!ParamType->isMemberPointerType()) {
5316 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5317 ParamType,
5318 Arg, Converted))
5319 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005320 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005321 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005322
Douglas Gregor20fdef32012-04-10 17:08:25 +00005323 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5324 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005325 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005326 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005327 }
5328
Chris Lattner696197c2009-02-20 21:37:53 +00005329 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005330 // -- for a non-type template-parameter of type pointer to
5331 // object, qualification conversions (4.4) and the
5332 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005333 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005334 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005335 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005336
John Wiegley01296292011-04-08 18:41:53 +00005337 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5338 ParamType,
5339 Arg, Converted))
5340 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005341 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005342 }
Mike Stump11289f42009-09-09 15:08:12 +00005343
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005344 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005345 // -- For a non-type template-parameter of type reference to
5346 // object, no conversions apply. The type referred to by the
5347 // reference may be more cv-qualified than the (otherwise
5348 // identical) type of the template-argument. The
5349 // template-parameter is bound directly to the
5350 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005351 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005352 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005353
Douglas Gregor064fdb22010-04-14 23:11:21 +00005354 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005355 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5356 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005357 true,
5358 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005359 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005360 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005361
5362 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5363 ArgType = Arg->getType();
5364 } else
John Wiegley01296292011-04-08 18:41:53 +00005365 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367
John Wiegley01296292011-04-08 18:41:53 +00005368 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5369 ParamType,
5370 Arg, Converted))
5371 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005372 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005373 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005374
Douglas Gregor20fdef32012-04-10 17:08:25 +00005375 // Deal with parameters of type std::nullptr_t.
5376 if (ParamType->isNullPtrType()) {
5377 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5378 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005379 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005380 }
5381
5382 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5383 case NPV_NotNullPointer:
5384 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5385 << Arg->getType() << ParamType;
5386 Diag(Param->getLocation(), diag::note_template_param_here);
5387 return ExprError();
5388
5389 case NPV_Error:
5390 return ExprError();
5391
5392 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005393 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005394 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5395 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005396 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005397 }
5398 }
5399
Douglas Gregor0e558532009-02-11 16:16:59 +00005400 // -- For a non-type template-parameter of type pointer to data
5401 // member, qualification conversions (4.4) are applied.
5402 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5403
Douglas Gregor20fdef32012-04-10 17:08:25 +00005404 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5405 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005406 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005407 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005408}
5409
5410/// \brief Check a template argument against its corresponding
5411/// template template parameter.
5412///
5413/// This routine implements the semantics of C++ [temp.arg.template].
5414/// It returns true if an error occurred, and false otherwise.
5415bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005416 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005417 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005418 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005419 TemplateDecl *Template = Name.getAsTemplateDecl();
5420 if (!Template) {
5421 // Any dependent template name is fine.
5422 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5423 return false;
5424 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005425
Richard Smith3f1b5d02011-05-05 21:57:07 +00005426 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005427 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005428 // the name of a class template or an alias template, expressed as an
5429 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005430 // primary class templates are considered when matching the
5431 // template template argument with the corresponding parameter;
5432 // partial specializations are not considered even if their
5433 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005434 //
5435 // Note that we also allow template template parameters here, which
5436 // will happen when we are dealing with, e.g., class template
5437 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005438 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005439 !isa<TemplateTemplateParmDecl>(Template) &&
David Majnemerc2406d42016-07-11 17:09:56 +00005440 !isa<TypeAliasTemplateDecl>(Template) &&
5441 !isa<BuiltinTemplateDecl>(Template)) {
5442 assert(isa<FunctionTemplateDecl>(Template) &&
5443 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005444 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
David Majnemerc2406d42016-07-11 17:09:56 +00005445 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5446 << Template;
Douglas Gregor85e0f662009-02-10 00:24:35 +00005447 }
5448
Richard Smith1fde8ec2012-09-07 02:06:42 +00005449 TemplateParameterList *Params = Param->getTemplateParameters();
5450 if (Param->isExpandedParameterPack())
5451 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5452
Douglas Gregor85e0f662009-02-10 00:24:35 +00005453 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005454 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005455 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005456 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005457 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005458}
5459
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005460/// \brief Given a non-type template argument that refers to a
5461/// declaration and the type of its corresponding non-type template
5462/// parameter, produce an expression that properly refers to that
5463/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005465Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5466 QualType ParamType,
5467 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005468 // C++ [temp.param]p8:
5469 //
5470 // A non-type template-parameter of type "array of T" or
5471 // "function returning T" is adjusted to be of type "pointer to
5472 // T" or "pointer to function returning T", respectively.
5473 if (ParamType->isArrayType())
5474 ParamType = Context.getArrayDecayedType(ParamType);
5475 else if (ParamType->isFunctionType())
5476 ParamType = Context.getPointerType(ParamType);
5477
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005478 // For a NULL non-type template argument, return nullptr casted to the
5479 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005480 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005481 return ImpCastExprToType(
5482 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5483 ParamType,
5484 ParamType->getAs<MemberPointerType>()
5485 ? CK_NullToMemberPointer
5486 : CK_NullToPointer);
5487 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005488 assert(Arg.getKind() == TemplateArgument::Declaration &&
5489 "Only declaration template arguments permitted here");
5490
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005491 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5492
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005494 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5495 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005496 // If the value is a class member, we might have a pointer-to-member.
5497 // Determine whether the non-type template template parameter is of
5498 // pointer-to-member type. If so, we need to build an appropriate
5499 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5500 // would refer to the member itself.
5501 if (ParamType->isMemberPointerType()) {
5502 QualType ClassType
5503 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5504 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005505 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005506 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005507 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005508 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005509
5510 // The actual value-ness of this is unimportant, but for
5511 // internal consistency's sake, references to instance methods
5512 // are r-values.
5513 ExprValueKind VK = VK_LValue;
5514 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5515 VK = VK_RValue;
5516
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005518 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005519 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005520 Loc,
5521 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005522 if (RefExpr.isInvalid())
5523 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
John McCalle3027922010-08-25 11:45:40 +00005525 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005527 // We might need to perform a trailing qualification conversion, since
5528 // the element type on the parameter could be more qualified than the
5529 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005530 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005531 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005532 ParamType.getUnqualifiedType(), false,
5533 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005534 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005535
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005536 assert(!RefExpr.isInvalid() &&
5537 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005538 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005539 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005540 }
5541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005543 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005544
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005545 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005546 // When the non-type template parameter is a pointer, take the
5547 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005548 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005549 if (RefExpr.isInvalid())
5550 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005551
5552 if (T->isFunctionType() || T->isArrayType()) {
5553 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005554 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005555 if (RefExpr.isInvalid())
5556 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005557
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005558 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005560
Douglas Gregorb242683d2010-04-01 18:32:35 +00005561 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005562 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005563 }
5564
John McCall7decc9e2010-11-18 06:31:45 +00005565 ExprValueKind VK = VK_RValue;
5566
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005567 // If the non-type template parameter has reference type, qualify the
5568 // resulting declaration reference with the extra qualifiers on the
5569 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005570 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5571 VK = VK_LValue;
5572 T = Context.getQualifiedType(T,
5573 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005574 } else if (isa<FunctionDecl>(VD)) {
5575 // References to functions are always lvalues.
5576 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578
John McCall7decc9e2010-11-18 06:31:45 +00005579 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005580}
5581
5582/// \brief Construct a new expression that refers to the given
5583/// integral template argument with the given source-location
5584/// information.
5585///
5586/// This routine takes care of the mapping from an integral template
5587/// argument (which may have any integral type) to the appropriate
5588/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005589ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005590Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5591 SourceLocation Loc) {
5592 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005593 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005594 QualType OrigT = Arg.getIntegralType();
5595
5596 // If this is an enum type that we're instantiating, we need to use an integer
5597 // type the same size as the enumerator. We don't want to build an
5598 // IntegerLiteral with enum type. The integer type of an enum type can be of
5599 // any integral type with C++11 enum classes, make sure we create the right
5600 // type of literal for it.
5601 QualType T = OrigT;
5602 if (const EnumType *ET = OrigT->getAs<EnumType>())
5603 T = ET->getDecl()->getIntegerType();
5604
5605 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005606 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005607 // This does not need to handle u8 character literals because those are
5608 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005609 CharacterLiteral::CharacterKind Kind;
5610 if (T->isWideCharType())
5611 Kind = CharacterLiteral::Wide;
5612 else if (T->isChar16Type())
5613 Kind = CharacterLiteral::UTF16;
5614 else if (T->isChar32Type())
5615 Kind = CharacterLiteral::UTF32;
5616 else
5617 Kind = CharacterLiteral::Ascii;
5618
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005619 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5620 Kind, T, Loc);
5621 } else if (T->isBooleanType()) {
5622 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5623 T, Loc);
5624 } else if (T->isNullPtrType()) {
5625 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5626 } else {
5627 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005628 }
5629
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005630 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005631 // FIXME: This is a hack. We need a better way to handle substituted
5632 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005633 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5634 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005635 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005636 Loc, Loc);
5637 }
5638
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005639 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005640}
5641
Douglas Gregor641040a2011-01-12 23:45:44 +00005642/// \brief Match two template parameters within template parameter lists.
5643static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5644 bool Complain,
5645 Sema::TemplateParameterListEqualKind Kind,
5646 SourceLocation TemplateArgLoc) {
5647 // Check the actual kind (type, non-type, template).
5648 if (Old->getKind() != New->getKind()) {
5649 if (Complain) {
5650 unsigned NextDiag = diag::err_template_param_different_kind;
5651 if (TemplateArgLoc.isValid()) {
5652 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5653 NextDiag = diag::note_template_param_different_kind;
5654 }
5655 S.Diag(New->getLocation(), NextDiag)
5656 << (Kind != Sema::TPL_TemplateMatch);
5657 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5658 << (Kind != Sema::TPL_TemplateMatch);
5659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregor641040a2011-01-12 23:45:44 +00005661 return false;
5662 }
5663
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664 // Check that both are parameter packs are neither are parameter packs.
5665 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005666 // template template parameter, the template template parameter can have
5667 // a parameter pack where the template template argument does not.
5668 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5669 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5670 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005671 if (Complain) {
5672 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5673 if (TemplateArgLoc.isValid()) {
5674 S.Diag(TemplateArgLoc,
5675 diag::err_template_arg_template_params_mismatch);
5676 NextDiag = diag::note_template_parameter_pack_non_pack;
5677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
Douglas Gregor641040a2011-01-12 23:45:44 +00005679 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5680 : isa<NonTypeTemplateParmDecl>(New)? 1
5681 : 2;
5682 S.Diag(New->getLocation(), NextDiag)
5683 << ParamKind << New->isParameterPack();
5684 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5685 << ParamKind << Old->isParameterPack();
5686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005687
Douglas Gregor641040a2011-01-12 23:45:44 +00005688 return false;
5689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005690
Douglas Gregor641040a2011-01-12 23:45:44 +00005691 // For non-type template parameters, check the type of the parameter.
5692 if (NonTypeTemplateParmDecl *OldNTTP
5693 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5694 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Douglas Gregor641040a2011-01-12 23:45:44 +00005696 // If we are matching a template template argument to a template
5697 // template parameter and one of the non-type template parameter types
5698 // is dependent, then we must wait until template instantiation time
5699 // to actually compare the arguments.
5700 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5701 (OldNTTP->getType()->isDependentType() ||
5702 NewNTTP->getType()->isDependentType()))
5703 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005704
Douglas Gregor641040a2011-01-12 23:45:44 +00005705 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5706 if (Complain) {
5707 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5708 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005710 diag::err_template_arg_template_params_mismatch);
5711 NextDiag = diag::note_template_nontype_parm_different_type;
5712 }
5713 S.Diag(NewNTTP->getLocation(), NextDiag)
5714 << NewNTTP->getType()
5715 << (Kind != Sema::TPL_TemplateMatch);
5716 S.Diag(OldNTTP->getLocation(),
5717 diag::note_template_nontype_parm_prev_declaration)
5718 << OldNTTP->getType();
5719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregor641040a2011-01-12 23:45:44 +00005721 return false;
5722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005723
Douglas Gregor641040a2011-01-12 23:45:44 +00005724 return true;
5725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726
Douglas Gregor641040a2011-01-12 23:45:44 +00005727 // For template template parameters, check the template parameter types.
5728 // The template parameter lists of template template
5729 // parameters must agree.
5730 if (TemplateTemplateParmDecl *OldTTP
5731 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005733 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5734 OldTTP->getTemplateParameters(),
5735 Complain,
5736 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005738 : Kind),
5739 TemplateArgLoc);
5740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Douglas Gregor641040a2011-01-12 23:45:44 +00005742 return true;
5743}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005744
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005745/// \brief Diagnose a known arity mismatch when comparing template argument
5746/// lists.
5747static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005749 TemplateParameterList *New,
5750 TemplateParameterList *Old,
5751 Sema::TemplateParameterListEqualKind Kind,
5752 SourceLocation TemplateArgLoc) {
5753 unsigned NextDiag = diag::err_template_param_list_different_arity;
5754 if (TemplateArgLoc.isValid()) {
5755 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5756 NextDiag = diag::note_template_param_list_different_arity;
5757 }
5758 S.Diag(New->getTemplateLoc(), NextDiag)
5759 << (New->size() > Old->size())
5760 << (Kind != Sema::TPL_TemplateMatch)
5761 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5762 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5763 << (Kind != Sema::TPL_TemplateMatch)
5764 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5765}
5766
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005767/// \brief Determine whether the given template parameter lists are
5768/// equivalent.
5769///
Mike Stump11289f42009-09-09 15:08:12 +00005770/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005771/// source code as part of a new template declaration.
5772///
5773/// \param Old The old template parameter list, typically found via
5774/// name lookup of the template declared with this template parameter
5775/// list.
5776///
5777/// \param Complain If true, this routine will produce a diagnostic if
5778/// the template parameter lists are not equivalent.
5779///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005780/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005781///
5782/// \param TemplateArgLoc If this source location is valid, then we
5783/// are actually checking the template parameter list of a template
5784/// argument (New) against the template parameter list of its
5785/// corresponding template template parameter (Old). We produce
5786/// slightly different diagnostics in this scenario.
5787///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005788/// \returns True if the template parameter lists are equal, false
5789/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005790bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005791Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5792 TemplateParameterList *Old,
5793 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005794 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005795 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005796 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5797 if (Complain)
5798 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5799 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005800
5801 return false;
5802 }
5803
Douglas Gregor641040a2011-01-12 23:45:44 +00005804 // C++0x [temp.arg.template]p3:
5805 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005806 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005807 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005808 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005809 // template-parameter-list of P. [...]
5810 TemplateParameterList::iterator NewParm = New->begin();
5811 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005812 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005813 OldParmEnd = Old->end();
5814 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005815 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5816 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005817 if (NewParm == NewParmEnd) {
5818 if (Complain)
5819 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5820 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005822 return false;
5823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005824
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005825 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5826 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827 return false;
5828
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005829 ++NewParm;
5830 continue;
5831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005832
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005833 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005834 // [...] When P's template- parameter-list contains a template parameter
5835 // pack (14.5.3), the template parameter pack will match zero or more
5836 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005837 // template-parameter-list of A with the same type and form as the
5838 // template parameter pack in P (ignoring whether those template
5839 // parameters are template parameter packs).
5840 for (; NewParm != NewParmEnd; ++NewParm) {
5841 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5842 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005844 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005846
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005847 // Make sure we exhausted all of the arguments.
5848 if (NewParm != NewParmEnd) {
5849 if (Complain)
5850 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5851 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005853 return false;
5854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005855
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005856 return true;
5857}
5858
5859/// \brief Check whether a template can be declared within this scope.
5860///
5861/// If the template declaration is valid in this scope, returns
5862/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005863bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005864Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005865 if (!S)
5866 return false;
5867
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005868 // Find the nearest enclosing declaration scope.
5869 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5870 (S->getFlags() & Scope::TemplateParamScope) != 0)
5871 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005872
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005873 // C++ [temp]p4:
5874 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005875 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005876 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005877 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005878 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005879
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005880 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005881 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005882
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005883 // C++ [temp]p2:
5884 // A template-declaration can appear only as a namespace scope or
5885 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005886 if (Ctx) {
5887 if (Ctx->isFileContext())
5888 return false;
5889 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5890 // C++ [temp.mem]p2:
5891 // A local class shall not have member templates.
5892 if (RD->isLocalClass())
5893 return Diag(TemplateParams->getTemplateLoc(),
5894 diag::err_template_inside_local_class)
5895 << TemplateParams->getSourceRange();
5896 else
5897 return false;
5898 }
5899 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005900
Mike Stump11289f42009-09-09 15:08:12 +00005901 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005902 diag::err_template_outside_namespace_or_class_scope)
5903 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005904}
Douglas Gregor67a65642009-02-17 23:15:12 +00005905
Douglas Gregor54888652009-10-07 00:13:32 +00005906/// \brief Determine what kind of template specialization the given declaration
5907/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005908static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005909 if (!D)
5910 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005911
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005912 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5913 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005914 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5915 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005916 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5917 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005918
Douglas Gregor54888652009-10-07 00:13:32 +00005919 return TSK_Undeclared;
5920}
5921
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005922/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005923/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005924///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005925/// This routine determines whether a template specialization can be declared
5926/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005927///
5928/// \param S the semantic analysis object for which this check is being
5929/// performed.
5930///
5931/// \param Specialized the entity being specialized or instantiated, which
5932/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005933/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005934/// member class).
5935///
5936/// \param PrevDecl the previous declaration of this entity, if any.
5937///
5938/// \param Loc the location of the explicit specialization or instantiation of
5939/// this entity.
5940///
5941/// \param IsPartialSpecialization whether this is a partial specialization of
5942/// a class template.
5943///
Douglas Gregor54888652009-10-07 00:13:32 +00005944/// \returns true if there was an error that we cannot recover from, false
5945/// otherwise.
5946static bool CheckTemplateSpecializationScope(Sema &S,
5947 NamedDecl *Specialized,
5948 NamedDecl *PrevDecl,
5949 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005950 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005951 // Keep these "kind" numbers in sync with the %select statements in the
5952 // various diagnostics emitted by this routine.
5953 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005954 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005955 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005956 else if (isa<VarTemplateDecl>(Specialized))
5957 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005958 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005959 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005960 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005961 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005962 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005963 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005964 else if (isa<RecordDecl>(Specialized))
5965 EntityKind = 7;
5966 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5967 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005968 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005969 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005970 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005971 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005972 return true;
5973 }
5974
Douglas Gregorf47b9112009-02-25 22:02:03 +00005975 // C++ [temp.expl.spec]p2:
5976 // An explicit specialization shall be declared in the namespace
5977 // of which the template is a member, or, for member templates, in
5978 // the namespace of which the enclosing class or enclosing class
5979 // template is a member. An explicit specialization of a member
5980 // function, member class or static data member of a class
5981 // template shall be declared in the namespace of which the class
5982 // template is a member. Such a declaration may also be a
5983 // definition. If the declaration is not a definition, the
5984 // specialization may be defined later in the name- space in which
5985 // the explicit specialization was declared, or in a namespace
5986 // that encloses the one in which the explicit specialization was
5987 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005988 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005989 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005990 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005991 return true;
5992 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005993
Douglas Gregor40fb7442009-10-07 17:30:37 +00005994 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005995 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005996 // Do not warn for class scope explicit specialization during
5997 // instantiation, warning was already emitted during pattern
5998 // semantic analysis.
5999 if (!S.ActiveTemplateInstantiations.size())
6000 S.Diag(Loc, diag::ext_function_specialization_in_class)
6001 << Specialized;
6002 } else {
6003 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6004 << Specialized;
6005 return true;
6006 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00006007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006008
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00006009 if (S.CurContext->isRecord() &&
6010 !S.CurContext->Equals(Specialized->getDeclContext())) {
6011 // Make sure that we're specializing in the right record context.
6012 // Otherwise, things can go horribly wrong.
6013 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6014 << Specialized;
6015 return true;
6016 }
6017
Douglas Gregore4b05162009-10-07 17:21:34 +00006018 // C++ [temp.class.spec]p6:
6019 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006020 // in any namespace scope in which its definition may be defined (14.5.1
6021 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00006022 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00006023 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00006024 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00006025
6026 // Make sure that this redeclaration (or definition) occurs in an enclosing
6027 // namespace.
6028 // Note that HandleDeclarator() performs this check for explicit
6029 // specializations of function templates, static data members, and member
6030 // functions, so we skip the check here for those kinds of entities.
6031 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6032 // Should we refactor that check, so that it occurs later?
6033 if (!DC->Encloses(SpecializedContext) &&
6034 !(isa<FunctionTemplateDecl>(Specialized) ||
6035 isa<FunctionDecl>(Specialized) ||
6036 isa<VarTemplateDecl>(Specialized) ||
6037 isa<VarDecl>(Specialized))) {
6038 if (isa<TranslationUnitDecl>(SpecializedContext))
6039 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6040 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00006041 else if (isa<NamespaceDecl>(SpecializedContext)) {
6042 int Diag = diag::err_template_spec_redecl_out_of_scope;
6043 if (S.getLangOpts().MicrosoftExt)
6044 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6045 S.Diag(Loc, Diag) << EntityKind << Specialized
6046 << cast<NamedDecl>(SpecializedContext);
6047 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00006048 llvm_unreachable("unexpected namespace context for specialization");
6049
6050 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6051 } else if ((!PrevDecl ||
6052 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6053 getTemplateSpecializationKind(PrevDecl) ==
6054 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006055 // C++ [temp.exp.spec]p2:
6056 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006057 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006058 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059 // An explicit specialization of a member function, member class or
6060 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006061 // namespace of which the class template is a member.
6062 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006063 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006064 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006065 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006066 // C++11 [temp.explicit]p3:
6067 // An explicit instantiation shall appear in an enclosing namespace of its
6068 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006069 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006070 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006071 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006072 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006073 "DC encloses TU but isn't in enclosing namespace set");
6074 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006075 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006076 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6077 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006078 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006079 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006080 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006081 Diag = diag::ext_template_spec_decl_out_of_scope;
6082 else
6083 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6084 S.Diag(Loc, Diag)
6085 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006088 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006089 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006091
Douglas Gregorf47b9112009-02-25 22:02:03 +00006092 return false;
6093}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006094
Richard Smith6056d5e2014-02-09 00:54:43 +00006095static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6096 if (!E->isInstantiationDependent())
6097 return SourceLocation();
6098 DependencyChecker Checker(Depth);
6099 Checker.TraverseStmt(E);
6100 if (Checker.Match && Checker.MatchLoc.isInvalid())
6101 return E->getSourceRange();
6102 return Checker.MatchLoc;
6103}
6104
6105static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6106 if (!TL.getType()->isDependentType())
6107 return SourceLocation();
6108 DependencyChecker Checker(Depth);
6109 Checker.TraverseTypeLoc(TL);
6110 if (Checker.Match && Checker.MatchLoc.isInvalid())
6111 return TL.getSourceRange();
6112 return Checker.MatchLoc;
6113}
6114
Larisse Voufo39a1e502013-08-06 01:03:05 +00006115/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006116/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006117static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006118 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6119 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006120 for (unsigned I = 0; I != NumArgs; ++I) {
6121 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006122 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006123 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6124 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006125 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006126
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006127 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129
Eli Friedmanb826a002012-09-26 02:36:12 +00006130 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006131 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006132
6133 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006134
Douglas Gregor98318c22011-01-03 21:37:45 +00006135 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006136 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6137 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006138
6139 // Strip off any implicit casts we added as part of type checking.
6140 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6141 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006142
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006143 // C++ [temp.class.spec]p8:
6144 // A non-type argument is non-specialized if it is the name of a
6145 // non-type parameter. All other non-type arguments are
6146 // specialized.
6147 //
6148 // Below, we check the two conditions that only apply to
6149 // specialized non-type arguments, so skip any non-specialized
6150 // arguments.
6151 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006152 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006153 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006154
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006155 // C++ [temp.class.spec]p9:
6156 // Within the argument list of a class template partial
6157 // specialization, the following restrictions apply:
6158 // -- A partially specialized non-type argument expression
6159 // shall not involve a template parameter of the partial
6160 // specialization except when the argument expression is a
6161 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006162 SourceRange ParamUseRange =
6163 findTemplateParameter(Param->getDepth(), ArgExpr);
6164 if (ParamUseRange.isValid()) {
6165 if (IsDefaultArgument) {
6166 S.Diag(TemplateNameLoc,
6167 diag::err_dependent_non_type_arg_in_partial_spec);
6168 S.Diag(ParamUseRange.getBegin(),
6169 diag::note_dependent_non_type_default_arg_in_partial_spec)
6170 << ParamUseRange;
6171 } else {
6172 S.Diag(ParamUseRange.getBegin(),
6173 diag::err_dependent_non_type_arg_in_partial_spec)
6174 << ParamUseRange;
6175 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006176 return true;
6177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006178
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006179 // -- The type of a template parameter corresponding to a
6180 // specialized non-type argument shall not be dependent on a
6181 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006182 //
6183 // FIXME: We need to delay this check until instantiation in some cases:
6184 //
6185 // template<template<typename> class X> struct A {
6186 // template<typename T, X<T> N> struct B;
6187 // template<typename T> struct B<T, 0>;
6188 // };
6189 // template<typename> using X = int;
6190 // A<X>::B<int, 0> b;
6191 ParamUseRange = findTemplateParameter(
6192 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6193 if (ParamUseRange.isValid()) {
6194 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6195 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6196 << Param->getType() << ParamUseRange;
6197 S.Diag(Param->getLocation(), diag::note_template_param_here)
6198 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006199 return true;
6200 }
6201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006202
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006203 return false;
6204}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006205
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006206/// \brief Check the non-type template arguments of a class template
6207/// partial specialization according to C++ [temp.class.spec]p9.
6208///
Richard Smith6056d5e2014-02-09 00:54:43 +00006209/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006210/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006211/// template.
6212/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006213/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006214/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006215///
Richard Smith6056d5e2014-02-09 00:54:43 +00006216/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006217static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006218 Sema &S, SourceLocation TemplateNameLoc,
6219 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006220 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006221 const TemplateArgument *ArgList = TemplateArgs.data();
6222
6223 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6224 NonTypeTemplateParmDecl *Param
6225 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6226 if (!Param)
6227 continue;
6228
Richard Smith6056d5e2014-02-09 00:54:43 +00006229 if (CheckNonTypeTemplatePartialSpecializationArgs(
6230 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006231 return true;
6232 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006233
6234 return false;
6235}
6236
John McCall48871652010-08-21 09:40:31 +00006237DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006238Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6239 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006240 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006241 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006242 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006243 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006244 MultiTemplateParamsArg
6245 TemplateParameterLists,
6246 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006247 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006248
Richard Smith4b55a9c2014-04-17 03:29:33 +00006249 CXXScopeSpec &SS = TemplateId.SS;
6250
Abramo Bagnara60804e12011-03-18 15:16:37 +00006251 // NOTE: KWLoc is the location of the tag keyword. This will instead
6252 // store the location of the outermost template keyword in the declaration.
6253 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006254 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6255 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6256 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6257 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006258
Douglas Gregor67a65642009-02-17 23:15:12 +00006259 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006260 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006261 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006262 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6263
6264 if (!ClassTemplate) {
6265 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006266 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006267 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6268 return true;
6269 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006270
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006271 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006272 bool isPartialSpecialization = false;
6273
Douglas Gregorf47b9112009-02-25 22:02:03 +00006274 // Check the validity of the template headers that introduce this
6275 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006276 // FIXME: We probably shouldn't complain about these headers for
6277 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006278 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006279 TemplateParameterList *TemplateParams =
6280 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006281 KWLoc, TemplateNameLoc, SS, &TemplateId,
6282 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6283 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006284 if (Invalid)
6285 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006286
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006287 if (TemplateParams && TemplateParams->size() > 0) {
6288 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006289
Douglas Gregorec9518b2010-12-21 08:14:57 +00006290 if (TUK == TUK_Friend) {
6291 Diag(KWLoc, diag::err_partial_specialization_friend)
6292 << SourceRange(LAngleLoc, RAngleLoc);
6293 return true;
6294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006295
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006296 // C++ [temp.class.spec]p10:
6297 // The template parameter list of a specialization shall not
6298 // contain default template argument values.
6299 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6300 Decl *Param = TemplateParams->getParam(I);
6301 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6302 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006303 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006304 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006305 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006306 }
6307 } else if (NonTypeTemplateParmDecl *NTTP
6308 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6309 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006310 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006311 diag::err_default_arg_in_partial_spec)
6312 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006313 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006314 }
6315 } else {
6316 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006317 if (TTP->hasDefaultArgument()) {
6318 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006319 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006320 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006321 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006322 }
6323 }
6324 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006325 } else if (TemplateParams) {
6326 if (TUK == TUK_Friend)
6327 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006328 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006329 SourceRange(TemplateParams->getTemplateLoc(),
6330 TemplateParams->getRAngleLoc()))
6331 << SourceRange(LAngleLoc, RAngleLoc);
6332 else
6333 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006334 } else {
6335 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006336 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006337
Douglas Gregor67a65642009-02-17 23:15:12 +00006338 // Check that the specialization uses the same tag kind as the
6339 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006340 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6341 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006342 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006343 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006344 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006345 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006346 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006347 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006348 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006349 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006350 diag::note_previous_use);
6351 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6352 }
6353
Douglas Gregorc40290e2009-03-09 23:48:35 +00006354 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006355 TemplateArgumentListInfo TemplateArgs =
6356 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006357
Douglas Gregor14406932011-01-03 20:35:03 +00006358 // Check for unexpanded parameter packs in any of the template arguments.
6359 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006360 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006361 UPPC_PartialSpecialization))
6362 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006363
Douglas Gregor67a65642009-02-17 23:15:12 +00006364 // Check that the template argument list is well-formed for this
6365 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006366 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006367 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6368 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006369 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006370
Douglas Gregor2373c592009-05-31 09:31:02 +00006371 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006372 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006373 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006374 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006375 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6376 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006377 return true;
6378
Douglas Gregor678d76c2011-07-01 01:22:09 +00006379 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006381 !TemplateSpecializationType::anyDependentTemplateArguments(
David Majnemer6fbeee32016-07-07 04:43:07 +00006382 TemplateArgs.arguments(), InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006383 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6384 << ClassTemplate->getDeclName();
6385 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006386 }
6387 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006388
Craig Topperc3ec1492014-05-26 06:22:03 +00006389 void *InsertPos = nullptr;
6390 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006391
6392 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006393 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006394 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006395 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006396 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006397
Craig Topperc3ec1492014-05-26 06:22:03 +00006398 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006399
Douglas Gregorf47b9112009-02-25 22:02:03 +00006400 // Check whether we can declare a class template specialization in
6401 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006402 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006403 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6404 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006405 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006406 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006407
Douglas Gregor15301382009-07-30 17:40:51 +00006408 // The canonical type
6409 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006410 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006411 // Build the canonical type that describes the converted template
6412 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006413 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6414 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00006415 Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006416
6417 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006418 ClassTemplate->getInjectedClassNameSpecialization())) {
6419 // C++ [temp.class.spec]p9b3:
6420 //
6421 // -- The argument list of the specialization shall not be identical
6422 // to the implicit argument list of the primary template.
6423 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006424 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006425 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006426 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6427 ClassTemplate->getIdentifier(),
6428 TemplateNameLoc,
6429 Attr,
6430 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006431 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006432 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006433 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006434 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006435 }
Douglas Gregor15301382009-07-30 17:40:51 +00006436
Douglas Gregor2373c592009-05-31 09:31:02 +00006437 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006438 ClassTemplatePartialSpecializationDecl *PrevPartial
6439 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006440 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006441 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006442 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006443 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006444 TemplateParams,
6445 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006446 Converted,
John McCall6b51f282009-11-23 01:53:49 +00006447 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006448 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006449 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006450 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006451 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006452 Partial->setTemplateParameterListsInfo(
6453 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006454 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006455
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006456 if (!PrevPartial)
6457 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006458 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006459
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006460 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006461 // template specialization, make a note of that.
6462 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6463 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006464
Douglas Gregor91772d12009-06-13 00:26:55 +00006465 // Check that all of the template parameters of the class template
6466 // partial specialization are deducible from the template
6467 // arguments. If not, this class template partial specialization
6468 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006469 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006470 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006471 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006472 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006473
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006474 if (!DeducibleParams.all()) {
6475 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006476 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006477 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006478 << SourceRange(TemplateNameLoc, RAngleLoc);
6479 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6480 if (!DeducibleParams[I]) {
6481 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6482 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006483 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006484 diag::note_partial_spec_unused_parameter)
6485 << Param->getDeclName();
6486 else
Mike Stump11289f42009-09-09 15:08:12 +00006487 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006488 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006489 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006490 }
6491 }
6492 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006493 } else {
6494 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006495 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006496 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006497 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006498 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006499 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006500 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00006501 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00006502 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006503 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006504 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006505 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006506 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006507 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006508
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006509 if (!PrevDecl)
6510 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006511
David Majnemer678f50b2015-11-18 19:49:19 +00006512 if (CurContext->isDependentContext()) {
6513 // -fms-extensions permits specialization of nested classes without
6514 // fully specializing the outer class(es).
6515 assert(getLangOpts().MicrosoftExt &&
6516 "Only possible with -fms-extensions!");
6517 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6518 CanonType = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00006519 CanonTemplate, Converted);
David Majnemer678f50b2015-11-18 19:49:19 +00006520 } else {
6521 CanonType = Context.getTypeDeclType(Specialization);
6522 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006523 }
6524
Douglas Gregor06db9f52009-10-12 20:18:28 +00006525 // C++ [temp.expl.spec]p6:
6526 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006528 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006529 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006530 // use occurs; no diagnostic is required.
6531 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006532 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006533 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006534 // Is there any previous explicit specialization declaration?
6535 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6536 Okay = true;
6537 break;
6538 }
6539 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006540
Douglas Gregorc854c662010-02-26 06:03:23 +00006541 if (!Okay) {
6542 SourceRange Range(TemplateNameLoc, RAngleLoc);
6543 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6544 << Context.getTypeDeclType(Specialization) << Range;
6545
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006546 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006547 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006548 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006549 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006550 return true;
6551 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006553
Douglas Gregor2208a292009-09-26 20:57:03 +00006554 // If this is not a friend, note that this is an explicit specialization.
6555 if (TUK != TUK_Friend)
6556 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006557
6558 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006559 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006560 RecordDecl *Def = Specialization->getDefinition();
6561 NamedDecl *Hidden = nullptr;
6562 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6563 SkipBody->ShouldSkip = true;
6564 makeMergedDefinitionVisible(Hidden, KWLoc);
6565 // From here on out, treat this as just a redeclaration.
6566 TUK = TUK_Declaration;
6567 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006568 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006569 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006570 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006571 Diag(Def->getLocation(), diag::note_previous_definition);
6572 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006573 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006574 }
6575 }
6576
John McCall659a3372010-12-18 03:30:47 +00006577 if (Attr)
6578 ProcessDeclAttributeList(S, Specialization, Attr);
6579
Richard Smith034b94a2012-08-17 03:20:55 +00006580 // Add alignment attributes if necessary; these attributes are checked when
6581 // the ASTContext lays out the structure.
6582 if (TUK == TUK_Definition) {
6583 AddAlignmentAttributesForRecord(Specialization);
6584 AddMsStructLayoutForRecord(Specialization);
6585 }
6586
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006587 if (ModulePrivateLoc.isValid())
6588 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6589 << (isPartialSpecialization? 1 : 0)
6590 << FixItHint::CreateRemoval(ModulePrivateLoc);
6591
Douglas Gregord56a91e2009-02-26 22:19:44 +00006592 // Build the fully-sugared type for this class template
6593 // specialization as the user wrote in the specialization
6594 // itself. This means that we'll pretty-print the type retrieved
6595 // from the specialization's declaration the way that the user
6596 // actually wrote the specialization, rather than formatting the
6597 // name based on the "canonical" representation used to store the
6598 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006599 TypeSourceInfo *WrittenTy
6600 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6601 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006602 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006603 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006604 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006605 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006606
Douglas Gregor1e249f82009-02-25 22:18:32 +00006607 // C++ [temp.expl.spec]p9:
6608 // A template explicit specialization is in the scope of the
6609 // namespace in which the template was defined.
6610 //
6611 // We actually implement this paragraph where we set the semantic
6612 // context (in the creation of the ClassTemplateSpecializationDecl),
6613 // but we also maintain the lexical context where the actual
6614 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006615 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006616
Douglas Gregor67a65642009-02-17 23:15:12 +00006617 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006618 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006619 Specialization->startDefinition();
6620
Douglas Gregor2208a292009-09-26 20:57:03 +00006621 if (TUK == TUK_Friend) {
6622 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6623 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006624 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006625 /*FIXME:*/KWLoc);
6626 Friend->setAccess(AS_public);
6627 CurContext->addDecl(Friend);
6628 } else {
6629 // Add the specialization into its lexical context, so that it can
6630 // be seen when iterating through the list of declarations in that
6631 // context. However, specializations are not found by name lookup.
6632 CurContext->addDecl(Specialization);
6633 }
John McCall48871652010-08-21 09:40:31 +00006634 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006635}
Douglas Gregor333489b2009-03-27 23:10:48 +00006636
John McCall48871652010-08-21 09:40:31 +00006637Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006638 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006639 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006640 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006641 ActOnDocumentableDecl(NewDecl);
6642 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006643}
6644
John McCall4f7ced62010-02-11 01:33:53 +00006645/// \brief Strips various properties off an implicit instantiation
6646/// that has just been explicitly specialized.
6647static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006648 D->dropAttr<DLLImportAttr>();
6649 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006650
Nico Webere4974382014-12-19 23:52:45 +00006651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006652 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006653}
6654
Nico Webera8f80b32012-01-09 19:52:25 +00006655/// \brief Compute the diagnostic location for an explicit instantiation
6656// declaration or definition.
6657static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006658 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006659 // Explicit instantiations following a specialization have no effect and
6660 // hence no PointOfInstantiation. In that case, walk decl backwards
6661 // until a valid name loc is found.
6662 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006663 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6664 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006665 PrevDiagLoc = Prev->getLocation();
6666 }
6667 assert(PrevDiagLoc.isValid() &&
6668 "Explicit instantiation without point of instantiation?");
6669 return PrevDiagLoc;
6670}
6671
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006672/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006673/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006674/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006675/// new specialization/instantiation will have any effect.
6676///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006678/// instantiation.
6679///
6680/// \param NewTSK the kind of the new explicit specialization or instantiation.
6681///
6682/// \param PrevDecl the previous declaration of the entity.
6683///
6684/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6685///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006686/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006687/// declaration was instantiated (either implicitly or explicitly).
6688///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006689/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006690/// specialization or instantiation has no effect and should be ignored.
6691///
6692/// \returns true if there was an error that should prevent the introduction of
6693/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006694bool
6695Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6696 TemplateSpecializationKind NewTSK,
6697 NamedDecl *PrevDecl,
6698 TemplateSpecializationKind PrevTSK,
6699 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006700 bool &HasNoEffect) {
6701 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006703 switch (NewTSK) {
6704 case TSK_Undeclared:
6705 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006706 assert(
6707 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6708 "previous declaration must be implicit!");
6709 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006710
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006711 case TSK_ExplicitSpecialization:
6712 switch (PrevTSK) {
6713 case TSK_Undeclared:
6714 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006716 // explicitly specialized or has merely been mentioned without any
6717 // instantiation.
6718 return false;
6719
6720 case TSK_ImplicitInstantiation:
6721 if (PrevPointOfInstantiation.isInvalid()) {
6722 // The declaration itself has not actually been instantiated, so it is
6723 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006724 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006725 return false;
6726 }
6727 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006728
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006729 case TSK_ExplicitInstantiationDeclaration:
6730 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006731 assert((PrevTSK == TSK_ImplicitInstantiation ||
6732 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006733 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006734
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006735 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006736 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006737 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006738 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006739 // implicit instantiation to take place, in every translation unit in
6740 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006741 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006742 // Is there any previous explicit specialization declaration?
6743 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6744 return false;
6745 }
6746
Douglas Gregor1d957a32009-10-27 18:42:08 +00006747 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006748 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006749 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006750 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006751
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006752 return true;
6753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006754
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006755 case TSK_ExplicitInstantiationDeclaration:
6756 switch (PrevTSK) {
6757 case TSK_ExplicitInstantiationDeclaration:
6758 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006759 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006760 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006762 case TSK_Undeclared:
6763 case TSK_ImplicitInstantiation:
6764 // We're explicitly instantiating something that may have already been
6765 // implicitly instantiated; that's fine.
6766 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006768 case TSK_ExplicitSpecialization:
6769 // C++0x [temp.explicit]p4:
6770 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006771 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006772 // specialization for that template, the explicit instantiation has no
6773 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006774 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006775 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006776
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006777 case TSK_ExplicitInstantiationDefinition:
6778 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779 // If an entity is the subject of both an explicit instantiation
6780 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006781 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006782 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006783 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006784
6785 // Explicit instantiations following a specialization have no effect and
6786 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6787 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006788 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6789 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006790 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006791 return false;
6792 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006794 case TSK_ExplicitInstantiationDefinition:
6795 switch (PrevTSK) {
6796 case TSK_Undeclared:
6797 case TSK_ImplicitInstantiation:
6798 // We're explicitly instantiating something that may have already been
6799 // implicitly instantiated; that's fine.
6800 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006802 case TSK_ExplicitSpecialization:
6803 // C++ DR 259, C++0x [temp.explicit]p4:
6804 // For a given set of template parameters, if an explicit
6805 // instantiation of a template appears after a declaration of
6806 // an explicit specialization for that template, the explicit
6807 // instantiation has no effect.
6808 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006809 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006810 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006811 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006812 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006813 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6814 diag::ext_explicit_instantiation_after_specialization)
6815 << PrevDecl;
6816 Diag(PrevDecl->getLocation(),
6817 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006818 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006819 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006821 case TSK_ExplicitInstantiationDeclaration:
6822 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006824
6825 // C++0x [temp.explicit]p4:
6826 // For a given set of template parameters, if an explicit instantiation
6827 // of a template appears after a declaration of an explicit
6828 // specialization for that template, the explicit instantiation has no
6829 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006830 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006831 // Is there any previous explicit specialization declaration?
6832 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6833 HasNoEffect = true;
6834 break;
6835 }
6836 }
6837
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006838 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006840 case TSK_ExplicitInstantiationDefinition:
6841 // C++0x [temp.spec]p5:
6842 // For a given template and a given set of template-arguments,
6843 // - an explicit instantiation definition shall appear at most once
6844 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006845
6846 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6847 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006848 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006849 : diag::err_explicit_instantiation_duplicate)
6850 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006851 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006852 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006853 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006855 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006856 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006857
David Blaikie83d382b2011-09-23 05:06:16 +00006858 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006859}
6860
John McCallb9c78482010-04-08 09:05:18 +00006861/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006862/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006863///
James Dennettf14a6e52012-06-15 22:23:43 +00006864/// The only possible way to get a dependent function template specialization
6865/// is with a friend declaration, like so:
6866///
6867/// \code
6868/// template \<class T> void foo(T);
6869/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006870/// friend void foo<>(T);
6871/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006872/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006873///
6874/// There really isn't any useful analysis we can do here, so we
6875/// just store the information.
6876bool
6877Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6878 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6879 LookupResult &Previous) {
6880 // Remove anything from Previous that isn't a function template in
6881 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006882 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006883 LookupResult::Filter F = Previous.makeFilter();
6884 while (F.hasNext()) {
6885 NamedDecl *D = F.next()->getUnderlyingDecl();
6886 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006887 !FDLookupContext->InEnclosingNamespaceSetOf(
6888 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006889 F.erase();
6890 }
6891 F.done();
6892
6893 // Should this be diagnosed here?
6894 if (Previous.empty()) return true;
6895
6896 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6897 ExplicitTemplateArgs);
6898 return false;
6899}
6900
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006901/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006902/// specialization.
6903///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006904/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006905/// explicit function template specialization. On successful completion,
6906/// the function declaration \p FD will become a function template
6907/// specialization.
6908///
6909/// \param FD the function declaration, which will be updated to become a
6910/// function template specialization.
6911///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006912/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6913/// if any. Note that this may be valid info even when 0 arguments are
6914/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6915/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006916///
Francois Pichet3a44e432011-07-08 06:21:47 +00006917/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006918/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006919bool Sema::CheckFunctionTemplateSpecialization(
6920 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6921 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006922 // The set of function template specializations that could match this
6923 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006924 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006925 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6926 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006927
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006928 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6929 ConvertedTemplateArgs;
6930
Sebastian Redl50c68252010-08-31 00:36:30 +00006931 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006932 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6933 I != E; ++I) {
6934 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6935 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006937 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006938 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6939 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006940 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006941
Richard Smith574f4f62013-01-14 05:37:29 +00006942 // When matching a constexpr member function template specialization
6943 // against the primary template, we don't yet know whether the
6944 // specialization has an implicit 'const' (because we don't know whether
6945 // it will be a static member function until we know which template it
6946 // specializes), so adjust it now assuming it specializes this template.
6947 QualType FT = FD->getType();
6948 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006949 CXXMethodDecl *OldMD =
6950 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006951 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006952 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006953 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6954 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006955 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006956 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006957 }
6958 }
6959
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006960 TemplateArgumentListInfo Args;
6961 if (ExplicitTemplateArgs)
6962 Args = *ExplicitTemplateArgs;
6963
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006964 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965 // A trailing template-argument can be left unspecified in the
6966 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006967 // provided it can be deduced from the function argument type.
6968 // Perform template argument deduction to determine whether we may be
6969 // specializing this template.
6970 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006971 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006972 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006973 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6974 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00006975 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
6976 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006977 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006978 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00006979 FailedCandidates.addCandidate().set(
6980 I.getPair(), FunTmpl->getTemplatedDecl(),
6981 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006982 (void)TDK;
6983 continue;
6984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006985
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006986 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006987 if (ExplicitTemplateArgs)
6988 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006989 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006990 }
6991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006992
Douglas Gregor5de279c2009-09-26 03:41:46 +00006993 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006994 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006995 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006996 FD->getLocation(),
6997 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6998 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006999 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007000 PDiag(diag::note_function_template_spec_matched));
7001
John McCall58cc69d2010-01-27 01:50:18 +00007002 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007003 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007004
7005 // Ignore access information; it doesn't figure into redeclaration checking.
7006 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007007
Nathan Wilson83839122016-04-09 02:55:27 +00007008 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7009 // an explicit specialization (14.8.3) [...] of a concept definition.
7010 if (Specialization->getPrimaryTemplate()->isConcept()) {
7011 Diag(FD->getLocation(), diag::err_concept_specialized)
7012 << 0 /*function*/ << 1 /*explicitly specialized*/;
7013 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7014 return true;
7015 }
7016
Abramo Bagnarab9893d62011-03-04 17:20:30 +00007017 FunctionTemplateSpecializationInfo *SpecInfo
7018 = Specialization->getTemplateSpecializationInfo();
7019 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00007020
7021 // Note: do not overwrite location info if previous template
7022 // specialization kind was explicit.
7023 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00007024 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00007025 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00007026 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7027 // function can differ from the template declaration with respect to
7028 // the constexpr specifier.
7029 Specialization->setConstexpr(FD->isConstexpr());
7030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007031
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007032 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00007033 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00007034
7035 // If this is a friend declaration, then we're not really declaring
7036 // an explicit specialization.
7037 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007038
Douglas Gregor54888652009-10-07 00:13:32 +00007039 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00007040 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007041 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00007042 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007044 false))
Douglas Gregor54888652009-10-07 00:13:32 +00007045 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007046
7047 // C++ [temp.expl.spec]p6:
7048 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007049 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007050 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007051 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007052 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007053 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007054 if (!isFriend &&
7055 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007056 TSK_ExplicitSpecialization,
7057 Specialization,
7058 SpecInfo->getTemplateSpecializationKind(),
7059 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007060 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007061 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007062
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007063 // Mark the prior declaration as an explicit specialization, so that later
7064 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007065 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007066 // Since explicit specializations do not inherit '=delete' from their
7067 // primary function template - check if the 'specialization' that was
7068 // implicitly generated (during template argument deduction for partial
7069 // ordering) from the most specialized of all the function templates that
7070 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7071 // first check that it was implicitly generated during template argument
7072 // deduction by making sure it wasn't referenced, and then reset the deleted
7073 // flag to not-deleted, so that we can inherit that information from 'FD'.
7074 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7075 !Specialization->getCanonicalDecl()->isReferenced()) {
7076 assert(
7077 Specialization->getCanonicalDecl() == Specialization &&
7078 "This must be the only existing declaration of this specialization");
7079 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007080 }
John McCall816d75b2010-03-24 07:46:06 +00007081 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007082 MarkUnusedFileScopedDecl(Specialization);
7083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007084
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007085 // Turn the given function declaration into a function template
7086 // specialization, with the template arguments from the previous
7087 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007088 // Take copies of (semantic and syntactic) template argument lists.
7089 const TemplateArgumentList* TemplArgs = new (Context)
7090 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007091 FD->setFunctionTemplateSpecialization(
7092 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7093 SpecInfo->getTemplateSpecializationKind(),
7094 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007095
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007096 // The "previous declaration" for this function template specialization is
7097 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007098 Previous.clear();
7099 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007100 return false;
7101}
7102
Douglas Gregor86d142a2009-10-08 07:24:58 +00007103/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007104/// specialization.
7105///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007106/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007107/// explicit member function specialization. On successful completion,
7108/// the function declaration \p FD will become a member function
7109/// specialization.
7110///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007111/// \param Member the member declaration, which will be updated to become a
7112/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007113///
John McCall1f82f242009-11-18 22:49:29 +00007114/// \param Previous the set of declarations, one of which may be specialized
7115/// by this function specialization; the set will be modified to contain the
7116/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117bool
John McCall1f82f242009-11-18 22:49:29 +00007118Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007119 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007120
Douglas Gregor86d142a2009-10-08 07:24:58 +00007121 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007122 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007123 NamedDecl *Instantiation = nullptr;
7124 NamedDecl *InstantiatedFrom = nullptr;
7125 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007126
John McCall1f82f242009-11-18 22:49:29 +00007127 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007128 // Nowhere to look anyway.
7129 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007130 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7131 I != E; ++I) {
7132 NamedDecl *D = (*I)->getUnderlyingDecl();
7133 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007134 QualType Adjusted = Function->getType();
7135 if (!hasExplicitCallingConv(Adjusted))
7136 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7137 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007138 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007139 Instantiation = Method;
7140 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007141 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007142 break;
7143 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007144 }
7145 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007146 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007147 VarDecl *PrevVar;
7148 if (Previous.isSingleResult() &&
7149 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007150 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007151 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007152 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007153 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007154 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007155 }
7156 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007157 CXXRecordDecl *PrevRecord;
7158 if (Previous.isSingleResult() &&
7159 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007160 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007161 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007162 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007163 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007164 }
Richard Smith7d137e32012-03-23 03:33:32 +00007165 } else if (isa<EnumDecl>(Member)) {
7166 EnumDecl *PrevEnum;
7167 if (Previous.isSingleResult() &&
7168 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007169 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007170 Instantiation = PrevEnum;
7171 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7172 MSInfo = PrevEnum->getMemberSpecializationInfo();
7173 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007175
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007176 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007177 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007178 // specializations are always out-of-line, the caller will complain about
7179 // this mismatch later.
7180 return false;
7181 }
John McCalle820e5e2010-04-13 20:37:33 +00007182
7183 // If this is a friend, just bail out here before we start turning
7184 // things into explicit specializations.
7185 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7186 // Preserve instantiation information.
7187 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7188 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7189 cast<CXXMethodDecl>(InstantiatedFrom),
7190 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7191 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7192 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7193 cast<CXXRecordDecl>(InstantiatedFrom),
7194 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7195 }
7196
7197 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007198 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007199 return false;
7200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007201
Douglas Gregor86d142a2009-10-08 07:24:58 +00007202 // Make sure that this is a specialization of a member.
7203 if (!InstantiatedFrom) {
7204 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7205 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007206 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7207 return true;
7208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007209
Douglas Gregor06db9f52009-10-12 20:18:28 +00007210 // C++ [temp.expl.spec]p6:
7211 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007212 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007213 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007214 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007215 // use occurs; no diagnostic is required.
7216 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007217
Abramo Bagnara8075c852010-06-12 07:44:57 +00007218 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007219 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7220 TSK_ExplicitSpecialization,
7221 Instantiation,
7222 MSInfo->getTemplateSpecializationKind(),
7223 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007224 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007225 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007226
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007227 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007228 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007229 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007230 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007231 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007232 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007233
Douglas Gregor86d142a2009-10-08 07:24:58 +00007234 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007235 // the original declaration to note that it is an explicit specialization
7236 // (if it was previously an implicit instantiation). This latter step
7237 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007238 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007239 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7240 if (InstantiationFunction->getTemplateSpecializationKind() ==
7241 TSK_ImplicitInstantiation) {
7242 InstantiationFunction->setTemplateSpecializationKind(
7243 TSK_ExplicitSpecialization);
7244 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007245 // Explicit specializations of member functions of class templates do not
7246 // inherit '=delete' from the member function they are specializing.
7247 if (InstantiationFunction->isDeleted()) {
7248 assert(InstantiationFunction->getCanonicalDecl() ==
7249 InstantiationFunction);
7250 InstantiationFunction->setDeletedAsWritten(false);
7251 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007253
Douglas Gregor86d142a2009-10-08 07:24:58 +00007254 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7255 cast<CXXMethodDecl>(InstantiatedFrom),
7256 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007257 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007258 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007259 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7260 if (InstantiationVar->getTemplateSpecializationKind() ==
7261 TSK_ImplicitInstantiation) {
7262 InstantiationVar->setTemplateSpecializationKind(
7263 TSK_ExplicitSpecialization);
7264 InstantiationVar->setLocation(Member->getLocation());
7265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007266
Larisse Voufo39a1e502013-08-06 01:03:05 +00007267 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7268 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007269 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007270 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007271 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7272 if (InstantiationClass->getTemplateSpecializationKind() ==
7273 TSK_ImplicitInstantiation) {
7274 InstantiationClass->setTemplateSpecializationKind(
7275 TSK_ExplicitSpecialization);
7276 InstantiationClass->setLocation(Member->getLocation());
7277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278
Douglas Gregor86d142a2009-10-08 07:24:58 +00007279 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007280 cast<CXXRecordDecl>(InstantiatedFrom),
7281 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007282 } else {
7283 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7284 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7285 if (InstantiationEnum->getTemplateSpecializationKind() ==
7286 TSK_ImplicitInstantiation) {
7287 InstantiationEnum->setTemplateSpecializationKind(
7288 TSK_ExplicitSpecialization);
7289 InstantiationEnum->setLocation(Member->getLocation());
7290 }
7291
7292 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7293 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007295
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007296 // Save the caller the trouble of having to figure out which declaration
7297 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007298 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007299 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007300 return false;
7301}
7302
Douglas Gregore47f5a72009-10-14 23:41:34 +00007303/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007304///
7305/// \returns true if a serious error occurs, false otherwise.
7306static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007307 SourceLocation InstLoc,
7308 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007309 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7310 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007311
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007312 if (CurContext->isRecord()) {
7313 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7314 << D;
7315 return true;
7316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007317
Richard Smith050d2612011-10-18 02:28:33 +00007318 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007319 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007320 // template. If the name declared in the explicit instantiation is an
7321 // unqualified name, the explicit instantiation shall appear in the
7322 // namespace where its template is declared or, if that namespace is inline
7323 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007324 //
7325 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007326 if (WasQualifiedName) {
7327 if (CurContext->Encloses(OrigContext))
7328 return false;
7329 } else {
7330 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7331 return false;
7332 }
7333
7334 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7335 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007336 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007337 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007338 diag::err_explicit_instantiation_out_of_scope :
7339 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007340 << D << NS;
7341 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007342 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007343 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007344 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7345 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7346 << D << NS;
7347 } else
7348 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007349 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007350 diag::err_explicit_instantiation_must_be_global :
7351 diag::warn_explicit_instantiation_must_be_global_0x)
7352 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007353 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007354 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007355}
7356
7357/// \brief Determine whether the given scope specifier has a template-id in it.
7358static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7359 if (!SS.isSet())
7360 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007361
Richard Smith050d2612011-10-18 02:28:33 +00007362 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007363 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007364 // or a static data member of a class template specialization, the name of
7365 // the class template specialization in the qualified-id for the member
7366 // name shall be a simple-template-id.
7367 //
7368 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007369 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7370 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007371 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007372 if (isa<TemplateSpecializationType>(T))
7373 return true;
7374
7375 return false;
7376}
7377
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007378// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007379DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007380Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007381 SourceLocation ExternLoc,
7382 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007383 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007384 SourceLocation KWLoc,
7385 const CXXScopeSpec &SS,
7386 TemplateTy TemplateD,
7387 SourceLocation TemplateNameLoc,
7388 SourceLocation LAngleLoc,
7389 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007390 SourceLocation RAngleLoc,
7391 AttributeList *Attr) {
7392 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007393 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007394 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007395 // Check that the specialization uses the same tag kind as the
7396 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007397 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7398 assert(Kind != TTK_Enum &&
7399 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007400
Richard Trieu265c3442016-04-05 21:13:54 +00007401 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7402
7403 if (!ClassTemplate) {
7404 unsigned ErrorKind = 0;
7405 if (isa<TypeAliasTemplateDecl>(TD)) {
7406 ErrorKind = 4;
7407 } else if (isa<TemplateTemplateParmDecl>(TD)) {
7408 ErrorKind = 5;
7409 }
7410
7411 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7412 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007413 return true;
7414 }
7415
Douglas Gregord9034f02009-05-14 16:41:31 +00007416 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007417 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007418 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007419 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007420 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007421 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007422 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007423 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007424 diag::note_previous_use);
7425 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7426 }
7427
Douglas Gregore47f5a72009-10-14 23:41:34 +00007428 // C++0x [temp.explicit]p2:
7429 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007430 // definition and an explicit instantiation declaration. An explicit
7431 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007432 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7433 ? TSK_ExplicitInstantiationDefinition
7434 : TSK_ExplicitInstantiationDeclaration;
7435
7436 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7437 // Check for dllexport class template instantiation declarations.
7438 for (AttributeList *A = Attr; A; A = A->getNext()) {
7439 if (A->getKind() == AttributeList::AT_DLLExport) {
7440 Diag(ExternLoc,
7441 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7442 Diag(A->getLoc(), diag::note_attribute);
7443 break;
7444 }
7445 }
7446
7447 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7448 Diag(ExternLoc,
7449 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7450 Diag(A->getLocation(), diag::note_attribute);
7451 }
7452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Hans Wennborga86a83b2016-05-26 19:42:56 +00007454 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7455 // instantiation declarations for most purposes.
7456 bool DLLImportExplicitInstantiationDef = false;
7457 if (TSK == TSK_ExplicitInstantiationDefinition &&
7458 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7459 // Check for dllimport class template instantiation definitions.
7460 bool DLLImport =
7461 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7462 for (AttributeList *A = Attr; A; A = A->getNext()) {
7463 if (A->getKind() == AttributeList::AT_DLLImport)
7464 DLLImport = true;
7465 if (A->getKind() == AttributeList::AT_DLLExport) {
7466 // dllexport trumps dllimport here.
7467 DLLImport = false;
7468 break;
7469 }
7470 }
7471 if (DLLImport) {
7472 TSK = TSK_ExplicitInstantiationDeclaration;
7473 DLLImportExplicitInstantiationDef = true;
7474 }
7475 }
7476
Douglas Gregora1f49972009-05-13 00:25:59 +00007477 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007478 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007479 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007480
7481 // Check that the template argument list is well-formed for this
7482 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007483 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007484 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7485 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007486 return true;
7487
Douglas Gregora1f49972009-05-13 00:25:59 +00007488 // Find the class template specialization declaration that
7489 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007490 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007491 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007492 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007493
Abramo Bagnara8075c852010-06-12 07:44:57 +00007494 TemplateSpecializationKind PrevDecl_TSK
7495 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7496
Douglas Gregor54888652009-10-07 00:13:32 +00007497 // C++0x [temp.explicit]p2:
7498 // [...] An explicit instantiation shall appear in an enclosing
7499 // namespace of its template. [...]
7500 //
7501 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007502 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7503 SS.isSet()))
7504 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007505
Craig Topperc3ec1492014-05-26 06:22:03 +00007506 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007507
Abramo Bagnara8075c852010-06-12 07:44:57 +00007508 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007509 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007510 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007511 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007512 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007513 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007514 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007515
Abramo Bagnara8075c852010-06-12 07:44:57 +00007516 // Even though HasNoEffect == true means that this explicit instantiation
7517 // has no effect on semantics, we go on to put its syntax in the AST.
7518
7519 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7520 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007521 // Since the only prior class template specialization with these
7522 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007523 // declaration node as our own, updating the source location
7524 // for the template name to reflect our new declaration.
7525 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007526 Specialization = PrevDecl;
7527 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007528 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007529 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007530
7531 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7532 DLLImportExplicitInstantiationDef) {
7533 // The new specialization might add a dllimport attribute.
7534 HasNoEffect = false;
7535 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007536 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007537
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007538 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007539 // Create a new class template specialization declaration node for
7540 // this explicit specialization.
7541 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007542 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007543 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007544 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007545 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00007546 Converted,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007547 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007548 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007549
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007550 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007551 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007552 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007553 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007554 }
7555
7556 // Build the fully-sugared type for this explicit instantiation as
7557 // the user wrote in the explicit instantiation itself. This means
7558 // that we'll pretty-print the type retrieved from the
7559 // specialization's declaration the way that the user actually wrote
7560 // the explicit instantiation, rather than formatting the name based
7561 // on the "canonical" representation used to store the template
7562 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007563 TypeSourceInfo *WrittenTy
7564 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7565 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007566 Context.getTypeDeclType(Specialization));
7567 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007568
Abramo Bagnara8075c852010-06-12 07:44:57 +00007569 // Set source locations for keywords.
7570 Specialization->setExternLoc(ExternLoc);
7571 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00007572 Specialization->setBraceRange(SourceRange());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007573
Rafael Espindola0b062072012-01-03 06:04:21 +00007574 if (Attr)
7575 ProcessDeclAttributeList(S, Specialization, Attr);
7576
Abramo Bagnara8075c852010-06-12 07:44:57 +00007577 // Add the explicit instantiation into its lexical context. However,
7578 // since explicit instantiations are never found by name lookup, we
7579 // just put it into the declaration context directly.
7580 Specialization->setLexicalDeclContext(CurContext);
7581 CurContext->addDecl(Specialization);
7582
7583 // Syntax is now OK, so return if it has no other effect on semantics.
7584 if (HasNoEffect) {
7585 // Set the template specialization kind.
7586 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007587 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007588 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007589
7590 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007591 // A definition of a class template or class member template
7592 // shall be in scope at the point of the explicit instantiation of
7593 // the class template or class member template.
7594 //
7595 // This check comes when we actually try to perform the
7596 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007597 ClassTemplateSpecializationDecl *Def
7598 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007599 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007600 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007601 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007602 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007603 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007604 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7605 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007606
Douglas Gregor1d957a32009-10-27 18:42:08 +00007607 // Instantiate the members of this class template specialization.
7608 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007609 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007610 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007611 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007612 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7613 // TSK_ExplicitInstantiationDefinition
7614 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007615 (TSK == TSK_ExplicitInstantiationDefinition ||
7616 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007617 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007618 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007619
Hans Wennborgc0875502015-06-09 00:39:05 +00007620 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7621 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7622 // In the MS ABI, an explicit instantiation definition can add a dll
7623 // attribute to a template with a previous instantiation declaration.
7624 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007625 auto *A = cast<InheritableAttr>(
7626 getDLLAttr(Specialization)->clone(getASTContext()));
7627 A->setInherited(true);
7628 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007629
7630 // We reject explicit instantiations in class scope, so there should
7631 // never be any delayed exported classes to worry about.
7632 assert(DelayedDllExportClasses.empty() &&
7633 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007634 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007635 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007636
7637 // Propagate attribute to base class templates.
7638 for (auto &B : Def->bases()) {
7639 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7640 B.getType()->getAsCXXRecordDecl()))
7641 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7642 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007643 }
7644 }
7645
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007646 // Set the template specialization kind. Make sure it is set before
7647 // instantiating the members which will trigger ASTConsumer callbacks.
7648 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007649 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007650 } else {
7651
7652 // Set the template specialization kind.
7653 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007654 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007655
John McCall48871652010-08-21 09:40:31 +00007656 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007657}
7658
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007659// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007660DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007661Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007662 SourceLocation ExternLoc,
7663 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007664 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007665 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007666 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007667 IdentifierInfo *Name,
7668 SourceLocation NameLoc,
7669 AttributeList *Attr) {
7670
Douglas Gregord6ab8742009-05-28 23:31:59 +00007671 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007672 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007673 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007674 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007675 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007676 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007677 SourceLocation(), false, TypeResult(),
7678 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007679 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7680
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007681 if (!TagD)
7682 return true;
7683
John McCall48871652010-08-21 09:40:31 +00007684 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007685 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007686
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007687 if (Tag->isInvalidDecl())
7688 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007689
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007690 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7691 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7692 if (!Pattern) {
7693 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7694 << Context.getTypeDeclType(Record);
7695 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7696 return true;
7697 }
7698
Douglas Gregore47f5a72009-10-14 23:41:34 +00007699 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007700 // If the explicit instantiation is for a class or member class, the
7701 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007702 // simple-template-id.
7703 //
7704 // C++98 has the same restriction, just worded differently.
7705 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007706 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007707 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007708
Douglas Gregore47f5a72009-10-14 23:41:34 +00007709 // C++0x [temp.explicit]p2:
7710 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007711 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007712 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007713 TemplateSpecializationKind TSK
7714 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7715 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007716
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007717 // C++0x [temp.explicit]p2:
7718 // [...] An explicit instantiation shall appear in an enclosing
7719 // namespace of its template. [...]
7720 //
7721 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007722 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007723
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007724 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007725 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007726 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007727 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007728 PrevDecl = Record;
7729 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007730 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007731 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007732 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007733 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007734 PrevDecl,
7735 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007736 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007737 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007738 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007739 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007740 return TagD;
7741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007742
Douglas Gregor12e49d32009-10-15 22:53:21 +00007743 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007744 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007745 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007746 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007747 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007748 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007749 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007750 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007751 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007752 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7753 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007754 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7755 << Pattern;
7756 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007757 } else {
7758 if (InstantiateClass(NameLoc, Record, Def,
7759 getTemplateInstantiationArgs(Record),
7760 TSK))
7761 return true;
7762
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007763 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007764 if (!RecordDef)
7765 return true;
7766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007767 }
7768
Douglas Gregor1d957a32009-10-27 18:42:08 +00007769 // Instantiate all of the members of the class.
7770 InstantiateClassMembers(NameLoc, RecordDef,
7771 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007772
Douglas Gregor88d292c2010-05-13 16:44:06 +00007773 if (TSK == TSK_ExplicitInstantiationDefinition)
7774 MarkVTableUsed(NameLoc, RecordDef, true);
7775
Mike Stump87c57ac2009-05-16 07:39:55 +00007776 // FIXME: We don't have any representation for explicit instantiations of
7777 // member classes. Such a representation is not needed for compilation, but it
7778 // should be available for clients that want to see all of the declarations in
7779 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007780 return TagD;
7781}
7782
John McCallfaf5fb42010-08-26 23:41:50 +00007783DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7784 SourceLocation ExternLoc,
7785 SourceLocation TemplateLoc,
7786 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007787 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007788 // TODO: check if/when DNInfo should replace Name.
7789 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7790 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007791 if (!Name) {
7792 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007793 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007794 diag::err_explicit_instantiation_requires_name)
7795 << D.getDeclSpec().getSourceRange()
7796 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007797
Douglas Gregor450f00842009-09-25 18:43:00 +00007798 return true;
7799 }
7800
7801 // The scope passed in may not be a decl scope. Zip up the scope tree until
7802 // we find one that is.
7803 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7804 (S->getFlags() & Scope::TemplateParamScope) != 0)
7805 S = S->getParent();
7806
7807 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007808 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7809 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007810 if (R.isNull())
7811 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007812
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007813 // C++ [dcl.stc]p1:
7814 // A storage-class-specifier shall not be specified in [...] an explicit
7815 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007816 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007817 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7818 << Name;
7819 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007820 } else if (D.getDeclSpec().getStorageClassSpec()
7821 != DeclSpec::SCS_unspecified) {
7822 // Complain about then remove the storage class specifier.
7823 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7824 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7825
7826 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007827 }
7828
Douglas Gregor3c74d412009-10-14 20:14:33 +00007829 // C++0x [temp.explicit]p1:
7830 // [...] An explicit instantiation of a function template shall not use the
7831 // inline or constexpr specifiers.
7832 // Presumably, this also applies to member functions of class templates as
7833 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007834 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007835 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007836 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007837 diag::err_explicit_instantiation_inline :
7838 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007839 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007840 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007841 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7842 // not already specified.
7843 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7844 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007845
Nathan Wilsonde498452016-02-08 05:34:00 +00007846 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7847 // applied only to the definition of a function template or variable template,
7848 // declared in namespace scope.
7849 if (D.getDeclSpec().isConceptSpecified()) {
7850 Diag(D.getDeclSpec().getConceptSpecLoc(),
7851 diag::err_concept_specified_specialization) << 0;
7852 return true;
7853 }
7854
Douglas Gregore47f5a72009-10-14 23:41:34 +00007855 // C++0x [temp.explicit]p2:
7856 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007857 // definition and an explicit instantiation declaration. An explicit
7858 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007859 TemplateSpecializationKind TSK
7860 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7861 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007862
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007863 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007864 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007865
7866 if (!R->isFunctionType()) {
7867 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007868 // A [...] static data member of a class template can be explicitly
7869 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007870 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007871 // C++1y [temp.explicit]p1:
7872 // A [...] variable [...] template specialization can be explicitly
7873 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007874 if (Previous.isAmbiguous())
7875 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007876
John McCall67c00872009-12-02 08:25:40 +00007877 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007878 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007879
Larisse Voufo39a1e502013-08-06 01:03:05 +00007880 if (!PrevTemplate) {
7881 if (!Prev || !Prev->isStaticDataMember()) {
7882 // We expect to see a data data member here.
7883 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7884 << Name;
7885 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7886 P != PEnd; ++P)
7887 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7888 return true;
7889 }
7890
7891 if (!Prev->getInstantiatedFromStaticDataMember()) {
7892 // FIXME: Check for explicit specialization?
7893 Diag(D.getIdentifierLoc(),
7894 diag::err_explicit_instantiation_data_member_not_instantiated)
7895 << Prev;
7896 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7897 // FIXME: Can we provide a note showing where this was declared?
7898 return true;
7899 }
7900 } else {
7901 // Explicitly instantiate a variable template.
7902
7903 // C++1y [dcl.spec.auto]p6:
7904 // ... A program that uses auto or decltype(auto) in a context not
7905 // explicitly allowed in this section is ill-formed.
7906 //
7907 // This includes auto-typed variable template instantiations.
7908 if (R->isUndeducedType()) {
7909 Diag(T->getTypeLoc().getLocStart(),
7910 diag::err_auto_not_allowed_var_inst);
7911 return true;
7912 }
7913
Richard Smithef985ac2013-09-18 02:10:12 +00007914 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7915 // C++1y [temp.explicit]p3:
7916 // If the explicit instantiation is for a variable, the unqualified-id
7917 // in the declaration shall be a template-id.
7918 Diag(D.getIdentifierLoc(),
7919 diag::err_explicit_instantiation_without_template_id)
7920 << PrevTemplate;
7921 Diag(PrevTemplate->getLocation(),
7922 diag::note_explicit_instantiation_here);
7923 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007924 }
7925
Nathan Wilson83839122016-04-09 02:55:27 +00007926 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7927 // explicit instantiation (14.8.2) [...] of a concept definition.
7928 if (PrevTemplate->isConcept()) {
7929 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7930 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7931 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7932 return true;
7933 }
7934
Richard Smithef985ac2013-09-18 02:10:12 +00007935 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007936 TemplateArgumentListInfo TemplateArgs =
7937 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007938
Larisse Voufo39a1e502013-08-06 01:03:05 +00007939 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7940 D.getIdentifierLoc(), TemplateArgs);
7941 if (Res.isInvalid())
7942 return true;
7943
7944 // Ignore access control bits, we don't need them for redeclaration
7945 // checking.
7946 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007948
Douglas Gregore47f5a72009-10-14 23:41:34 +00007949 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007950 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007951 // or a static data member of a class template specialization, the name of
7952 // the class template specialization in the qualified-id for the member
7953 // name shall be a simple-template-id.
7954 //
7955 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007956 //
Richard Smith5977d872013-09-18 21:55:14 +00007957 // This does not apply to variable template specializations, where the
7958 // template-id is in the unqualified-id instead.
7959 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007961 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007962 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007963
Douglas Gregore47f5a72009-10-14 23:41:34 +00007964 // Check the scope of this explicit instantiation.
7965 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007966
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007967 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007968 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7969 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007970 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007971 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007972 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007973 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007974
Larisse Voufo39a1e502013-08-06 01:03:05 +00007975 if (!HasNoEffect) {
7976 // Instantiate static data member or variable template.
7977
7978 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7979 if (PrevTemplate) {
7980 // Merge attributes.
7981 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7982 ProcessDeclAttributeList(S, Prev, Attr);
7983 }
7984 if (TSK == TSK_ExplicitInstantiationDefinition)
7985 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7986 }
7987
7988 // Check the new variable specialization against the parsed input.
7989 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7990 Diag(T->getTypeLoc().getLocStart(),
7991 diag::err_invalid_var_template_spec_type)
7992 << 0 << PrevTemplate << R << Prev->getType();
7993 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7994 << 2 << PrevTemplate->getDeclName();
7995 return true;
7996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007997
Douglas Gregor450f00842009-09-25 18:43:00 +00007998 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007999 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008001
8002 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00008003 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00008004 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00008005 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00008006 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00008007 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00008008 HasExplicitTemplateArgs = true;
8009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008010
Douglas Gregor450f00842009-09-25 18:43:00 +00008011 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008012 // A [...] function [...] can be explicitly instantiated from its template.
8013 // A member function [...] of a class template can be explicitly
8014 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00008015 // template.
John McCall58cc69d2010-01-27 01:50:18 +00008016 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00008017 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00008018 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8019 P != PEnd; ++P) {
8020 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00008021 if (!HasExplicitTemplateArgs) {
8022 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00008023 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
8024 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00008025 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008026
John McCall58cc69d2010-01-27 01:50:18 +00008027 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00008028 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8029 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00008030 }
Douglas Gregor450f00842009-09-25 18:43:00 +00008031 }
8032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008033
Douglas Gregor450f00842009-09-25 18:43:00 +00008034 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8035 if (!FunTmpl)
8036 continue;
8037
Larisse Voufo98b20f12013-07-19 23:00:19 +00008038 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00008039 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008040 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008041 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00008042 (HasExplicitTemplateArgs ? &TemplateArgs
8043 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00008044 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008045 // Keep track of almost-matches.
8046 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00008047 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00008048 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008049 (void)TDK;
8050 continue;
8051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008052
John McCall58cc69d2010-01-27 01:50:18 +00008053 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008055
Douglas Gregor450f00842009-09-25 18:43:00 +00008056 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008057 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008058 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008059 D.getIdentifierLoc(),
8060 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8061 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8062 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008063
John McCall58cc69d2010-01-27 01:50:18 +00008064 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008065 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008066
8067 // Ignore access control bits, we don't need them for redeclaration checking.
8068 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008069
Alexey Bataev73983912014-11-06 10:10:50 +00008070 // C++11 [except.spec]p4
8071 // In an explicit instantiation an exception-specification may be specified,
8072 // but is not required.
8073 // If an exception-specification is specified in an explicit instantiation
8074 // directive, it shall be compatible with the exception-specifications of
8075 // other declarations of that function.
8076 if (auto *FPT = R->getAs<FunctionProtoType>())
8077 if (FPT->hasExceptionSpec()) {
8078 unsigned DiagID =
8079 diag::err_mismatched_exception_spec_explicit_instantiation;
8080 if (getLangOpts().MicrosoftExt)
8081 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8082 bool Result = CheckEquivalentExceptionSpec(
8083 PDiag(DiagID) << Specialization->getType(),
8084 PDiag(diag::note_explicit_instantiation_here),
8085 Specialization->getType()->getAs<FunctionProtoType>(),
8086 Specialization->getLocation(), FPT, D.getLocStart());
8087 // In Microsoft mode, mismatching exception specifications just cause a
8088 // warning.
8089 if (!getLangOpts().MicrosoftExt && Result)
8090 return true;
8091 }
8092
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008093 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008094 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008095 diag::err_explicit_instantiation_member_function_not_instantiated)
8096 << Specialization
8097 << (Specialization->getTemplateSpecializationKind() ==
8098 TSK_ExplicitSpecialization);
8099 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8100 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008101 }
8102
Douglas Gregorec9fd132012-01-14 16:38:05 +00008103 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008104 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8105 PrevDecl = Specialization;
8106
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008107 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008108 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008109 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008110 PrevDecl,
8111 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008112 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008113 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008114 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008115
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008116 // FIXME: We may still want to build some representation of this
8117 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008118 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008119 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008120 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008121
8122 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008123 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8124 if (Attr)
8125 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008126
Richard Smitheb36ddf2014-04-24 22:45:46 +00008127 if (Specialization->isDefined()) {
8128 // Let the ASTConsumer know that this function has been explicitly
8129 // instantiated now, and its linkage might have changed.
8130 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8131 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008132 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008133
Douglas Gregore47f5a72009-10-14 23:41:34 +00008134 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008135 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008136 // or a static data member of a class template specialization, the name of
8137 // the class template specialization in the qualified-id for the member
8138 // name shall be a simple-template-id.
8139 //
8140 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008141 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008142 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008143 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008144 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008145 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008146 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008147 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008148
Nathan Wilson83839122016-04-09 02:55:27 +00008149 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8150 // explicit instantiation (14.8.2) [...] of a concept definition.
8151 if (FunTmpl && FunTmpl->isConcept() &&
8152 !D.getDeclSpec().isConceptSpecified()) {
8153 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8154 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8155 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8156 return true;
8157 }
8158
Douglas Gregore47f5a72009-10-14 23:41:34 +00008159 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008160 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008161 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008162 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008163 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164
Douglas Gregor450f00842009-09-25 18:43:00 +00008165 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008166 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008167}
8168
John McCallfaf5fb42010-08-26 23:41:50 +00008169TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008170Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8171 const CXXScopeSpec &SS, IdentifierInfo *Name,
8172 SourceLocation TagLoc, SourceLocation NameLoc) {
8173 // This has to hold, because SS is expected to be defined.
8174 assert(Name && "Expected a name in a dependent tag");
8175
Aaron Ballman4a979672014-01-03 13:56:08 +00008176 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008177 if (!NNS)
8178 return true;
8179
Abramo Bagnara6150c882010-05-11 21:36:43 +00008180 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008181
Douglas Gregorba41d012010-04-24 16:38:41 +00008182 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8183 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008184 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008185 return true;
8186 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008187
Douglas Gregore7c20652011-03-02 00:47:37 +00008188 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008189 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008190 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8191
8192 // Create type-source location information for this type.
8193 TypeLocBuilder TLB;
8194 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008195 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008196 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8197 TL.setNameLoc(NameLoc);
8198 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008199}
8200
John McCallfaf5fb42010-08-26 23:41:50 +00008201TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008202Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8203 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008204 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008205 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008206 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008207
Richard Smith0bf8a4922011-10-18 20:49:44 +00008208 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8209 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008210 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008211 diag::warn_cxx98_compat_typename_outside_of_template :
8212 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008213 << FixItHint::CreateRemoval(TypenameLoc);
8214
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008215 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008216 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8217 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008218 if (T.isNull())
8219 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008220
8221 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8222 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008223 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008224 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008225 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008226 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008227 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008228 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008229 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008230 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008231 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008233
John McCallba7bf592010-08-24 05:47:05 +00008234 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008235}
8236
John McCallfaf5fb42010-08-26 23:41:50 +00008237TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008238Sema::ActOnTypenameType(Scope *S,
8239 SourceLocation TypenameLoc,
8240 const CXXScopeSpec &SS,
8241 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008242 TemplateTy TemplateIn,
8243 SourceLocation TemplateNameLoc,
8244 SourceLocation LAngleLoc,
8245 ASTTemplateArgsPtr TemplateArgsIn,
8246 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008247 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8248 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008249 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008250 diag::warn_cxx98_compat_typename_outside_of_template :
8251 diag::ext_typename_outside_of_template)
8252 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008253
8254 // Translate the parser's template argument list in our AST format.
8255 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8256 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8257
8258 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008259 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8260 // Construct a dependent template specialization type.
8261 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008262 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008263 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8264 DTN->getQualifier(),
8265 DTN->getIdentifier(),
8266 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008267
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008268 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008269 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008270 DependentTemplateSpecializationTypeLoc SpecTL
8271 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008272 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8273 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008274 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008275 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008276 SpecTL.setLAngleLoc(LAngleLoc);
8277 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008278 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8279 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008280 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008281 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008282
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008283 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8284 if (T.isNull())
8285 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008286
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008287 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008288 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008289 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008290 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008291 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8292 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008293 SpecTL.setLAngleLoc(LAngleLoc);
8294 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008295 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8296 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8297
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008298 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8299 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008300 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008301 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8302
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008303 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8304 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008305}
8306
Douglas Gregorb09518c2011-02-27 22:46:49 +00008307
Richard Smith6f8d2c62012-05-09 05:17:00 +00008308/// Determine whether this failed name lookup should be treated as being
8309/// disabled by a usage of std::enable_if.
8310static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8311 SourceRange &CondRange) {
8312 // We must be looking for a ::type...
8313 if (!II.isStr("type"))
8314 return false;
8315
8316 // ... within an explicitly-written template specialization...
8317 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8318 return false;
8319 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008320 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8321 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8322 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008323 return false;
8324 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008325 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008326
8327 // ... which names a complete class template declaration...
8328 const TemplateDecl *EnableIfDecl =
8329 EnableIfTST->getTemplateName().getAsTemplateDecl();
8330 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8331 return false;
8332
8333 // ... called "enable_if".
8334 const IdentifierInfo *EnableIfII =
8335 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8336 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8337 return false;
8338
8339 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008340 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008341 return true;
8342}
8343
Douglas Gregor333489b2009-03-27 23:10:48 +00008344/// \brief Build the type that describes a C++ typename specifier,
8345/// e.g., "typename T::type".
8346QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008347Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8348 SourceLocation KeywordLoc,
8349 NestedNameSpecifierLoc QualifierLoc,
8350 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008351 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008352 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008353 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008354
John McCall0b66eb32010-05-01 00:40:08 +00008355 DeclContext *Ctx = computeDeclContext(SS);
8356 if (!Ctx) {
8357 // If the nested-name-specifier is dependent and couldn't be
8358 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008359 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8360 return Context.getDependentNameType(Keyword,
8361 QualifierLoc.getNestedNameSpecifier(),
8362 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008363 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008364
John McCall0b66eb32010-05-01 00:40:08 +00008365 // If the nested-name-specifier refers to the current instantiation,
8366 // the "typename" keyword itself is superfluous. In C++03, the
8367 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8368 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008369 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008370
John McCall0b66eb32010-05-01 00:40:08 +00008371 if (RequireCompleteDeclContext(SS, Ctx))
8372 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008373
8374 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008375 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008376 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008377 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008378 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008379 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008380 case LookupResult::NotFound: {
8381 // If we're looking up 'type' within a template named 'enable_if', produce
8382 // a more specific diagnostic.
8383 SourceRange CondRange;
8384 if (isEnableIf(QualifierLoc, II, CondRange)) {
8385 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8386 << Ctx << CondRange;
8387 return QualType();
8388 }
8389
Douglas Gregore40876a2009-10-13 21:16:44 +00008390 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008391 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008392 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008393
8394 case LookupResult::FoundUnresolvedValue: {
8395 // We found a using declaration that is a value. Most likely, the using
8396 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008397 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008398 IILoc);
8399 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8400 << Name << Ctx << FullRange;
8401 if (UnresolvedUsingValueDecl *Using
8402 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008403 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008404 Diag(Loc, diag::note_using_value_decl_missing_typename)
8405 << FixItHint::CreateInsertion(Loc, "typename ");
8406 }
8407 }
8408 // Fall through to create a dependent typename type, from which we can recover
8409 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008410
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008411 case LookupResult::NotFoundInCurrentInstantiation:
8412 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008413 return Context.getDependentNameType(Keyword,
8414 QualifierLoc.getNestedNameSpecifier(),
8415 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008416
8417 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008418 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008419 // We found a type. Build an ElaboratedType, since the
8420 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008421 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008422 return Context.getElaboratedType(ETK_Typename,
8423 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008424 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008425 }
8426
8427 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008428 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008429 break;
8430
8431 case LookupResult::FoundOverloaded:
8432 DiagID = diag::err_typename_nested_not_type;
8433 Referenced = *Result.begin();
8434 break;
8435
John McCall6538c932009-10-10 05:48:19 +00008436 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008437 return QualType();
8438 }
8439
8440 // If we get here, it's because name lookup did not find a
8441 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008442 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008443 IILoc);
8444 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008445 if (Referenced)
8446 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8447 << Name;
8448 return QualType();
8449}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008450
8451namespace {
8452 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008453 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008454 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008455 SourceLocation Loc;
8456 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008457
Douglas Gregor15acfb92009-08-06 16:20:37 +00008458 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008459 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008460
Mike Stump11289f42009-09-09 15:08:12 +00008461 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008462 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008463 DeclarationName Entity)
8464 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008465 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008466
8467 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008468 /// transformed.
8469 ///
8470 /// For the purposes of type reconstruction, a type has already been
8471 /// transformed if it is NULL or if it is not dependent.
8472 bool AlreadyTransformed(QualType T) {
8473 return T.isNull() || !T->isDependentType();
8474 }
Mike Stump11289f42009-09-09 15:08:12 +00008475
8476 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008477 /// rebuilt.
8478 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008479
Douglas Gregor15acfb92009-08-06 16:20:37 +00008480 /// \brief Returns the name of the entity whose type is being rebuilt.
8481 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008482
Douglas Gregoref6ab412009-10-27 06:26:26 +00008483 /// \brief Sets the "base" location and entity when that
8484 /// information is known based on another transformation.
8485 void setBase(SourceLocation Loc, DeclarationName Entity) {
8486 this->Loc = Loc;
8487 this->Entity = Entity;
8488 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008489
8490 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8491 // Lambdas never need to be transformed.
8492 return E;
8493 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008494 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008495} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008496
Douglas Gregor15acfb92009-08-06 16:20:37 +00008497/// \brief Rebuilds a type within the context of the current instantiation.
8498///
Mike Stump11289f42009-09-09 15:08:12 +00008499/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008500/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008501/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008502/// partial specialization thereof). This routine will rebuild that type now
8503/// that we have entered the declarator's scope, which may produce different
8504/// canonical types, e.g.,
8505///
8506/// \code
8507/// template<typename T>
8508/// struct X {
8509/// typedef T* pointer;
8510/// pointer data();
8511/// };
8512///
8513/// template<typename T>
8514/// typename X<T>::pointer X<T>::data() { ... }
8515/// \endcode
8516///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008517/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008518/// since we do not know that we can look into X<T> when we parsed the type.
8519/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008520/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008521/// as the canonical type of T*, allowing the return types of the out-of-line
8522/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008523TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8524 SourceLocation Loc,
8525 DeclarationName Name) {
8526 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008527 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008528
Douglas Gregor15acfb92009-08-06 16:20:37 +00008529 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8530 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008531}
Douglas Gregorbe999392009-09-15 16:23:51 +00008532
John McCalldadc5752010-08-24 06:29:42 +00008533ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008534 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8535 DeclarationName());
8536 return Rebuilder.TransformExpr(E);
8537}
8538
John McCall99b2fe52010-04-29 23:50:39 +00008539bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008540 if (SS.isInvalid())
8541 return true;
John McCall2408e322010-04-27 00:57:59 +00008542
Douglas Gregor10176412011-02-25 16:07:42 +00008543 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008544 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8545 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008546 NestedNameSpecifierLoc Rebuilt
8547 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8548 if (!Rebuilt)
8549 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008550
Douglas Gregor10176412011-02-25 16:07:42 +00008551 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008552 return false;
John McCall2408e322010-04-27 00:57:59 +00008553}
8554
Douglas Gregor041b0842011-10-14 15:31:12 +00008555/// \brief Rebuild the template parameters now that we know we're in a current
8556/// instantiation.
8557bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8558 TemplateParameterList *Params) {
8559 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8560 Decl *Param = Params->getParam(I);
8561
8562 // There is nothing to rebuild in a type parameter.
8563 if (isa<TemplateTypeParmDecl>(Param))
8564 continue;
8565
8566 // Rebuild the template parameter list of a template template parameter.
8567 if (TemplateTemplateParmDecl *TTP
8568 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8569 if (RebuildTemplateParamsInCurrentInstantiation(
8570 TTP->getTemplateParameters()))
8571 return true;
8572
8573 continue;
8574 }
8575
8576 // Rebuild the type of a non-type template parameter.
8577 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8578 TypeSourceInfo *NewTSI
8579 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8580 NTTP->getLocation(),
8581 NTTP->getDeclName());
8582 if (!NewTSI)
8583 return true;
8584
8585 if (NewTSI != NTTP->getTypeSourceInfo()) {
8586 NTTP->setTypeSourceInfo(NewTSI);
8587 NTTP->setType(NewTSI->getType());
8588 }
8589 }
8590
8591 return false;
8592}
8593
Douglas Gregorbe999392009-09-15 16:23:51 +00008594/// \brief Produces a formatted string that describes the binding of
8595/// template parameters to template arguments.
8596std::string
8597Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8598 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008599 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008600}
8601
8602std::string
8603Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8604 const TemplateArgument *Args,
8605 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008606 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008607 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008608
Douglas Gregore62e6a02009-11-11 19:13:48 +00008609 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008610 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008611
Douglas Gregorbe999392009-09-15 16:23:51 +00008612 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008613 if (I >= NumArgs)
8614 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008615
Douglas Gregorbe999392009-09-15 16:23:51 +00008616 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008617 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008618 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008619 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008620
Douglas Gregorbe999392009-09-15 16:23:51 +00008621 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008622 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008623 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008624 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008626
Douglas Gregor0192c232010-12-20 16:52:59 +00008627 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008628 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008629 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008630
8631 Out << ']';
8632 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008633}
Francois Pichet1c229c02011-04-22 22:18:13 +00008634
Richard Smithe40f2ba2013-08-07 21:41:30 +00008635void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8636 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008637 if (!FD)
8638 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008639
8640 LateParsedTemplate *LPT = new LateParsedTemplate;
8641
8642 // Take tokens to avoid allocations
8643 LPT->Toks.swap(Toks);
8644 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008645 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008646
8647 FD->setLateTemplateParsed(true);
8648}
8649
8650void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8651 if (!FD)
8652 return;
8653 FD->setLateTemplateParsed(false);
8654}
Francois Pichet1c229c02011-04-22 22:18:13 +00008655
8656bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8657 DeclContext *DC = CurContext;
8658
8659 while (DC) {
8660 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8661 const FunctionDecl *FD = RD->isLocalClass();
8662 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8663 } else if (DC->isTranslationUnit() || DC->isNamespace())
8664 return false;
8665
8666 DC = DC->getParent();
8667 }
8668 return false;
8669}
Richard Smith6739a102016-05-05 00:56:12 +00008670
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008671namespace {
Richard Smith6739a102016-05-05 00:56:12 +00008672/// \brief Walk the path from which a declaration was instantiated, and check
8673/// that every explicit specialization along that path is visible. This enforces
8674/// C++ [temp.expl.spec]/6:
8675///
8676/// If a template, a member template or a member of a class template is
8677/// explicitly specialized then that specialization shall be declared before
8678/// the first use of that specialization that would cause an implicit
8679/// instantiation to take place, in every translation unit in which such a
8680/// use occurs; no diagnostic is required.
8681///
8682/// and also C++ [temp.class.spec]/1:
8683///
8684/// A partial specialization shall be declared before the first use of a
8685/// class template specialization that would make use of the partial
8686/// specialization as the result of an implicit or explicit instantiation
8687/// in every translation unit in which such a use occurs; no diagnostic is
8688/// required.
8689class ExplicitSpecializationVisibilityChecker {
8690 Sema &S;
8691 SourceLocation Loc;
8692 llvm::SmallVector<Module *, 8> Modules;
8693
8694public:
8695 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8696 : S(S), Loc(Loc) {}
8697
8698 void check(NamedDecl *ND) {
8699 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8700 return checkImpl(FD);
8701 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8702 return checkImpl(RD);
8703 if (auto *VD = dyn_cast<VarDecl>(ND))
8704 return checkImpl(VD);
8705 if (auto *ED = dyn_cast<EnumDecl>(ND))
8706 return checkImpl(ED);
8707 }
8708
8709private:
8710 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8711 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8712 : Sema::MissingImportKind::ExplicitSpecialization;
8713 const bool Recover = true;
8714
8715 // If we got a custom set of modules (because only a subset of the
8716 // declarations are interesting), use them, otherwise let
8717 // diagnoseMissingImport intelligently pick some.
8718 if (Modules.empty())
8719 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8720 else
8721 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8722 }
8723
8724 // Check a specific declaration. There are three problematic cases:
8725 //
8726 // 1) The declaration is an explicit specialization of a template
8727 // specialization.
8728 // 2) The declaration is an explicit specialization of a member of an
8729 // templated class.
8730 // 3) The declaration is an instantiation of a template, and that template
8731 // is an explicit specialization of a member of a templated class.
8732 //
8733 // We don't need to go any deeper than that, as the instantiation of the
8734 // surrounding class / etc is not triggered by whatever triggered this
8735 // instantiation, and thus should be checked elsewhere.
8736 template<typename SpecDecl>
8737 void checkImpl(SpecDecl *Spec) {
8738 bool IsHiddenExplicitSpecialization = false;
8739 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8740 IsHiddenExplicitSpecialization =
8741 Spec->getMemberSpecializationInfo()
8742 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8743 : !S.hasVisibleDeclaration(Spec);
8744 } else {
8745 checkInstantiated(Spec);
8746 }
8747
8748 if (IsHiddenExplicitSpecialization)
8749 diagnose(Spec->getMostRecentDecl(), false);
8750 }
8751
8752 void checkInstantiated(FunctionDecl *FD) {
8753 if (auto *TD = FD->getPrimaryTemplate())
8754 checkTemplate(TD);
8755 }
8756
8757 void checkInstantiated(CXXRecordDecl *RD) {
8758 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8759 if (!SD)
8760 return;
8761
8762 auto From = SD->getSpecializedTemplateOrPartial();
8763 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8764 checkTemplate(TD);
8765 else if (auto *TD =
8766 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8767 if (!S.hasVisibleDeclaration(TD))
8768 diagnose(TD, true);
8769 checkTemplate(TD);
8770 }
8771 }
8772
8773 void checkInstantiated(VarDecl *RD) {
8774 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8775 if (!SD)
8776 return;
8777
8778 auto From = SD->getSpecializedTemplateOrPartial();
8779 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8780 checkTemplate(TD);
8781 else if (auto *TD =
8782 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8783 if (!S.hasVisibleDeclaration(TD))
8784 diagnose(TD, true);
8785 checkTemplate(TD);
8786 }
8787 }
8788
8789 void checkInstantiated(EnumDecl *FD) {}
8790
8791 template<typename TemplDecl>
8792 void checkTemplate(TemplDecl *TD) {
8793 if (TD->isMemberSpecialization()) {
8794 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8795 diagnose(TD->getMostRecentDecl(), false);
8796 }
8797 }
8798};
Benjamin Kramera0a13c32016-08-06 11:21:04 +00008799} // end anonymous namespace
Richard Smith6739a102016-05-05 00:56:12 +00008800
8801void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8802 if (!getLangOpts().Modules)
8803 return;
8804
8805 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8806}
8807
8808/// \brief Check whether a template partial specialization that we've discovered
8809/// is hidden, and produce suitable diagnostics if so.
8810void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8811 NamedDecl *Spec) {
8812 llvm::SmallVector<Module *, 8> Modules;
8813 if (!hasVisibleDeclaration(Spec, &Modules))
8814 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8815 MissingImportKind::PartialSpecialization,
8816 /*Recover*/true);
8817}