1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2 //
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.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===/
11
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/DeclFriend.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/RecursiveASTVisitor.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #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"
32 #include "llvm/ADT/SmallBitVector.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 using namespace clang;
36 using namespace sema;
37
38 // Exported for use by Parser.
39 SourceRange
getTemplateParamsRange(TemplateParameterList const * const * Ps,unsigned N)40 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
41 unsigned N) {
42 if (!N) return SourceRange();
43 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
44 }
45
46 /// \brief Determine whether the declaration found is acceptable as the name
47 /// of a template and, if so, return that template declaration. Otherwise,
48 /// returns NULL.
isAcceptableTemplateName(ASTContext & Context,NamedDecl * Orig,bool AllowFunctionTemplates)49 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
50 NamedDecl *Orig,
51 bool AllowFunctionTemplates) {
52 NamedDecl *D = Orig->getUnderlyingDecl();
53
54 if (isa<TemplateDecl>(D)) {
55 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
56 return nullptr;
57
58 return Orig;
59 }
60
61 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
62 // C++ [temp.local]p1:
63 // Like normal (non-template) classes, class templates have an
64 // injected-class-name (Clause 9). The injected-class-name
65 // can be used with or without a template-argument-list. When
66 // it is used without a template-argument-list, it is
67 // equivalent to the injected-class-name followed by the
68 // template-parameters of the class template enclosed in
69 // <>. When it is used with a template-argument-list, it
70 // refers to the specified class template specialization,
71 // which could be the current specialization or another
72 // specialization.
73 if (Record->isInjectedClassName()) {
74 Record = cast<CXXRecordDecl>(Record->getDeclContext());
75 if (Record->getDescribedClassTemplate())
76 return Record->getDescribedClassTemplate();
77
78 if (ClassTemplateSpecializationDecl *Spec
79 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
80 return Spec->getSpecializedTemplate();
81 }
82
83 return nullptr;
84 }
85
86 return nullptr;
87 }
88
FilterAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates)89 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
90 bool AllowFunctionTemplates) {
91 // The set of class templates we've already seen.
92 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
93 LookupResult::Filter filter = R.makeFilter();
94 while (filter.hasNext()) {
95 NamedDecl *Orig = filter.next();
96 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
97 AllowFunctionTemplates);
98 if (!Repl)
99 filter.erase();
100 else if (Repl != Orig) {
101
102 // C++ [temp.local]p3:
103 // A lookup that finds an injected-class-name (10.2) can result in an
104 // ambiguity in certain cases (for example, if it is found in more than
105 // one base class). If all of the injected-class-names that are found
106 // refer to specializations of the same class template, and if the name
107 // is used as a template-name, the reference refers to the class
108 // template itself and not a specialization thereof, and is not
109 // ambiguous.
110 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
111 if (!ClassTemplates.insert(ClassTmpl).second) {
112 filter.erase();
113 continue;
114 }
115
116 // FIXME: we promote access to public here as a workaround to
117 // the fact that LookupResult doesn't let us remember that we
118 // found this template through a particular injected class name,
119 // which means we end up doing nasty things to the invariants.
120 // Pretending that access is public is *much* safer.
121 filter.replace(Repl, AS_public);
122 }
123 }
124 filter.done();
125 }
126
hasAnyAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates)127 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
128 bool AllowFunctionTemplates) {
129 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
130 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
131 return true;
132
133 return false;
134 }
135
isTemplateName(Scope * S,CXXScopeSpec & SS,bool hasTemplateKeyword,UnqualifiedId & Name,ParsedType ObjectTypePtr,bool EnteringContext,TemplateTy & TemplateResult,bool & MemberOfUnknownSpecialization)136 TemplateNameKind Sema::isTemplateName(Scope *S,
137 CXXScopeSpec &SS,
138 bool hasTemplateKeyword,
139 UnqualifiedId &Name,
140 ParsedType ObjectTypePtr,
141 bool EnteringContext,
142 TemplateTy &TemplateResult,
143 bool &MemberOfUnknownSpecialization) {
144 assert(getLangOpts().CPlusPlus && "No template names in C!");
145
146 DeclarationName TName;
147 MemberOfUnknownSpecialization = false;
148
149 switch (Name.getKind()) {
150 case UnqualifiedId::IK_Identifier:
151 TName = DeclarationName(Name.Identifier);
152 break;
153
154 case UnqualifiedId::IK_OperatorFunctionId:
155 TName = Context.DeclarationNames.getCXXOperatorName(
156 Name.OperatorFunctionId.Operator);
157 break;
158
159 case UnqualifiedId::IK_LiteralOperatorId:
160 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
161 break;
162
163 default:
164 return TNK_Non_template;
165 }
166
167 QualType ObjectType = ObjectTypePtr.get();
168
169 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
170 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
171 MemberOfUnknownSpecialization);
172 if (R.empty()) return TNK_Non_template;
173 if (R.isAmbiguous()) {
174 // Suppress diagnostics; we'll redo this lookup later.
175 R.suppressDiagnostics();
176
177 // FIXME: we might have ambiguous templates, in which case we
178 // should at least parse them properly!
179 return TNK_Non_template;
180 }
181
182 TemplateName Template;
183 TemplateNameKind TemplateKind;
184
185 unsigned ResultCount = R.end() - R.begin();
186 if (ResultCount > 1) {
187 // We assume that we'll preserve the qualifier from a function
188 // template name in other ways.
189 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
190 TemplateKind = TNK_Function_template;
191
192 // We'll do this lookup again later.
193 R.suppressDiagnostics();
194 } else {
195 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
196
197 if (SS.isSet() && !SS.isInvalid()) {
198 NestedNameSpecifier *Qualifier = SS.getScopeRep();
199 Template = Context.getQualifiedTemplateName(Qualifier,
200 hasTemplateKeyword, TD);
201 } else {
202 Template = TemplateName(TD);
203 }
204
205 if (isa<FunctionTemplateDecl>(TD)) {
206 TemplateKind = TNK_Function_template;
207
208 // We'll do this lookup again later.
209 R.suppressDiagnostics();
210 } else {
211 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
212 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
213 TemplateKind =
214 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
215 }
216 }
217
218 TemplateResult = TemplateTy::make(Template);
219 return TemplateKind;
220 }
221
DiagnoseUnknownTemplateName(const IdentifierInfo & II,SourceLocation IILoc,Scope * S,const CXXScopeSpec * SS,TemplateTy & SuggestedTemplate,TemplateNameKind & SuggestedKind)222 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
223 SourceLocation IILoc,
224 Scope *S,
225 const CXXScopeSpec *SS,
226 TemplateTy &SuggestedTemplate,
227 TemplateNameKind &SuggestedKind) {
228 // We can't recover unless there's a dependent scope specifier preceding the
229 // template name.
230 // FIXME: Typo correction?
231 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
232 computeDeclContext(*SS))
233 return false;
234
235 // The code is missing a 'template' keyword prior to the dependent template
236 // name.
237 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
238 Diag(IILoc, diag::err_template_kw_missing)
239 << Qualifier << II.getName()
240 << FixItHint::CreateInsertion(IILoc, "template ");
241 SuggestedTemplate
242 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
243 SuggestedKind = TNK_Dependent_template_name;
244 return true;
245 }
246
LookupTemplateName(LookupResult & Found,Scope * S,CXXScopeSpec & SS,QualType ObjectType,bool EnteringContext,bool & MemberOfUnknownSpecialization)247 void Sema::LookupTemplateName(LookupResult &Found,
248 Scope *S, CXXScopeSpec &SS,
249 QualType ObjectType,
250 bool EnteringContext,
251 bool &MemberOfUnknownSpecialization) {
252 // Determine where to perform name lookup
253 MemberOfUnknownSpecialization = false;
254 DeclContext *LookupCtx = nullptr;
255 bool isDependent = false;
256 if (!ObjectType.isNull()) {
257 // This nested-name-specifier occurs in a member access expression, e.g.,
258 // x->B::f, and we are looking into the type of the object.
259 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
260 LookupCtx = computeDeclContext(ObjectType);
261 isDependent = ObjectType->isDependentType();
262 assert((isDependent || !ObjectType->isIncompleteType() ||
263 ObjectType->castAs<TagType>()->isBeingDefined()) &&
264 "Caller should have completed object type");
265
266 // Template names cannot appear inside an Objective-C class or object type.
267 if (ObjectType->isObjCObjectOrInterfaceType()) {
268 Found.clear();
269 return;
270 }
271 } else if (SS.isSet()) {
272 // This nested-name-specifier occurs after another nested-name-specifier,
273 // so long into the context associated with the prior nested-name-specifier.
274 LookupCtx = computeDeclContext(SS, EnteringContext);
275 isDependent = isDependentScopeSpecifier(SS);
276
277 // The declaration context must be complete.
278 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
279 return;
280 }
281
282 bool ObjectTypeSearchedInScope = false;
283 bool AllowFunctionTemplatesInLookup = true;
284 if (LookupCtx) {
285 // Perform "qualified" name lookup into the declaration context we
286 // computed, which is either the type of the base of a member access
287 // expression or the declaration context associated with a prior
288 // nested-name-specifier.
289 LookupQualifiedName(Found, LookupCtx);
290 if (!ObjectType.isNull() && Found.empty()) {
291 // C++ [basic.lookup.classref]p1:
292 // In a class member access expression (5.2.5), if the . or -> token is
293 // immediately followed by an identifier followed by a <, the
294 // identifier must be looked up to determine whether the < is the
295 // beginning of a template argument list (14.2) or a less-than operator.
296 // The identifier is first looked up in the class of the object
297 // expression. If the identifier is not found, it is then looked up in
298 // the context of the entire postfix-expression and shall name a class
299 // or function template.
300 if (S) LookupName(Found, S);
301 ObjectTypeSearchedInScope = true;
302 AllowFunctionTemplatesInLookup = false;
303 }
304 } else if (isDependent && (!S || ObjectType.isNull())) {
305 // We cannot look into a dependent object type or nested nme
306 // specifier.
307 MemberOfUnknownSpecialization = true;
308 return;
309 } else {
310 // Perform unqualified name lookup in the current scope.
311 LookupName(Found, S);
312
313 if (!ObjectType.isNull())
314 AllowFunctionTemplatesInLookup = false;
315 }
316
317 if (Found.empty() && !isDependent) {
318 // If we did not find any names, attempt to correct any typos.
319 DeclarationName Name = Found.getLookupName();
320 Found.clear();
321 // Simple filter callback that, for keywords, only accepts the C++ *_cast
322 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
323 FilterCCC->WantTypeSpecifiers = false;
324 FilterCCC->WantExpressionKeywords = false;
325 FilterCCC->WantRemainingKeywords = false;
326 FilterCCC->WantCXXNamedCasts = true;
327 if (TypoCorrection Corrected = CorrectTypo(
328 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
329 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
330 Found.setLookupName(Corrected.getCorrection());
331 if (Corrected.getCorrectionDecl())
332 Found.addDecl(Corrected.getCorrectionDecl());
333 FilterAcceptableTemplateNames(Found);
334 if (!Found.empty()) {
335 if (LookupCtx) {
336 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
337 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
338 Name.getAsString() == CorrectedStr;
339 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
340 << Name << LookupCtx << DroppedSpecifier
341 << SS.getRange());
342 } else {
343 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
344 }
345 }
346 } else {
347 Found.setLookupName(Name);
348 }
349 }
350
351 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
352 if (Found.empty()) {
353 if (isDependent)
354 MemberOfUnknownSpecialization = true;
355 return;
356 }
357
358 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
359 !getLangOpts().CPlusPlus11) {
360 // C++03 [basic.lookup.classref]p1:
361 // [...] If the lookup in the class of the object expression finds a
362 // template, the name is also looked up in the context of the entire
363 // postfix-expression and [...]
364 //
365 // Note: C++11 does not perform this second lookup.
366 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
367 LookupOrdinaryName);
368 LookupName(FoundOuter, S);
369 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
370
371 if (FoundOuter.empty()) {
372 // - if the name is not found, the name found in the class of the
373 // object expression is used, otherwise
374 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
375 FoundOuter.isAmbiguous()) {
376 // - if the name is found in the context of the entire
377 // postfix-expression and does not name a class template, the name
378 // found in the class of the object expression is used, otherwise
379 FoundOuter.clear();
380 } else if (!Found.isSuppressingDiagnostics()) {
381 // - if the name found is a class template, it must refer to the same
382 // entity as the one found in the class of the object expression,
383 // otherwise the program is ill-formed.
384 if (!Found.isSingleResult() ||
385 Found.getFoundDecl()->getCanonicalDecl()
386 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
387 Diag(Found.getNameLoc(),
388 diag::ext_nested_name_member_ref_lookup_ambiguous)
389 << Found.getLookupName()
390 << ObjectType;
391 Diag(Found.getRepresentativeDecl()->getLocation(),
392 diag::note_ambig_member_ref_object_type)
393 << ObjectType;
394 Diag(FoundOuter.getFoundDecl()->getLocation(),
395 diag::note_ambig_member_ref_scope);
396
397 // Recover by taking the template that we found in the object
398 // expression's type.
399 }
400 }
401 }
402 }
403
404 /// ActOnDependentIdExpression - Handle a dependent id-expression that
405 /// was just parsed. This is only possible with an explicit scope
406 /// specifier naming a dependent type.
407 ExprResult
ActOnDependentIdExpression(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,bool isAddressOfOperand,const TemplateArgumentListInfo * TemplateArgs)408 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
409 SourceLocation TemplateKWLoc,
410 const DeclarationNameInfo &NameInfo,
411 bool isAddressOfOperand,
412 const TemplateArgumentListInfo *TemplateArgs) {
413 DeclContext *DC = getFunctionLevelDeclContext();
414
415 if (!isAddressOfOperand &&
416 isa<CXXMethodDecl>(DC) &&
417 cast<CXXMethodDecl>(DC)->isInstance()) {
418 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
419
420 // Since the 'this' expression is synthesized, we don't need to
421 // perform the double-lookup check.
422 NamedDecl *FirstQualifierInScope = nullptr;
423
424 return CXXDependentScopeMemberExpr::Create(
425 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
426 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
427 FirstQualifierInScope, NameInfo, TemplateArgs);
428 }
429
430 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
431 }
432
433 ExprResult
BuildDependentDeclRefExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)434 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
435 SourceLocation TemplateKWLoc,
436 const DeclarationNameInfo &NameInfo,
437 const TemplateArgumentListInfo *TemplateArgs) {
438 return DependentScopeDeclRefExpr::Create(
439 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
440 TemplateArgs);
441 }
442
443 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
444 /// that the template parameter 'PrevDecl' is being shadowed by a new
445 /// declaration at location Loc. Returns true to indicate that this is
446 /// an error, and false otherwise.
DiagnoseTemplateParameterShadow(SourceLocation Loc,Decl * PrevDecl)447 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
448 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
449
450 // Microsoft Visual C++ permits template parameters to be shadowed.
451 if (getLangOpts().MicrosoftExt)
452 return;
453
454 // C++ [temp.local]p4:
455 // A template-parameter shall not be redeclared within its
456 // scope (including nested scopes).
457 Diag(Loc, diag::err_template_param_shadow)
458 << cast<NamedDecl>(PrevDecl)->getDeclName();
459 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
460 return;
461 }
462
463 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
464 /// the parameter D to reference the templated declaration and return a pointer
465 /// to the template declaration. Otherwise, do nothing to D and return null.
AdjustDeclIfTemplate(Decl * & D)466 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
467 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
468 D = Temp->getTemplatedDecl();
469 return Temp;
470 }
471 return nullptr;
472 }
473
getTemplatePackExpansion(SourceLocation EllipsisLoc) const474 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
475 SourceLocation EllipsisLoc) const {
476 assert(Kind == Template &&
477 "Only template template arguments can be pack expansions here");
478 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
479 "Template template argument pack expansion without packs");
480 ParsedTemplateArgument Result(*this);
481 Result.EllipsisLoc = EllipsisLoc;
482 return Result;
483 }
484
translateTemplateArgument(Sema & SemaRef,const ParsedTemplateArgument & Arg)485 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
486 const ParsedTemplateArgument &Arg) {
487
488 switch (Arg.getKind()) {
489 case ParsedTemplateArgument::Type: {
490 TypeSourceInfo *DI;
491 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
492 if (!DI)
493 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
494 return TemplateArgumentLoc(TemplateArgument(T), DI);
495 }
496
497 case ParsedTemplateArgument::NonType: {
498 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
499 return TemplateArgumentLoc(TemplateArgument(E), E);
500 }
501
502 case ParsedTemplateArgument::Template: {
503 TemplateName Template = Arg.getAsTemplate().get();
504 TemplateArgument TArg;
505 if (Arg.getEllipsisLoc().isValid())
506 TArg = TemplateArgument(Template, Optional<unsigned int>());
507 else
508 TArg = Template;
509 return TemplateArgumentLoc(TArg,
510 Arg.getScopeSpec().getWithLocInContext(
511 SemaRef.Context),
512 Arg.getLocation(),
513 Arg.getEllipsisLoc());
514 }
515 }
516
517 llvm_unreachable("Unhandled parsed template argument");
518 }
519
520 /// \brief Translates template arguments as provided by the parser
521 /// into template arguments used by semantic analysis.
translateTemplateArguments(const ASTTemplateArgsPtr & TemplateArgsIn,TemplateArgumentListInfo & TemplateArgs)522 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
523 TemplateArgumentListInfo &TemplateArgs) {
524 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
525 TemplateArgs.addArgument(translateTemplateArgument(*this,
526 TemplateArgsIn[I]));
527 }
528
maybeDiagnoseTemplateParameterShadow(Sema & SemaRef,Scope * S,SourceLocation Loc,IdentifierInfo * Name)529 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
530 SourceLocation Loc,
531 IdentifierInfo *Name) {
532 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
533 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
534 if (PrevDecl && PrevDecl->isTemplateParameter())
535 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
536 }
537
538 /// ActOnTypeParameter - Called when a C++ template type parameter
539 /// (e.g., "typename T") has been parsed. Typename specifies whether
540 /// the keyword "typename" was used to declare the type parameter
541 /// (otherwise, "class" was used), and KeyLoc is the location of the
542 /// "class" or "typename" keyword. ParamName is the name of the
543 /// parameter (NULL indicates an unnamed template parameter) and
544 /// ParamNameLoc is the location of the parameter name (if any).
545 /// If the type parameter has a default argument, it will be added
546 /// later via ActOnTypeParameterDefault.
ActOnTypeParameter(Scope * S,bool Typename,SourceLocation EllipsisLoc,SourceLocation KeyLoc,IdentifierInfo * ParamName,SourceLocation ParamNameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedType DefaultArg)547 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
548 SourceLocation EllipsisLoc,
549 SourceLocation KeyLoc,
550 IdentifierInfo *ParamName,
551 SourceLocation ParamNameLoc,
552 unsigned Depth, unsigned Position,
553 SourceLocation EqualLoc,
554 ParsedType DefaultArg) {
555 assert(S->isTemplateParamScope() &&
556 "Template type parameter not in template parameter scope!");
557 bool Invalid = false;
558
559 SourceLocation Loc = ParamNameLoc;
560 if (!ParamName)
561 Loc = KeyLoc;
562
563 bool IsParameterPack = EllipsisLoc.isValid();
564 TemplateTypeParmDecl *Param
565 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
566 KeyLoc, Loc, Depth, Position, ParamName,
567 Typename, IsParameterPack);
568 Param->setAccess(AS_public);
569 if (Invalid)
570 Param->setInvalidDecl();
571
572 if (ParamName) {
573 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
574
575 // Add the template parameter into the current scope.
576 S->AddDecl(Param);
577 IdResolver.AddDecl(Param);
578 }
579
580 // C++0x [temp.param]p9:
581 // A default template-argument may be specified for any kind of
582 // template-parameter that is not a template parameter pack.
583 if (DefaultArg && IsParameterPack) {
584 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
585 DefaultArg = ParsedType();
586 }
587
588 // Handle the default argument, if provided.
589 if (DefaultArg) {
590 TypeSourceInfo *DefaultTInfo;
591 GetTypeFromParser(DefaultArg, &DefaultTInfo);
592
593 assert(DefaultTInfo && "expected source information for type");
594
595 // Check for unexpanded parameter packs.
596 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
597 UPPC_DefaultArgument))
598 return Param;
599
600 // Check the template argument itself.
601 if (CheckTemplateArgument(Param, DefaultTInfo)) {
602 Param->setInvalidDecl();
603 return Param;
604 }
605
606 Param->setDefaultArgument(DefaultTInfo, false);
607 }
608
609 return Param;
610 }
611
612 /// \brief Check that the type of a non-type template parameter is
613 /// well-formed.
614 ///
615 /// \returns the (possibly-promoted) parameter type if valid;
616 /// otherwise, produces a diagnostic and returns a NULL type.
617 QualType
CheckNonTypeTemplateParameterType(QualType T,SourceLocation Loc)618 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
619 // We don't allow variably-modified types as the type of non-type template
620 // parameters.
621 if (T->isVariablyModifiedType()) {
622 Diag(Loc, diag::err_variably_modified_nontype_template_param)
623 << T;
624 return QualType();
625 }
626
627 // C++ [temp.param]p4:
628 //
629 // A non-type template-parameter shall have one of the following
630 // (optionally cv-qualified) types:
631 //
632 // -- integral or enumeration type,
633 if (T->isIntegralOrEnumerationType() ||
634 // -- pointer to object or pointer to function,
635 T->isPointerType() ||
636 // -- reference to object or reference to function,
637 T->isReferenceType() ||
638 // -- pointer to member,
639 T->isMemberPointerType() ||
640 // -- std::nullptr_t.
641 T->isNullPtrType() ||
642 // If T is a dependent type, we can't do the check now, so we
643 // assume that it is well-formed.
644 T->isDependentType()) {
645 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
646 // are ignored when determining its type.
647 return T.getUnqualifiedType();
648 }
649
650 // C++ [temp.param]p8:
651 //
652 // A non-type template-parameter of type "array of T" or
653 // "function returning T" is adjusted to be of type "pointer to
654 // T" or "pointer to function returning T", respectively.
655 else if (T->isArrayType() || T->isFunctionType())
656 return Context.getDecayedType(T);
657
658 Diag(Loc, diag::err_template_nontype_parm_bad_type)
659 << T;
660
661 return QualType();
662 }
663
ActOnNonTypeTemplateParameter(Scope * S,Declarator & D,unsigned Depth,unsigned Position,SourceLocation EqualLoc,Expr * Default)664 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
665 unsigned Depth,
666 unsigned Position,
667 SourceLocation EqualLoc,
668 Expr *Default) {
669 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
670 QualType T = TInfo->getType();
671
672 assert(S->isTemplateParamScope() &&
673 "Non-type template parameter not in template parameter scope!");
674 bool Invalid = false;
675
676 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
677 if (T.isNull()) {
678 T = Context.IntTy; // Recover with an 'int' type.
679 Invalid = true;
680 }
681
682 IdentifierInfo *ParamName = D.getIdentifier();
683 bool IsParameterPack = D.hasEllipsis();
684 NonTypeTemplateParmDecl *Param
685 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
686 D.getLocStart(),
687 D.getIdentifierLoc(),
688 Depth, Position, ParamName, T,
689 IsParameterPack, TInfo);
690 Param->setAccess(AS_public);
691
692 if (Invalid)
693 Param->setInvalidDecl();
694
695 if (ParamName) {
696 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
697 ParamName);
698
699 // Add the template parameter into the current scope.
700 S->AddDecl(Param);
701 IdResolver.AddDecl(Param);
702 }
703
704 // C++0x [temp.param]p9:
705 // A default template-argument may be specified for any kind of
706 // template-parameter that is not a template parameter pack.
707 if (Default && IsParameterPack) {
708 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
709 Default = nullptr;
710 }
711
712 // Check the well-formedness of the default template argument, if provided.
713 if (Default) {
714 // Check for unexpanded parameter packs.
715 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
716 return Param;
717
718 TemplateArgument Converted;
719 ExprResult DefaultRes =
720 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
721 if (DefaultRes.isInvalid()) {
722 Param->setInvalidDecl();
723 return Param;
724 }
725 Default = DefaultRes.get();
726
727 Param->setDefaultArgument(Default, false);
728 }
729
730 return Param;
731 }
732
733 /// ActOnTemplateTemplateParameter - Called when a C++ template template
734 /// parameter (e.g. T in template <template \<typename> class T> class array)
735 /// has been parsed. S is the current scope.
ActOnTemplateTemplateParameter(Scope * S,SourceLocation TmpLoc,TemplateParameterList * Params,SourceLocation EllipsisLoc,IdentifierInfo * Name,SourceLocation NameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedTemplateArgument Default)736 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
737 SourceLocation TmpLoc,
738 TemplateParameterList *Params,
739 SourceLocation EllipsisLoc,
740 IdentifierInfo *Name,
741 SourceLocation NameLoc,
742 unsigned Depth,
743 unsigned Position,
744 SourceLocation EqualLoc,
745 ParsedTemplateArgument Default) {
746 assert(S->isTemplateParamScope() &&
747 "Template template parameter not in template parameter scope!");
748
749 // Construct the parameter object.
750 bool IsParameterPack = EllipsisLoc.isValid();
751 TemplateTemplateParmDecl *Param =
752 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
753 NameLoc.isInvalid()? TmpLoc : NameLoc,
754 Depth, Position, IsParameterPack,
755 Name, Params);
756 Param->setAccess(AS_public);
757
758 // If the template template parameter has a name, then link the identifier
759 // into the scope and lookup mechanisms.
760 if (Name) {
761 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
762
763 S->AddDecl(Param);
764 IdResolver.AddDecl(Param);
765 }
766
767 if (Params->size() == 0) {
768 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
769 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
770 Param->setInvalidDecl();
771 }
772
773 // C++0x [temp.param]p9:
774 // A default template-argument may be specified for any kind of
775 // template-parameter that is not a template parameter pack.
776 if (IsParameterPack && !Default.isInvalid()) {
777 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
778 Default = ParsedTemplateArgument();
779 }
780
781 if (!Default.isInvalid()) {
782 // Check only that we have a template template argument. We don't want to
783 // try to check well-formedness now, because our template template parameter
784 // might have dependent types in its template parameters, which we wouldn't
785 // be able to match now.
786 //
787 // If none of the template template parameter's template arguments mention
788 // other template parameters, we could actually perform more checking here.
789 // However, it isn't worth doing.
790 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
791 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
792 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
793 << DefaultArg.getSourceRange();
794 return Param;
795 }
796
797 // Check for unexpanded parameter packs.
798 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
799 DefaultArg.getArgument().getAsTemplate(),
800 UPPC_DefaultArgument))
801 return Param;
802
803 Param->setDefaultArgument(DefaultArg, false);
804 }
805
806 return Param;
807 }
808
809 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
810 /// contains the template parameters in Params/NumParams.
811 TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,SourceLocation ExportLoc,SourceLocation TemplateLoc,SourceLocation LAngleLoc,Decl ** Params,unsigned NumParams,SourceLocation RAngleLoc)812 Sema::ActOnTemplateParameterList(unsigned Depth,
813 SourceLocation ExportLoc,
814 SourceLocation TemplateLoc,
815 SourceLocation LAngleLoc,
816 Decl **Params, unsigned NumParams,
817 SourceLocation RAngleLoc) {
818 if (ExportLoc.isValid())
819 Diag(ExportLoc, diag::warn_template_export_unsupported);
820
821 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
822 (NamedDecl**)Params, NumParams,
823 RAngleLoc);
824 }
825
SetNestedNameSpecifier(TagDecl * T,const CXXScopeSpec & SS)826 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
827 if (SS.isSet())
828 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
829 }
830
831 DeclResult
CheckClassTemplate(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,TemplateParameterList * TemplateParams,AccessSpecifier AS,SourceLocation ModulePrivateLoc,SourceLocation FriendLoc,unsigned NumOuterTemplateParamLists,TemplateParameterList ** OuterTemplateParamLists,bool * SkipBody)832 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
833 SourceLocation KWLoc, CXXScopeSpec &SS,
834 IdentifierInfo *Name, SourceLocation NameLoc,
835 AttributeList *Attr,
836 TemplateParameterList *TemplateParams,
837 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
838 SourceLocation FriendLoc,
839 unsigned NumOuterTemplateParamLists,
840 TemplateParameterList** OuterTemplateParamLists,
841 bool *SkipBody) {
842 assert(TemplateParams && TemplateParams->size() > 0 &&
843 "No template parameters");
844 assert(TUK != TUK_Reference && "Can only declare or define class templates");
845 bool Invalid = false;
846
847 // Check that we can declare a template here.
848 if (CheckTemplateDeclScope(S, TemplateParams))
849 return true;
850
851 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
852 assert(Kind != TTK_Enum && "can't build template of enumerated type");
853
854 // There is no such thing as an unnamed class template.
855 if (!Name) {
856 Diag(KWLoc, diag::err_template_unnamed_class);
857 return true;
858 }
859
860 // Find any previous declaration with this name. For a friend with no
861 // scope explicitly specified, we only look for tag declarations (per
862 // C++11 [basic.lookup.elab]p2).
863 DeclContext *SemanticContext;
864 LookupResult Previous(*this, Name, NameLoc,
865 (SS.isEmpty() && TUK == TUK_Friend)
866 ? LookupTagName : LookupOrdinaryName,
867 ForRedeclaration);
868 if (SS.isNotEmpty() && !SS.isInvalid()) {
869 SemanticContext = computeDeclContext(SS, true);
870 if (!SemanticContext) {
871 // FIXME: Horrible, horrible hack! We can't currently represent this
872 // in the AST, and historically we have just ignored such friend
873 // class templates, so don't complain here.
874 Diag(NameLoc, TUK == TUK_Friend
875 ? diag::warn_template_qualified_friend_ignored
876 : diag::err_template_qualified_declarator_no_match)
877 << SS.getScopeRep() << SS.getRange();
878 return TUK != TUK_Friend;
879 }
880
881 if (RequireCompleteDeclContext(SS, SemanticContext))
882 return true;
883
884 // If we're adding a template to a dependent context, we may need to
885 // rebuilding some of the types used within the template parameter list,
886 // now that we know what the current instantiation is.
887 if (SemanticContext->isDependentContext()) {
888 ContextRAII SavedContext(*this, SemanticContext);
889 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
890 Invalid = true;
891 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
892 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
893
894 LookupQualifiedName(Previous, SemanticContext);
895 } else {
896 SemanticContext = CurContext;
897 LookupName(Previous, S);
898 }
899
900 if (Previous.isAmbiguous())
901 return true;
902
903 NamedDecl *PrevDecl = nullptr;
904 if (Previous.begin() != Previous.end())
905 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
906
907 // If there is a previous declaration with the same name, check
908 // whether this is a valid redeclaration.
909 ClassTemplateDecl *PrevClassTemplate
910 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
911
912 // We may have found the injected-class-name of a class template,
913 // class template partial specialization, or class template specialization.
914 // In these cases, grab the template that is being defined or specialized.
915 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
916 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
917 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
918 PrevClassTemplate
919 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
920 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
921 PrevClassTemplate
922 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
923 ->getSpecializedTemplate();
924 }
925 }
926
927 if (TUK == TUK_Friend) {
928 // C++ [namespace.memdef]p3:
929 // [...] When looking for a prior declaration of a class or a function
930 // declared as a friend, and when the name of the friend class or
931 // function is neither a qualified name nor a template-id, scopes outside
932 // the innermost enclosing namespace scope are not considered.
933 if (!SS.isSet()) {
934 DeclContext *OutermostContext = CurContext;
935 while (!OutermostContext->isFileContext())
936 OutermostContext = OutermostContext->getLookupParent();
937
938 if (PrevDecl &&
939 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
940 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
941 SemanticContext = PrevDecl->getDeclContext();
942 } else {
943 // Declarations in outer scopes don't matter. However, the outermost
944 // context we computed is the semantic context for our new
945 // declaration.
946 PrevDecl = PrevClassTemplate = nullptr;
947 SemanticContext = OutermostContext;
948
949 // Check that the chosen semantic context doesn't already contain a
950 // declaration of this name as a non-tag type.
951 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
952 ForRedeclaration);
953 DeclContext *LookupContext = SemanticContext;
954 while (LookupContext->isTransparentContext())
955 LookupContext = LookupContext->getLookupParent();
956 LookupQualifiedName(Previous, LookupContext);
957
958 if (Previous.isAmbiguous())
959 return true;
960
961 if (Previous.begin() != Previous.end())
962 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
963 }
964 }
965 } else if (PrevDecl &&
966 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
967 PrevDecl = PrevClassTemplate = nullptr;
968
969 if (PrevClassTemplate) {
970 // Ensure that the template parameter lists are compatible. Skip this check
971 // for a friend in a dependent context: the template parameter list itself
972 // could be dependent.
973 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
974 !TemplateParameterListsAreEqual(TemplateParams,
975 PrevClassTemplate->getTemplateParameters(),
976 /*Complain=*/true,
977 TPL_TemplateMatch))
978 return true;
979
980 // C++ [temp.class]p4:
981 // In a redeclaration, partial specialization, explicit
982 // specialization or explicit instantiation of a class template,
983 // the class-key shall agree in kind with the original class
984 // template declaration (7.1.5.3).
985 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
986 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
987 TUK == TUK_Definition, KWLoc, *Name)) {
988 Diag(KWLoc, diag::err_use_with_wrong_tag)
989 << Name
990 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
991 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
992 Kind = PrevRecordDecl->getTagKind();
993 }
994
995 // Check for redefinition of this class template.
996 if (TUK == TUK_Definition) {
997 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
998 // If we have a prior definition that is not visible, treat this as
999 // simply making that previous definition visible.
1000 NamedDecl *Hidden = nullptr;
1001 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1002 *SkipBody = true;
1003 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1004 assert(Tmpl && "original definition of a class template is not a "
1005 "class template?");
1006 if (auto *Listener = getASTMutationListener()) {
1007 Listener->RedefinedHiddenDefinition(Hidden, KWLoc);
1008 Listener->RedefinedHiddenDefinition(Tmpl, KWLoc);
1009 }
1010 Hidden->setHidden(false);
1011 Tmpl->setHidden(false);
1012 return Def;
1013 }
1014
1015 Diag(NameLoc, diag::err_redefinition) << Name;
1016 Diag(Def->getLocation(), diag::note_previous_definition);
1017 // FIXME: Would it make sense to try to "forget" the previous
1018 // definition, as part of error recovery?
1019 return true;
1020 }
1021 }
1022 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1023 // Maybe we will complain about the shadowed template parameter.
1024 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1025 // Just pretend that we didn't see the previous declaration.
1026 PrevDecl = nullptr;
1027 } else if (PrevDecl) {
1028 // C++ [temp]p5:
1029 // A class template shall not have the same name as any other
1030 // template, class, function, object, enumeration, enumerator,
1031 // namespace, or type in the same scope (3.3), except as specified
1032 // in (14.5.4).
1033 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1034 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1035 return true;
1036 }
1037
1038 // Check the template parameter list of this declaration, possibly
1039 // merging in the template parameter list from the previous class
1040 // template declaration. Skip this check for a friend in a dependent
1041 // context, because the template parameter list might be dependent.
1042 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1043 CheckTemplateParameterList(
1044 TemplateParams,
1045 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1046 : nullptr,
1047 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1048 SemanticContext->isDependentContext())
1049 ? TPC_ClassTemplateMember
1050 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1051 : TPC_ClassTemplate))
1052 Invalid = true;
1053
1054 if (SS.isSet()) {
1055 // If the name of the template was qualified, we must be defining the
1056 // template out-of-line.
1057 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1058 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1059 : diag::err_member_decl_does_not_match)
1060 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1061 Invalid = true;
1062 }
1063 }
1064
1065 CXXRecordDecl *NewClass =
1066 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1067 PrevClassTemplate?
1068 PrevClassTemplate->getTemplatedDecl() : nullptr,
1069 /*DelayTypeCreation=*/true);
1070 SetNestedNameSpecifier(NewClass, SS);
1071 if (NumOuterTemplateParamLists > 0)
1072 NewClass->setTemplateParameterListsInfo(Context,
1073 NumOuterTemplateParamLists,
1074 OuterTemplateParamLists);
1075
1076 // Add alignment attributes if necessary; these attributes are checked when
1077 // the ASTContext lays out the structure.
1078 if (TUK == TUK_Definition) {
1079 AddAlignmentAttributesForRecord(NewClass);
1080 AddMsStructLayoutForRecord(NewClass);
1081 }
1082
1083 ClassTemplateDecl *NewTemplate
1084 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1085 DeclarationName(Name), TemplateParams,
1086 NewClass, PrevClassTemplate);
1087 NewClass->setDescribedClassTemplate(NewTemplate);
1088
1089 if (ModulePrivateLoc.isValid())
1090 NewTemplate->setModulePrivate();
1091
1092 // Build the type for the class template declaration now.
1093 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1094 T = Context.getInjectedClassNameType(NewClass, T);
1095 assert(T->isDependentType() && "Class template type is not dependent?");
1096 (void)T;
1097
1098 // If we are providing an explicit specialization of a member that is a
1099 // class template, make a note of that.
1100 if (PrevClassTemplate &&
1101 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1102 PrevClassTemplate->setMemberSpecialization();
1103
1104 // Set the access specifier.
1105 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1106 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1107
1108 // Set the lexical context of these templates
1109 NewClass->setLexicalDeclContext(CurContext);
1110 NewTemplate->setLexicalDeclContext(CurContext);
1111
1112 if (TUK == TUK_Definition)
1113 NewClass->startDefinition();
1114
1115 if (Attr)
1116 ProcessDeclAttributeList(S, NewClass, Attr);
1117
1118 if (PrevClassTemplate)
1119 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1120
1121 AddPushedVisibilityAttribute(NewClass);
1122
1123 if (TUK != TUK_Friend) {
1124 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1125 Scope *Outer = S;
1126 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1127 Outer = Outer->getParent();
1128 PushOnScopeChains(NewTemplate, Outer);
1129 } else {
1130 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1131 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1132 NewClass->setAccess(PrevClassTemplate->getAccess());
1133 }
1134
1135 NewTemplate->setObjectOfFriendDecl();
1136
1137 // Friend templates are visible in fairly strange ways.
1138 if (!CurContext->isDependentContext()) {
1139 DeclContext *DC = SemanticContext->getRedeclContext();
1140 DC->makeDeclVisibleInContext(NewTemplate);
1141 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1142 PushOnScopeChains(NewTemplate, EnclosingScope,
1143 /* AddToContext = */ false);
1144 }
1145
1146 FriendDecl *Friend = FriendDecl::Create(
1147 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1148 Friend->setAccess(AS_public);
1149 CurContext->addDecl(Friend);
1150 }
1151
1152 if (Invalid) {
1153 NewTemplate->setInvalidDecl();
1154 NewClass->setInvalidDecl();
1155 }
1156
1157 ActOnDocumentableDecl(NewTemplate);
1158
1159 return NewTemplate;
1160 }
1161
1162 /// \brief Diagnose the presence of a default template argument on a
1163 /// template parameter, which is ill-formed in certain contexts.
1164 ///
1165 /// \returns true if the default template argument should be dropped.
DiagnoseDefaultTemplateArgument(Sema & S,Sema::TemplateParamListContext TPC,SourceLocation ParamLoc,SourceRange DefArgRange)1166 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1167 Sema::TemplateParamListContext TPC,
1168 SourceLocation ParamLoc,
1169 SourceRange DefArgRange) {
1170 switch (TPC) {
1171 case Sema::TPC_ClassTemplate:
1172 case Sema::TPC_VarTemplate:
1173 case Sema::TPC_TypeAliasTemplate:
1174 return false;
1175
1176 case Sema::TPC_FunctionTemplate:
1177 case Sema::TPC_FriendFunctionTemplateDefinition:
1178 // C++ [temp.param]p9:
1179 // A default template-argument shall not be specified in a
1180 // function template declaration or a function template
1181 // definition [...]
1182 // If a friend function template declaration specifies a default
1183 // template-argument, that declaration shall be a definition and shall be
1184 // the only declaration of the function template in the translation unit.
1185 // (C++98/03 doesn't have this wording; see DR226).
1186 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1187 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1188 : diag::ext_template_parameter_default_in_function_template)
1189 << DefArgRange;
1190 return false;
1191
1192 case Sema::TPC_ClassTemplateMember:
1193 // C++0x [temp.param]p9:
1194 // A default template-argument shall not be specified in the
1195 // template-parameter-lists of the definition of a member of a
1196 // class template that appears outside of the member's class.
1197 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1198 << DefArgRange;
1199 return true;
1200
1201 case Sema::TPC_FriendClassTemplate:
1202 case Sema::TPC_FriendFunctionTemplate:
1203 // C++ [temp.param]p9:
1204 // A default template-argument shall not be specified in a
1205 // friend template declaration.
1206 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1207 << DefArgRange;
1208 return true;
1209
1210 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1211 // for friend function templates if there is only a single
1212 // declaration (and it is a definition). Strange!
1213 }
1214
1215 llvm_unreachable("Invalid TemplateParamListContext!");
1216 }
1217
1218 /// \brief Check for unexpanded parameter packs within the template parameters
1219 /// of a template template parameter, recursively.
DiagnoseUnexpandedParameterPacks(Sema & S,TemplateTemplateParmDecl * TTP)1220 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1221 TemplateTemplateParmDecl *TTP) {
1222 // A template template parameter which is a parameter pack is also a pack
1223 // expansion.
1224 if (TTP->isParameterPack())
1225 return false;
1226
1227 TemplateParameterList *Params = TTP->getTemplateParameters();
1228 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1229 NamedDecl *P = Params->getParam(I);
1230 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1231 if (!NTTP->isParameterPack() &&
1232 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1233 NTTP->getTypeSourceInfo(),
1234 Sema::UPPC_NonTypeTemplateParameterType))
1235 return true;
1236
1237 continue;
1238 }
1239
1240 if (TemplateTemplateParmDecl *InnerTTP
1241 = dyn_cast<TemplateTemplateParmDecl>(P))
1242 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1243 return true;
1244 }
1245
1246 return false;
1247 }
1248
1249 /// \brief Checks the validity of a template parameter list, possibly
1250 /// considering the template parameter list from a previous
1251 /// declaration.
1252 ///
1253 /// If an "old" template parameter list is provided, it must be
1254 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1255 /// template parameter list.
1256 ///
1257 /// \param NewParams Template parameter list for a new template
1258 /// declaration. This template parameter list will be updated with any
1259 /// default arguments that are carried through from the previous
1260 /// template parameter list.
1261 ///
1262 /// \param OldParams If provided, template parameter list from a
1263 /// previous declaration of the same template. Default template
1264 /// arguments will be merged from the old template parameter list to
1265 /// the new template parameter list.
1266 ///
1267 /// \param TPC Describes the context in which we are checking the given
1268 /// template parameter list.
1269 ///
1270 /// \returns true if an error occurred, false otherwise.
CheckTemplateParameterList(TemplateParameterList * NewParams,TemplateParameterList * OldParams,TemplateParamListContext TPC)1271 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1272 TemplateParameterList *OldParams,
1273 TemplateParamListContext TPC) {
1274 bool Invalid = false;
1275
1276 // C++ [temp.param]p10:
1277 // The set of default template-arguments available for use with a
1278 // template declaration or definition is obtained by merging the
1279 // default arguments from the definition (if in scope) and all
1280 // declarations in scope in the same way default function
1281 // arguments are (8.3.6).
1282 bool SawDefaultArgument = false;
1283 SourceLocation PreviousDefaultArgLoc;
1284
1285 // Dummy initialization to avoid warnings.
1286 TemplateParameterList::iterator OldParam = NewParams->end();
1287 if (OldParams)
1288 OldParam = OldParams->begin();
1289
1290 bool RemoveDefaultArguments = false;
1291 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1292 NewParamEnd = NewParams->end();
1293 NewParam != NewParamEnd; ++NewParam) {
1294 // Variables used to diagnose redundant default arguments
1295 bool RedundantDefaultArg = false;
1296 SourceLocation OldDefaultLoc;
1297 SourceLocation NewDefaultLoc;
1298
1299 // Variable used to diagnose missing default arguments
1300 bool MissingDefaultArg = false;
1301
1302 // Variable used to diagnose non-final parameter packs
1303 bool SawParameterPack = false;
1304
1305 if (TemplateTypeParmDecl *NewTypeParm
1306 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1307 // Check the presence of a default argument here.
1308 if (NewTypeParm->hasDefaultArgument() &&
1309 DiagnoseDefaultTemplateArgument(*this, TPC,
1310 NewTypeParm->getLocation(),
1311 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1312 .getSourceRange()))
1313 NewTypeParm->removeDefaultArgument();
1314
1315 // Merge default arguments for template type parameters.
1316 TemplateTypeParmDecl *OldTypeParm
1317 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1318
1319 if (NewTypeParm->isParameterPack()) {
1320 assert(!NewTypeParm->hasDefaultArgument() &&
1321 "Parameter packs can't have a default argument!");
1322 SawParameterPack = true;
1323 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1324 NewTypeParm->hasDefaultArgument()) {
1325 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1326 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1327 SawDefaultArgument = true;
1328 RedundantDefaultArg = true;
1329 PreviousDefaultArgLoc = NewDefaultLoc;
1330 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1331 // Merge the default argument from the old declaration to the
1332 // new declaration.
1333 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1334 true);
1335 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1336 } else if (NewTypeParm->hasDefaultArgument()) {
1337 SawDefaultArgument = true;
1338 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1339 } else if (SawDefaultArgument)
1340 MissingDefaultArg = true;
1341 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1342 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1343 // Check for unexpanded parameter packs.
1344 if (!NewNonTypeParm->isParameterPack() &&
1345 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1346 NewNonTypeParm->getTypeSourceInfo(),
1347 UPPC_NonTypeTemplateParameterType)) {
1348 Invalid = true;
1349 continue;
1350 }
1351
1352 // Check the presence of a default argument here.
1353 if (NewNonTypeParm->hasDefaultArgument() &&
1354 DiagnoseDefaultTemplateArgument(*this, TPC,
1355 NewNonTypeParm->getLocation(),
1356 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1357 NewNonTypeParm->removeDefaultArgument();
1358 }
1359
1360 // Merge default arguments for non-type template parameters
1361 NonTypeTemplateParmDecl *OldNonTypeParm
1362 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1363 if (NewNonTypeParm->isParameterPack()) {
1364 assert(!NewNonTypeParm->hasDefaultArgument() &&
1365 "Parameter packs can't have a default argument!");
1366 if (!NewNonTypeParm->isPackExpansion())
1367 SawParameterPack = true;
1368 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1369 NewNonTypeParm->hasDefaultArgument()) {
1370 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1371 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1372 SawDefaultArgument = true;
1373 RedundantDefaultArg = true;
1374 PreviousDefaultArgLoc = NewDefaultLoc;
1375 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1376 // Merge the default argument from the old declaration to the
1377 // new declaration.
1378 // FIXME: We need to create a new kind of "default argument"
1379 // expression that points to a previous non-type template
1380 // parameter.
1381 NewNonTypeParm->setDefaultArgument(
1382 OldNonTypeParm->getDefaultArgument(),
1383 /*Inherited=*/ true);
1384 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1385 } else if (NewNonTypeParm->hasDefaultArgument()) {
1386 SawDefaultArgument = true;
1387 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1388 } else if (SawDefaultArgument)
1389 MissingDefaultArg = true;
1390 } else {
1391 TemplateTemplateParmDecl *NewTemplateParm
1392 = cast<TemplateTemplateParmDecl>(*NewParam);
1393
1394 // Check for unexpanded parameter packs, recursively.
1395 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1396 Invalid = true;
1397 continue;
1398 }
1399
1400 // Check the presence of a default argument here.
1401 if (NewTemplateParm->hasDefaultArgument() &&
1402 DiagnoseDefaultTemplateArgument(*this, TPC,
1403 NewTemplateParm->getLocation(),
1404 NewTemplateParm->getDefaultArgument().getSourceRange()))
1405 NewTemplateParm->removeDefaultArgument();
1406
1407 // Merge default arguments for template template parameters
1408 TemplateTemplateParmDecl *OldTemplateParm
1409 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1410 if (NewTemplateParm->isParameterPack()) {
1411 assert(!NewTemplateParm->hasDefaultArgument() &&
1412 "Parameter packs can't have a default argument!");
1413 if (!NewTemplateParm->isPackExpansion())
1414 SawParameterPack = true;
1415 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1416 NewTemplateParm->hasDefaultArgument()) {
1417 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1418 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1419 SawDefaultArgument = true;
1420 RedundantDefaultArg = true;
1421 PreviousDefaultArgLoc = NewDefaultLoc;
1422 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1423 // Merge the default argument from the old declaration to the
1424 // new declaration.
1425 // FIXME: We need to create a new kind of "default argument" expression
1426 // that points to a previous template template parameter.
1427 NewTemplateParm->setDefaultArgument(
1428 OldTemplateParm->getDefaultArgument(),
1429 /*Inherited=*/ true);
1430 PreviousDefaultArgLoc
1431 = OldTemplateParm->getDefaultArgument().getLocation();
1432 } else if (NewTemplateParm->hasDefaultArgument()) {
1433 SawDefaultArgument = true;
1434 PreviousDefaultArgLoc
1435 = NewTemplateParm->getDefaultArgument().getLocation();
1436 } else if (SawDefaultArgument)
1437 MissingDefaultArg = true;
1438 }
1439
1440 // C++11 [temp.param]p11:
1441 // If a template parameter of a primary class template or alias template
1442 // is a template parameter pack, it shall be the last template parameter.
1443 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1444 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1445 TPC == TPC_TypeAliasTemplate)) {
1446 Diag((*NewParam)->getLocation(),
1447 diag::err_template_param_pack_must_be_last_template_parameter);
1448 Invalid = true;
1449 }
1450
1451 if (RedundantDefaultArg) {
1452 // C++ [temp.param]p12:
1453 // A template-parameter shall not be given default arguments
1454 // by two different declarations in the same scope.
1455 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1456 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1457 Invalid = true;
1458 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1459 // C++ [temp.param]p11:
1460 // If a template-parameter of a class template has a default
1461 // template-argument, each subsequent template-parameter shall either
1462 // have a default template-argument supplied or be a template parameter
1463 // pack.
1464 Diag((*NewParam)->getLocation(),
1465 diag::err_template_param_default_arg_missing);
1466 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1467 Invalid = true;
1468 RemoveDefaultArguments = true;
1469 }
1470
1471 // If we have an old template parameter list that we're merging
1472 // in, move on to the next parameter.
1473 if (OldParams)
1474 ++OldParam;
1475 }
1476
1477 // We were missing some default arguments at the end of the list, so remove
1478 // all of the default arguments.
1479 if (RemoveDefaultArguments) {
1480 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1481 NewParamEnd = NewParams->end();
1482 NewParam != NewParamEnd; ++NewParam) {
1483 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1484 TTP->removeDefaultArgument();
1485 else if (NonTypeTemplateParmDecl *NTTP
1486 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1487 NTTP->removeDefaultArgument();
1488 else
1489 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1490 }
1491 }
1492
1493 return Invalid;
1494 }
1495
1496 namespace {
1497
1498 /// A class which looks for a use of a certain level of template
1499 /// parameter.
1500 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1501 typedef RecursiveASTVisitor<DependencyChecker> super;
1502
1503 unsigned Depth;
1504 bool Match;
1505 SourceLocation MatchLoc;
1506
DependencyChecker__anonce82d6730111::DependencyChecker1507 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1508
DependencyChecker__anonce82d6730111::DependencyChecker1509 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1510 NamedDecl *ND = Params->getParam(0);
1511 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1512 Depth = PD->getDepth();
1513 } else if (NonTypeTemplateParmDecl *PD =
1514 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1515 Depth = PD->getDepth();
1516 } else {
1517 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1518 }
1519 }
1520
Matches__anonce82d6730111::DependencyChecker1521 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1522 if (ParmDepth >= Depth) {
1523 Match = true;
1524 MatchLoc = Loc;
1525 return true;
1526 }
1527 return false;
1528 }
1529
VisitTemplateTypeParmTypeLoc__anonce82d6730111::DependencyChecker1530 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1531 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1532 }
1533
VisitTemplateTypeParmType__anonce82d6730111::DependencyChecker1534 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1535 return !Matches(T->getDepth());
1536 }
1537
TraverseTemplateName__anonce82d6730111::DependencyChecker1538 bool TraverseTemplateName(TemplateName N) {
1539 if (TemplateTemplateParmDecl *PD =
1540 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1541 if (Matches(PD->getDepth()))
1542 return false;
1543 return super::TraverseTemplateName(N);
1544 }
1545
VisitDeclRefExpr__anonce82d6730111::DependencyChecker1546 bool VisitDeclRefExpr(DeclRefExpr *E) {
1547 if (NonTypeTemplateParmDecl *PD =
1548 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1549 if (Matches(PD->getDepth(), E->getExprLoc()))
1550 return false;
1551 return super::VisitDeclRefExpr(E);
1552 }
1553
VisitSubstTemplateTypeParmType__anonce82d6730111::DependencyChecker1554 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1555 return TraverseType(T->getReplacementType());
1556 }
1557
1558 bool
VisitSubstTemplateTypeParmPackType__anonce82d6730111::DependencyChecker1559 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1560 return TraverseTemplateArgument(T->getArgumentPack());
1561 }
1562
TraverseInjectedClassNameType__anonce82d6730111::DependencyChecker1563 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1564 return TraverseType(T->getInjectedSpecializationType());
1565 }
1566 };
1567 }
1568
1569 /// Determines whether a given type depends on the given parameter
1570 /// list.
1571 static bool
DependsOnTemplateParameters(QualType T,TemplateParameterList * Params)1572 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1573 DependencyChecker Checker(Params);
1574 Checker.TraverseType(T);
1575 return Checker.Match;
1576 }
1577
1578 // Find the source range corresponding to the named type in the given
1579 // nested-name-specifier, if any.
getRangeOfTypeInNestedNameSpecifier(ASTContext & Context,QualType T,const CXXScopeSpec & SS)1580 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1581 QualType T,
1582 const CXXScopeSpec &SS) {
1583 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1584 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1585 if (const Type *CurType = NNS->getAsType()) {
1586 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1587 return NNSLoc.getTypeLoc().getSourceRange();
1588 } else
1589 break;
1590
1591 NNSLoc = NNSLoc.getPrefix();
1592 }
1593
1594 return SourceRange();
1595 }
1596
1597 /// \brief Match the given template parameter lists to the given scope
1598 /// specifier, returning the template parameter list that applies to the
1599 /// name.
1600 ///
1601 /// \param DeclStartLoc the start of the declaration that has a scope
1602 /// specifier or a template parameter list.
1603 ///
1604 /// \param DeclLoc The location of the declaration itself.
1605 ///
1606 /// \param SS the scope specifier that will be matched to the given template
1607 /// parameter lists. This scope specifier precedes a qualified name that is
1608 /// being declared.
1609 ///
1610 /// \param TemplateId The template-id following the scope specifier, if there
1611 /// is one. Used to check for a missing 'template<>'.
1612 ///
1613 /// \param ParamLists the template parameter lists, from the outermost to the
1614 /// innermost template parameter lists.
1615 ///
1616 /// \param IsFriend Whether to apply the slightly different rules for
1617 /// matching template parameters to scope specifiers in friend
1618 /// declarations.
1619 ///
1620 /// \param IsExplicitSpecialization will be set true if the entity being
1621 /// declared is an explicit specialization, false otherwise.
1622 ///
1623 /// \returns the template parameter list, if any, that corresponds to the
1624 /// name that is preceded by the scope specifier @p SS. This template
1625 /// parameter list may have template parameters (if we're declaring a
1626 /// template) or may have no template parameters (if we're declaring a
1627 /// template specialization), or may be NULL (if what we're declaring isn't
1628 /// itself a template).
MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,SourceLocation DeclLoc,const CXXScopeSpec & SS,TemplateIdAnnotation * TemplateId,ArrayRef<TemplateParameterList * > ParamLists,bool IsFriend,bool & IsExplicitSpecialization,bool & Invalid)1629 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1630 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1631 TemplateIdAnnotation *TemplateId,
1632 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1633 bool &IsExplicitSpecialization, bool &Invalid) {
1634 IsExplicitSpecialization = false;
1635 Invalid = false;
1636
1637 // The sequence of nested types to which we will match up the template
1638 // parameter lists. We first build this list by starting with the type named
1639 // by the nested-name-specifier and walking out until we run out of types.
1640 SmallVector<QualType, 4> NestedTypes;
1641 QualType T;
1642 if (SS.getScopeRep()) {
1643 if (CXXRecordDecl *Record
1644 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1645 T = Context.getTypeDeclType(Record);
1646 else
1647 T = QualType(SS.getScopeRep()->getAsType(), 0);
1648 }
1649
1650 // If we found an explicit specialization that prevents us from needing
1651 // 'template<>' headers, this will be set to the location of that
1652 // explicit specialization.
1653 SourceLocation ExplicitSpecLoc;
1654
1655 while (!T.isNull()) {
1656 NestedTypes.push_back(T);
1657
1658 // Retrieve the parent of a record type.
1659 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1660 // If this type is an explicit specialization, we're done.
1661 if (ClassTemplateSpecializationDecl *Spec
1662 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1663 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1664 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1665 ExplicitSpecLoc = Spec->getLocation();
1666 break;
1667 }
1668 } else if (Record->getTemplateSpecializationKind()
1669 == TSK_ExplicitSpecialization) {
1670 ExplicitSpecLoc = Record->getLocation();
1671 break;
1672 }
1673
1674 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1675 T = Context.getTypeDeclType(Parent);
1676 else
1677 T = QualType();
1678 continue;
1679 }
1680
1681 if (const TemplateSpecializationType *TST
1682 = T->getAs<TemplateSpecializationType>()) {
1683 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1684 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1685 T = Context.getTypeDeclType(Parent);
1686 else
1687 T = QualType();
1688 continue;
1689 }
1690 }
1691
1692 // Look one step prior in a dependent template specialization type.
1693 if (const DependentTemplateSpecializationType *DependentTST
1694 = T->getAs<DependentTemplateSpecializationType>()) {
1695 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1696 T = QualType(NNS->getAsType(), 0);
1697 else
1698 T = QualType();
1699 continue;
1700 }
1701
1702 // Look one step prior in a dependent name type.
1703 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1704 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1705 T = QualType(NNS->getAsType(), 0);
1706 else
1707 T = QualType();
1708 continue;
1709 }
1710
1711 // Retrieve the parent of an enumeration type.
1712 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1713 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1714 // check here.
1715 EnumDecl *Enum = EnumT->getDecl();
1716
1717 // Get to the parent type.
1718 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1719 T = Context.getTypeDeclType(Parent);
1720 else
1721 T = QualType();
1722 continue;
1723 }
1724
1725 T = QualType();
1726 }
1727 // Reverse the nested types list, since we want to traverse from the outermost
1728 // to the innermost while checking template-parameter-lists.
1729 std::reverse(NestedTypes.begin(), NestedTypes.end());
1730
1731 // C++0x [temp.expl.spec]p17:
1732 // A member or a member template may be nested within many
1733 // enclosing class templates. In an explicit specialization for
1734 // such a member, the member declaration shall be preceded by a
1735 // template<> for each enclosing class template that is
1736 // explicitly specialized.
1737 bool SawNonEmptyTemplateParameterList = false;
1738
1739 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1740 if (SawNonEmptyTemplateParameterList) {
1741 Diag(DeclLoc, diag::err_specialize_member_of_template)
1742 << !Recovery << Range;
1743 Invalid = true;
1744 IsExplicitSpecialization = false;
1745 return true;
1746 }
1747
1748 return false;
1749 };
1750
1751 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1752 // Check that we can have an explicit specialization here.
1753 if (CheckExplicitSpecialization(Range, true))
1754 return true;
1755
1756 // We don't have a template header, but we should.
1757 SourceLocation ExpectedTemplateLoc;
1758 if (!ParamLists.empty())
1759 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1760 else
1761 ExpectedTemplateLoc = DeclStartLoc;
1762
1763 Diag(DeclLoc, diag::err_template_spec_needs_header)
1764 << Range
1765 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1766 return false;
1767 };
1768
1769 unsigned ParamIdx = 0;
1770 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1771 ++TypeIdx) {
1772 T = NestedTypes[TypeIdx];
1773
1774 // Whether we expect a 'template<>' header.
1775 bool NeedEmptyTemplateHeader = false;
1776
1777 // Whether we expect a template header with parameters.
1778 bool NeedNonemptyTemplateHeader = false;
1779
1780 // For a dependent type, the set of template parameters that we
1781 // expect to see.
1782 TemplateParameterList *ExpectedTemplateParams = nullptr;
1783
1784 // C++0x [temp.expl.spec]p15:
1785 // A member or a member template may be nested within many enclosing
1786 // class templates. In an explicit specialization for such a member, the
1787 // member declaration shall be preceded by a template<> for each
1788 // enclosing class template that is explicitly specialized.
1789 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1790 if (ClassTemplatePartialSpecializationDecl *Partial
1791 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1792 ExpectedTemplateParams = Partial->getTemplateParameters();
1793 NeedNonemptyTemplateHeader = true;
1794 } else if (Record->isDependentType()) {
1795 if (Record->getDescribedClassTemplate()) {
1796 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1797 ->getTemplateParameters();
1798 NeedNonemptyTemplateHeader = true;
1799 }
1800 } else if (ClassTemplateSpecializationDecl *Spec
1801 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1802 // C++0x [temp.expl.spec]p4:
1803 // Members of an explicitly specialized class template are defined
1804 // in the same manner as members of normal classes, and not using
1805 // the template<> syntax.
1806 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1807 NeedEmptyTemplateHeader = true;
1808 else
1809 continue;
1810 } else if (Record->getTemplateSpecializationKind()) {
1811 if (Record->getTemplateSpecializationKind()
1812 != TSK_ExplicitSpecialization &&
1813 TypeIdx == NumTypes - 1)
1814 IsExplicitSpecialization = true;
1815
1816 continue;
1817 }
1818 } else if (const TemplateSpecializationType *TST
1819 = T->getAs<TemplateSpecializationType>()) {
1820 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1821 ExpectedTemplateParams = Template->getTemplateParameters();
1822 NeedNonemptyTemplateHeader = true;
1823 }
1824 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1825 // FIXME: We actually could/should check the template arguments here
1826 // against the corresponding template parameter list.
1827 NeedNonemptyTemplateHeader = false;
1828 }
1829
1830 // C++ [temp.expl.spec]p16:
1831 // In an explicit specialization declaration for a member of a class
1832 // template or a member template that ap- pears in namespace scope, the
1833 // member template and some of its enclosing class templates may remain
1834 // unspecialized, except that the declaration shall not explicitly
1835 // specialize a class member template if its en- closing class templates
1836 // are not explicitly specialized as well.
1837 if (ParamIdx < ParamLists.size()) {
1838 if (ParamLists[ParamIdx]->size() == 0) {
1839 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1840 false))
1841 return nullptr;
1842 } else
1843 SawNonEmptyTemplateParameterList = true;
1844 }
1845
1846 if (NeedEmptyTemplateHeader) {
1847 // If we're on the last of the types, and we need a 'template<>' header
1848 // here, then it's an explicit specialization.
1849 if (TypeIdx == NumTypes - 1)
1850 IsExplicitSpecialization = true;
1851
1852 if (ParamIdx < ParamLists.size()) {
1853 if (ParamLists[ParamIdx]->size() > 0) {
1854 // The header has template parameters when it shouldn't. Complain.
1855 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1856 diag::err_template_param_list_matches_nontemplate)
1857 << T
1858 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1859 ParamLists[ParamIdx]->getRAngleLoc())
1860 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1861 Invalid = true;
1862 return nullptr;
1863 }
1864
1865 // Consume this template header.
1866 ++ParamIdx;
1867 continue;
1868 }
1869
1870 if (!IsFriend)
1871 if (DiagnoseMissingExplicitSpecialization(
1872 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1873 return nullptr;
1874
1875 continue;
1876 }
1877
1878 if (NeedNonemptyTemplateHeader) {
1879 // In friend declarations we can have template-ids which don't
1880 // depend on the corresponding template parameter lists. But
1881 // assume that empty parameter lists are supposed to match this
1882 // template-id.
1883 if (IsFriend && T->isDependentType()) {
1884 if (ParamIdx < ParamLists.size() &&
1885 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1886 ExpectedTemplateParams = nullptr;
1887 else
1888 continue;
1889 }
1890
1891 if (ParamIdx < ParamLists.size()) {
1892 // Check the template parameter list, if we can.
1893 if (ExpectedTemplateParams &&
1894 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1895 ExpectedTemplateParams,
1896 true, TPL_TemplateMatch))
1897 Invalid = true;
1898
1899 if (!Invalid &&
1900 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1901 TPC_ClassTemplateMember))
1902 Invalid = true;
1903
1904 ++ParamIdx;
1905 continue;
1906 }
1907
1908 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1909 << T
1910 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1911 Invalid = true;
1912 continue;
1913 }
1914 }
1915
1916 // If there were at least as many template-ids as there were template
1917 // parameter lists, then there are no template parameter lists remaining for
1918 // the declaration itself.
1919 if (ParamIdx >= ParamLists.size()) {
1920 if (TemplateId && !IsFriend) {
1921 // We don't have a template header for the declaration itself, but we
1922 // should.
1923 IsExplicitSpecialization = true;
1924 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1925 TemplateId->RAngleLoc));
1926
1927 // Fabricate an empty template parameter list for the invented header.
1928 return TemplateParameterList::Create(Context, SourceLocation(),
1929 SourceLocation(), nullptr, 0,
1930 SourceLocation());
1931 }
1932
1933 return nullptr;
1934 }
1935
1936 // If there were too many template parameter lists, complain about that now.
1937 if (ParamIdx < ParamLists.size() - 1) {
1938 bool HasAnyExplicitSpecHeader = false;
1939 bool AllExplicitSpecHeaders = true;
1940 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1941 if (ParamLists[I]->size() == 0)
1942 HasAnyExplicitSpecHeader = true;
1943 else
1944 AllExplicitSpecHeaders = false;
1945 }
1946
1947 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1948 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1949 : diag::err_template_spec_extra_headers)
1950 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1951 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1952
1953 // If there was a specialization somewhere, such that 'template<>' is
1954 // not required, and there were any 'template<>' headers, note where the
1955 // specialization occurred.
1956 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1957 Diag(ExplicitSpecLoc,
1958 diag::note_explicit_template_spec_does_not_need_header)
1959 << NestedTypes.back();
1960
1961 // We have a template parameter list with no corresponding scope, which
1962 // means that the resulting template declaration can't be instantiated
1963 // properly (we'll end up with dependent nodes when we shouldn't).
1964 if (!AllExplicitSpecHeaders)
1965 Invalid = true;
1966 }
1967
1968 // C++ [temp.expl.spec]p16:
1969 // In an explicit specialization declaration for a member of a class
1970 // template or a member template that ap- pears in namespace scope, the
1971 // member template and some of its enclosing class templates may remain
1972 // unspecialized, except that the declaration shall not explicitly
1973 // specialize a class member template if its en- closing class templates
1974 // are not explicitly specialized as well.
1975 if (ParamLists.back()->size() == 0 &&
1976 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1977 false))
1978 return nullptr;
1979
1980 // Return the last template parameter list, which corresponds to the
1981 // entity being declared.
1982 return ParamLists.back();
1983 }
1984
NoteAllFoundTemplates(TemplateName Name)1985 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1986 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1987 Diag(Template->getLocation(), diag::note_template_declared_here)
1988 << (isa<FunctionTemplateDecl>(Template)
1989 ? 0
1990 : isa<ClassTemplateDecl>(Template)
1991 ? 1
1992 : isa<VarTemplateDecl>(Template)
1993 ? 2
1994 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1995 << Template->getDeclName();
1996 return;
1997 }
1998
1999 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2000 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2001 IEnd = OST->end();
2002 I != IEnd; ++I)
2003 Diag((*I)->getLocation(), diag::note_template_declared_here)
2004 << 0 << (*I)->getDeclName();
2005
2006 return;
2007 }
2008 }
2009
CheckTemplateIdType(TemplateName Name,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)2010 QualType Sema::CheckTemplateIdType(TemplateName Name,
2011 SourceLocation TemplateLoc,
2012 TemplateArgumentListInfo &TemplateArgs) {
2013 DependentTemplateName *DTN
2014 = Name.getUnderlying().getAsDependentTemplateName();
2015 if (DTN && DTN->isIdentifier())
2016 // When building a template-id where the template-name is dependent,
2017 // assume the template is a type template. Either our assumption is
2018 // correct, or the code is ill-formed and will be diagnosed when the
2019 // dependent name is substituted.
2020 return Context.getDependentTemplateSpecializationType(ETK_None,
2021 DTN->getQualifier(),
2022 DTN->getIdentifier(),
2023 TemplateArgs);
2024
2025 TemplateDecl *Template = Name.getAsTemplateDecl();
2026 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2027 isa<VarTemplateDecl>(Template)) {
2028 // We might have a substituted template template parameter pack. If so,
2029 // build a template specialization type for it.
2030 if (Name.getAsSubstTemplateTemplateParmPack())
2031 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2032
2033 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2034 << Name;
2035 NoteAllFoundTemplates(Name);
2036 return QualType();
2037 }
2038
2039 // Check that the template argument list is well-formed for this
2040 // template.
2041 SmallVector<TemplateArgument, 4> Converted;
2042 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2043 false, Converted))
2044 return QualType();
2045
2046 QualType CanonType;
2047
2048 bool InstantiationDependent = false;
2049 if (TypeAliasTemplateDecl *AliasTemplate =
2050 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2051 // Find the canonical type for this type alias template specialization.
2052 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2053 if (Pattern->isInvalidDecl())
2054 return QualType();
2055
2056 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2057 Converted.data(), Converted.size());
2058
2059 // Only substitute for the innermost template argument list.
2060 MultiLevelTemplateArgumentList TemplateArgLists;
2061 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2062 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2063 for (unsigned I = 0; I < Depth; ++I)
2064 TemplateArgLists.addOuterTemplateArguments(None);
2065
2066 LocalInstantiationScope Scope(*this);
2067 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2068 if (Inst.isInvalid())
2069 return QualType();
2070
2071 CanonType = SubstType(Pattern->getUnderlyingType(),
2072 TemplateArgLists, AliasTemplate->getLocation(),
2073 AliasTemplate->getDeclName());
2074 if (CanonType.isNull())
2075 return QualType();
2076 } else if (Name.isDependent() ||
2077 TemplateSpecializationType::anyDependentTemplateArguments(
2078 TemplateArgs, InstantiationDependent)) {
2079 // This class template specialization is a dependent
2080 // type. Therefore, its canonical type is another class template
2081 // specialization type that contains all of the converted
2082 // arguments in canonical form. This ensures that, e.g., A<T> and
2083 // A<T, T> have identical types when A is declared as:
2084 //
2085 // template<typename T, typename U = T> struct A;
2086 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2087 CanonType = Context.getTemplateSpecializationType(CanonName,
2088 Converted.data(),
2089 Converted.size());
2090
2091 // FIXME: CanonType is not actually the canonical type, and unfortunately
2092 // it is a TemplateSpecializationType that we will never use again.
2093 // In the future, we need to teach getTemplateSpecializationType to only
2094 // build the canonical type and return that to us.
2095 CanonType = Context.getCanonicalType(CanonType);
2096
2097 // This might work out to be a current instantiation, in which
2098 // case the canonical type needs to be the InjectedClassNameType.
2099 //
2100 // TODO: in theory this could be a simple hashtable lookup; most
2101 // changes to CurContext don't change the set of current
2102 // instantiations.
2103 if (isa<ClassTemplateDecl>(Template)) {
2104 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2105 // If we get out to a namespace, we're done.
2106 if (Ctx->isFileContext()) break;
2107
2108 // If this isn't a record, keep looking.
2109 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2110 if (!Record) continue;
2111
2112 // Look for one of the two cases with InjectedClassNameTypes
2113 // and check whether it's the same template.
2114 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2115 !Record->getDescribedClassTemplate())
2116 continue;
2117
2118 // Fetch the injected class name type and check whether its
2119 // injected type is equal to the type we just built.
2120 QualType ICNT = Context.getTypeDeclType(Record);
2121 QualType Injected = cast<InjectedClassNameType>(ICNT)
2122 ->getInjectedSpecializationType();
2123
2124 if (CanonType != Injected->getCanonicalTypeInternal())
2125 continue;
2126
2127 // If so, the canonical type of this TST is the injected
2128 // class name type of the record we just found.
2129 assert(ICNT.isCanonical());
2130 CanonType = ICNT;
2131 break;
2132 }
2133 }
2134 } else if (ClassTemplateDecl *ClassTemplate
2135 = dyn_cast<ClassTemplateDecl>(Template)) {
2136 // Find the class template specialization declaration that
2137 // corresponds to these arguments.
2138 void *InsertPos = nullptr;
2139 ClassTemplateSpecializationDecl *Decl
2140 = ClassTemplate->findSpecialization(Converted, InsertPos);
2141 if (!Decl) {
2142 // This is the first time we have referenced this class template
2143 // specialization. Create the canonical declaration and add it to
2144 // the set of specializations.
2145 Decl = ClassTemplateSpecializationDecl::Create(Context,
2146 ClassTemplate->getTemplatedDecl()->getTagKind(),
2147 ClassTemplate->getDeclContext(),
2148 ClassTemplate->getTemplatedDecl()->getLocStart(),
2149 ClassTemplate->getLocation(),
2150 ClassTemplate,
2151 Converted.data(),
2152 Converted.size(), nullptr);
2153 ClassTemplate->AddSpecialization(Decl, InsertPos);
2154 if (ClassTemplate->isOutOfLine())
2155 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2156 }
2157
2158 // Diagnose uses of this specialization.
2159 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2160
2161 CanonType = Context.getTypeDeclType(Decl);
2162 assert(isa<RecordType>(CanonType) &&
2163 "type of non-dependent specialization is not a RecordType");
2164 }
2165
2166 // Build the fully-sugared type for this class template
2167 // specialization, which refers back to the class template
2168 // specialization we created or found.
2169 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2170 }
2171
2172 TypeResult
ActOnTemplateIdType(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,bool IsCtorOrDtorName)2173 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2174 TemplateTy TemplateD, SourceLocation TemplateLoc,
2175 SourceLocation LAngleLoc,
2176 ASTTemplateArgsPtr TemplateArgsIn,
2177 SourceLocation RAngleLoc,
2178 bool IsCtorOrDtorName) {
2179 if (SS.isInvalid())
2180 return true;
2181
2182 TemplateName Template = TemplateD.get();
2183
2184 // Translate the parser's template argument list in our AST format.
2185 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2186 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2187
2188 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2189 QualType T
2190 = Context.getDependentTemplateSpecializationType(ETK_None,
2191 DTN->getQualifier(),
2192 DTN->getIdentifier(),
2193 TemplateArgs);
2194 // Build type-source information.
2195 TypeLocBuilder TLB;
2196 DependentTemplateSpecializationTypeLoc SpecTL
2197 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2198 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2199 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2200 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2201 SpecTL.setTemplateNameLoc(TemplateLoc);
2202 SpecTL.setLAngleLoc(LAngleLoc);
2203 SpecTL.setRAngleLoc(RAngleLoc);
2204 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2205 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2206 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2207 }
2208
2209 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2210
2211 if (Result.isNull())
2212 return true;
2213
2214 // Build type-source information.
2215 TypeLocBuilder TLB;
2216 TemplateSpecializationTypeLoc SpecTL
2217 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2218 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2219 SpecTL.setTemplateNameLoc(TemplateLoc);
2220 SpecTL.setLAngleLoc(LAngleLoc);
2221 SpecTL.setRAngleLoc(RAngleLoc);
2222 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2223 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2224
2225 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2226 // constructor or destructor name (in such a case, the scope specifier
2227 // will be attached to the enclosing Decl or Expr node).
2228 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2229 // Create an elaborated-type-specifier containing the nested-name-specifier.
2230 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2231 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2232 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2233 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2234 }
2235
2236 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2237 }
2238
ActOnTagTemplateIdType(TagUseKind TUK,TypeSpecifierType TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)2239 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2240 TypeSpecifierType TagSpec,
2241 SourceLocation TagLoc,
2242 CXXScopeSpec &SS,
2243 SourceLocation TemplateKWLoc,
2244 TemplateTy TemplateD,
2245 SourceLocation TemplateLoc,
2246 SourceLocation LAngleLoc,
2247 ASTTemplateArgsPtr TemplateArgsIn,
2248 SourceLocation RAngleLoc) {
2249 TemplateName Template = TemplateD.get();
2250
2251 // Translate the parser's template argument list in our AST format.
2252 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2253 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2254
2255 // Determine the tag kind
2256 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2257 ElaboratedTypeKeyword Keyword
2258 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2259
2260 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2261 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2262 DTN->getQualifier(),
2263 DTN->getIdentifier(),
2264 TemplateArgs);
2265
2266 // Build type-source information.
2267 TypeLocBuilder TLB;
2268 DependentTemplateSpecializationTypeLoc SpecTL
2269 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2270 SpecTL.setElaboratedKeywordLoc(TagLoc);
2271 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2272 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2273 SpecTL.setTemplateNameLoc(TemplateLoc);
2274 SpecTL.setLAngleLoc(LAngleLoc);
2275 SpecTL.setRAngleLoc(RAngleLoc);
2276 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2277 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2278 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2279 }
2280
2281 if (TypeAliasTemplateDecl *TAT =
2282 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2283 // C++0x [dcl.type.elab]p2:
2284 // If the identifier resolves to a typedef-name or the simple-template-id
2285 // resolves to an alias template specialization, the
2286 // elaborated-type-specifier is ill-formed.
2287 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2288 Diag(TAT->getLocation(), diag::note_declared_at);
2289 }
2290
2291 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2292 if (Result.isNull())
2293 return TypeResult(true);
2294
2295 // Check the tag kind
2296 if (const RecordType *RT = Result->getAs<RecordType>()) {
2297 RecordDecl *D = RT->getDecl();
2298
2299 IdentifierInfo *Id = D->getIdentifier();
2300 assert(Id && "templated class must have an identifier");
2301
2302 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2303 TagLoc, *Id)) {
2304 Diag(TagLoc, diag::err_use_with_wrong_tag)
2305 << Result
2306 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2307 Diag(D->getLocation(), diag::note_previous_use);
2308 }
2309 }
2310
2311 // Provide source-location information for the template specialization.
2312 TypeLocBuilder TLB;
2313 TemplateSpecializationTypeLoc SpecTL
2314 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2315 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2316 SpecTL.setTemplateNameLoc(TemplateLoc);
2317 SpecTL.setLAngleLoc(LAngleLoc);
2318 SpecTL.setRAngleLoc(RAngleLoc);
2319 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2320 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2321
2322 // Construct an elaborated type containing the nested-name-specifier (if any)
2323 // and tag keyword.
2324 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2325 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2326 ElabTL.setElaboratedKeywordLoc(TagLoc);
2327 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2328 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2329 }
2330
2331 static bool CheckTemplatePartialSpecializationArgs(
2332 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2333 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2334
2335 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2336 NamedDecl *PrevDecl,
2337 SourceLocation Loc,
2338 bool IsPartialSpecialization);
2339
2340 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2341
isTemplateArgumentTemplateParameter(const TemplateArgument & Arg,unsigned Depth,unsigned Index)2342 static bool isTemplateArgumentTemplateParameter(
2343 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2344 switch (Arg.getKind()) {
2345 case TemplateArgument::Null:
2346 case TemplateArgument::NullPtr:
2347 case TemplateArgument::Integral:
2348 case TemplateArgument::Declaration:
2349 case TemplateArgument::Pack:
2350 case TemplateArgument::TemplateExpansion:
2351 return false;
2352
2353 case TemplateArgument::Type: {
2354 QualType Type = Arg.getAsType();
2355 const TemplateTypeParmType *TPT =
2356 Arg.getAsType()->getAs<TemplateTypeParmType>();
2357 return TPT && !Type.hasQualifiers() &&
2358 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2359 }
2360
2361 case TemplateArgument::Expression: {
2362 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2363 if (!DRE || !DRE->getDecl())
2364 return false;
2365 const NonTypeTemplateParmDecl *NTTP =
2366 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2367 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2368 }
2369
2370 case TemplateArgument::Template:
2371 const TemplateTemplateParmDecl *TTP =
2372 dyn_cast_or_null<TemplateTemplateParmDecl>(
2373 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2374 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2375 }
2376 llvm_unreachable("unexpected kind of template argument");
2377 }
2378
isSameAsPrimaryTemplate(TemplateParameterList * Params,ArrayRef<TemplateArgument> Args)2379 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2380 ArrayRef<TemplateArgument> Args) {
2381 if (Params->size() != Args.size())
2382 return false;
2383
2384 unsigned Depth = Params->getDepth();
2385
2386 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2387 TemplateArgument Arg = Args[I];
2388
2389 // If the parameter is a pack expansion, the argument must be a pack
2390 // whose only element is a pack expansion.
2391 if (Params->getParam(I)->isParameterPack()) {
2392 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2393 !Arg.pack_begin()->isPackExpansion())
2394 return false;
2395 Arg = Arg.pack_begin()->getPackExpansionPattern();
2396 }
2397
2398 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2399 return false;
2400 }
2401
2402 return true;
2403 }
2404
2405 /// Convert the parser's template argument list representation into our form.
2406 static TemplateArgumentListInfo
makeTemplateArgumentListInfo(Sema & S,TemplateIdAnnotation & TemplateId)2407 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2408 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2409 TemplateId.RAngleLoc);
2410 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2411 TemplateId.NumArgs);
2412 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2413 return TemplateArgs;
2414 }
2415
ActOnVarTemplateSpecialization(Scope * S,Declarator & D,TypeSourceInfo * DI,SourceLocation TemplateKWLoc,TemplateParameterList * TemplateParams,StorageClass SC,bool IsPartialSpecialization)2416 DeclResult Sema::ActOnVarTemplateSpecialization(
2417 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2418 TemplateParameterList *TemplateParams, StorageClass SC,
2419 bool IsPartialSpecialization) {
2420 // D must be variable template id.
2421 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2422 "Variable template specialization is declared with a template it.");
2423
2424 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2425 TemplateArgumentListInfo TemplateArgs =
2426 makeTemplateArgumentListInfo(*this, *TemplateId);
2427 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2428 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2429 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2430
2431 TemplateName Name = TemplateId->Template.get();
2432
2433 // The template-id must name a variable template.
2434 VarTemplateDecl *VarTemplate =
2435 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2436 if (!VarTemplate) {
2437 NamedDecl *FnTemplate;
2438 if (auto *OTS = Name.getAsOverloadedTemplate())
2439 FnTemplate = *OTS->begin();
2440 else
2441 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2442 if (FnTemplate)
2443 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2444 << FnTemplate->getDeclName();
2445 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2446 << IsPartialSpecialization;
2447 }
2448
2449 // Check for unexpanded parameter packs in any of the template arguments.
2450 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2451 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2452 UPPC_PartialSpecialization))
2453 return true;
2454
2455 // Check that the template argument list is well-formed for this
2456 // template.
2457 SmallVector<TemplateArgument, 4> Converted;
2458 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2459 false, Converted))
2460 return true;
2461
2462 // Check that the type of this variable template specialization
2463 // matches the expected type.
2464 TypeSourceInfo *ExpectedDI;
2465 {
2466 // Do substitution on the type of the declaration
2467 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2468 Converted.data(), Converted.size());
2469 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
2470 if (Inst.isInvalid())
2471 return true;
2472 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2473 ExpectedDI =
2474 SubstType(Templated->getTypeSourceInfo(),
2475 MultiLevelTemplateArgumentList(TemplateArgList),
2476 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2477 }
2478 if (!ExpectedDI)
2479 return true;
2480
2481 // Find the variable template (partial) specialization declaration that
2482 // corresponds to these arguments.
2483 if (IsPartialSpecialization) {
2484 if (CheckTemplatePartialSpecializationArgs(
2485 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2486 TemplateArgs.size(), Converted))
2487 return true;
2488
2489 bool InstantiationDependent;
2490 if (!Name.isDependent() &&
2491 !TemplateSpecializationType::anyDependentTemplateArguments(
2492 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2493 InstantiationDependent)) {
2494 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2495 << VarTemplate->getDeclName();
2496 IsPartialSpecialization = false;
2497 }
2498
2499 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2500 Converted)) {
2501 // C++ [temp.class.spec]p9b3:
2502 //
2503 // -- The argument list of the specialization shall not be identical
2504 // to the implicit argument list of the primary template.
2505 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2506 << /*variable template*/ 1
2507 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2508 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2509 // FIXME: Recover from this by treating the declaration as a redeclaration
2510 // of the primary template.
2511 return true;
2512 }
2513 }
2514
2515 void *InsertPos = nullptr;
2516 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2517
2518 if (IsPartialSpecialization)
2519 // FIXME: Template parameter list matters too
2520 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2521 else
2522 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2523
2524 VarTemplateSpecializationDecl *Specialization = nullptr;
2525
2526 // Check whether we can declare a variable template specialization in
2527 // the current scope.
2528 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2529 TemplateNameLoc,
2530 IsPartialSpecialization))
2531 return true;
2532
2533 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2534 // Since the only prior variable template specialization with these
2535 // arguments was referenced but not declared, reuse that
2536 // declaration node as our own, updating its source location and
2537 // the list of outer template parameters to reflect our new declaration.
2538 Specialization = PrevDecl;
2539 Specialization->setLocation(TemplateNameLoc);
2540 PrevDecl = nullptr;
2541 } else if (IsPartialSpecialization) {
2542 // Create a new class template partial specialization declaration node.
2543 VarTemplatePartialSpecializationDecl *PrevPartial =
2544 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2545 VarTemplatePartialSpecializationDecl *Partial =
2546 VarTemplatePartialSpecializationDecl::Create(
2547 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2548 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2549 Converted.data(), Converted.size(), TemplateArgs);
2550
2551 if (!PrevPartial)
2552 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2553 Specialization = Partial;
2554
2555 // If we are providing an explicit specialization of a member variable
2556 // template specialization, make a note of that.
2557 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2558 PrevPartial->setMemberSpecialization();
2559
2560 // Check that all of the template parameters of the variable template
2561 // partial specialization are deducible from the template
2562 // arguments. If not, this variable template partial specialization
2563 // will never be used.
2564 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2565 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2566 TemplateParams->getDepth(), DeducibleParams);
2567
2568 if (!DeducibleParams.all()) {
2569 unsigned NumNonDeducible =
2570 DeducibleParams.size() - DeducibleParams.count();
2571 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2572 << /*variable template*/ 1 << (NumNonDeducible > 1)
2573 << SourceRange(TemplateNameLoc, RAngleLoc);
2574 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2575 if (!DeducibleParams[I]) {
2576 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2577 if (Param->getDeclName())
2578 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2579 << Param->getDeclName();
2580 else
2581 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2582 << "(anonymous)";
2583 }
2584 }
2585 }
2586 } else {
2587 // Create a new class template specialization declaration node for
2588 // this explicit specialization or friend declaration.
2589 Specialization = VarTemplateSpecializationDecl::Create(
2590 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2591 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2592 Specialization->setTemplateArgsInfo(TemplateArgs);
2593
2594 if (!PrevDecl)
2595 VarTemplate->AddSpecialization(Specialization, InsertPos);
2596 }
2597
2598 // C++ [temp.expl.spec]p6:
2599 // If a template, a member template or the member of a class template is
2600 // explicitly specialized then that specialization shall be declared
2601 // before the first use of that specialization that would cause an implicit
2602 // instantiation to take place, in every translation unit in which such a
2603 // use occurs; no diagnostic is required.
2604 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2605 bool Okay = false;
2606 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2607 // Is there any previous explicit specialization declaration?
2608 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2609 Okay = true;
2610 break;
2611 }
2612 }
2613
2614 if (!Okay) {
2615 SourceRange Range(TemplateNameLoc, RAngleLoc);
2616 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2617 << Name << Range;
2618
2619 Diag(PrevDecl->getPointOfInstantiation(),
2620 diag::note_instantiation_required_here)
2621 << (PrevDecl->getTemplateSpecializationKind() !=
2622 TSK_ImplicitInstantiation);
2623 return true;
2624 }
2625 }
2626
2627 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2628 Specialization->setLexicalDeclContext(CurContext);
2629
2630 // Add the specialization into its lexical context, so that it can
2631 // be seen when iterating through the list of declarations in that
2632 // context. However, specializations are not found by name lookup.
2633 CurContext->addDecl(Specialization);
2634
2635 // Note that this is an explicit specialization.
2636 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2637
2638 if (PrevDecl) {
2639 // Check that this isn't a redefinition of this specialization,
2640 // merging with previous declarations.
2641 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2642 ForRedeclaration);
2643 PrevSpec.addDecl(PrevDecl);
2644 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2645 } else if (Specialization->isStaticDataMember() &&
2646 Specialization->isOutOfLine()) {
2647 Specialization->setAccess(VarTemplate->getAccess());
2648 }
2649
2650 // Link instantiations of static data members back to the template from
2651 // which they were instantiated.
2652 if (Specialization->isStaticDataMember())
2653 Specialization->setInstantiationOfStaticDataMember(
2654 VarTemplate->getTemplatedDecl(),
2655 Specialization->getSpecializationKind());
2656
2657 return Specialization;
2658 }
2659
2660 namespace {
2661 /// \brief A partial specialization whose template arguments have matched
2662 /// a given template-id.
2663 struct PartialSpecMatchResult {
2664 VarTemplatePartialSpecializationDecl *Partial;
2665 TemplateArgumentList *Args;
2666 };
2667 }
2668
2669 DeclResult
CheckVarTemplateId(VarTemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation TemplateNameLoc,const TemplateArgumentListInfo & TemplateArgs)2670 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2671 SourceLocation TemplateNameLoc,
2672 const TemplateArgumentListInfo &TemplateArgs) {
2673 assert(Template && "A variable template id without template?");
2674
2675 // Check that the template argument list is well-formed for this template.
2676 SmallVector<TemplateArgument, 4> Converted;
2677 if (CheckTemplateArgumentList(
2678 Template, TemplateNameLoc,
2679 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2680 Converted))
2681 return true;
2682
2683 // Find the variable template specialization declaration that
2684 // corresponds to these arguments.
2685 void *InsertPos = nullptr;
2686 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2687 Converted, InsertPos))
2688 // If we already have a variable template specialization, return it.
2689 return Spec;
2690
2691 // This is the first time we have referenced this variable template
2692 // specialization. Create the canonical declaration and add it to
2693 // the set of specializations, based on the closest partial specialization
2694 // that it represents. That is,
2695 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2696 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2697 Converted.data(), Converted.size());
2698 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2699 bool AmbiguousPartialSpec = false;
2700 typedef PartialSpecMatchResult MatchResult;
2701 SmallVector<MatchResult, 4> Matched;
2702 SourceLocation PointOfInstantiation = TemplateNameLoc;
2703 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2704
2705 // 1. Attempt to find the closest partial specialization that this
2706 // specializes, if any.
2707 // If any of the template arguments is dependent, then this is probably
2708 // a placeholder for an incomplete declarative context; which must be
2709 // complete by instantiation time. Thus, do not search through the partial
2710 // specializations yet.
2711 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2712 // Perhaps better after unification of DeduceTemplateArguments() and
2713 // getMoreSpecializedPartialSpecialization().
2714 bool InstantiationDependent = false;
2715 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2716 TemplateArgs, InstantiationDependent)) {
2717
2718 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2719 Template->getPartialSpecializations(PartialSpecs);
2720
2721 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2722 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2723 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2724
2725 if (TemplateDeductionResult Result =
2726 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2727 // Store the failed-deduction information for use in diagnostics, later.
2728 // TODO: Actually use the failed-deduction info?
2729 FailedCandidates.addCandidate()
2730 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2731 (void)Result;
2732 } else {
2733 Matched.push_back(PartialSpecMatchResult());
2734 Matched.back().Partial = Partial;
2735 Matched.back().Args = Info.take();
2736 }
2737 }
2738
2739 if (Matched.size() >= 1) {
2740 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2741 if (Matched.size() == 1) {
2742 // -- If exactly one matching specialization is found, the
2743 // instantiation is generated from that specialization.
2744 // We don't need to do anything for this.
2745 } else {
2746 // -- If more than one matching specialization is found, the
2747 // partial order rules (14.5.4.2) are used to determine
2748 // whether one of the specializations is more specialized
2749 // than the others. If none of the specializations is more
2750 // specialized than all of the other matching
2751 // specializations, then the use of the variable template is
2752 // ambiguous and the program is ill-formed.
2753 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2754 PEnd = Matched.end();
2755 P != PEnd; ++P) {
2756 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2757 PointOfInstantiation) ==
2758 P->Partial)
2759 Best = P;
2760 }
2761
2762 // Determine if the best partial specialization is more specialized than
2763 // the others.
2764 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2765 PEnd = Matched.end();
2766 P != PEnd; ++P) {
2767 if (P != Best && getMoreSpecializedPartialSpecialization(
2768 P->Partial, Best->Partial,
2769 PointOfInstantiation) != Best->Partial) {
2770 AmbiguousPartialSpec = true;
2771 break;
2772 }
2773 }
2774 }
2775
2776 // Instantiate using the best variable template partial specialization.
2777 InstantiationPattern = Best->Partial;
2778 InstantiationArgs = Best->Args;
2779 } else {
2780 // -- If no match is found, the instantiation is generated
2781 // from the primary template.
2782 // InstantiationPattern = Template->getTemplatedDecl();
2783 }
2784 }
2785
2786 // 2. Create the canonical declaration.
2787 // Note that we do not instantiate the variable just yet, since
2788 // instantiation is handled in DoMarkVarDeclReferenced().
2789 // FIXME: LateAttrs et al.?
2790 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2791 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2792 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2793 if (!Decl)
2794 return true;
2795
2796 if (AmbiguousPartialSpec) {
2797 // Partial ordering did not produce a clear winner. Complain.
2798 Decl->setInvalidDecl();
2799 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2800 << Decl;
2801
2802 // Print the matching partial specializations.
2803 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2804 PEnd = Matched.end();
2805 P != PEnd; ++P)
2806 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2807 << getTemplateArgumentBindingsText(
2808 P->Partial->getTemplateParameters(), *P->Args);
2809 return true;
2810 }
2811
2812 if (VarTemplatePartialSpecializationDecl *D =
2813 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2814 Decl->setInstantiationOf(D, InstantiationArgs);
2815
2816 assert(Decl && "No variable template specialization?");
2817 return Decl;
2818 }
2819
2820 ExprResult
CheckVarTemplateId(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,VarTemplateDecl * Template,SourceLocation TemplateLoc,const TemplateArgumentListInfo * TemplateArgs)2821 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2822 const DeclarationNameInfo &NameInfo,
2823 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2824 const TemplateArgumentListInfo *TemplateArgs) {
2825
2826 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2827 *TemplateArgs);
2828 if (Decl.isInvalid())
2829 return ExprError();
2830
2831 VarDecl *Var = cast<VarDecl>(Decl.get());
2832 if (!Var->getTemplateSpecializationKind())
2833 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2834 NameInfo.getLoc());
2835
2836 // Build an ordinary singleton decl ref.
2837 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2838 /*FoundD=*/nullptr, TemplateArgs);
2839 }
2840
BuildTemplateIdExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,bool RequiresADL,const TemplateArgumentListInfo * TemplateArgs)2841 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2842 SourceLocation TemplateKWLoc,
2843 LookupResult &R,
2844 bool RequiresADL,
2845 const TemplateArgumentListInfo *TemplateArgs) {
2846 // FIXME: Can we do any checking at this point? I guess we could check the
2847 // template arguments that we have against the template name, if the template
2848 // name refers to a single template. That's not a terribly common case,
2849 // though.
2850 // foo<int> could identify a single function unambiguously
2851 // This approach does NOT work, since f<int>(1);
2852 // gets resolved prior to resorting to overload resolution
2853 // i.e., template<class T> void f(double);
2854 // vs template<class T, class U> void f(U);
2855
2856 // These should be filtered out by our callers.
2857 assert(!R.empty() && "empty lookup results when building templateid");
2858 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2859
2860 // In C++1y, check variable template ids.
2861 bool InstantiationDependent;
2862 if (R.getAsSingle<VarTemplateDecl>() &&
2863 !TemplateSpecializationType::anyDependentTemplateArguments(
2864 *TemplateArgs, InstantiationDependent)) {
2865 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2866 R.getAsSingle<VarTemplateDecl>(),
2867 TemplateKWLoc, TemplateArgs);
2868 }
2869
2870 // We don't want lookup warnings at this point.
2871 R.suppressDiagnostics();
2872
2873 UnresolvedLookupExpr *ULE
2874 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2875 SS.getWithLocInContext(Context),
2876 TemplateKWLoc,
2877 R.getLookupNameInfo(),
2878 RequiresADL, TemplateArgs,
2879 R.begin(), R.end());
2880
2881 return ULE;
2882 }
2883
2884 // We actually only call this from template instantiation.
2885 ExprResult
BuildQualifiedTemplateIdExpr(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)2886 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2887 SourceLocation TemplateKWLoc,
2888 const DeclarationNameInfo &NameInfo,
2889 const TemplateArgumentListInfo *TemplateArgs) {
2890
2891 assert(TemplateArgs || TemplateKWLoc.isValid());
2892 DeclContext *DC;
2893 if (!(DC = computeDeclContext(SS, false)) ||
2894 DC->isDependentContext() ||
2895 RequireCompleteDeclContext(SS, DC))
2896 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2897
2898 bool MemberOfUnknownSpecialization;
2899 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2900 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2901 MemberOfUnknownSpecialization);
2902
2903 if (R.isAmbiguous())
2904 return ExprError();
2905
2906 if (R.empty()) {
2907 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2908 << NameInfo.getName() << SS.getRange();
2909 return ExprError();
2910 }
2911
2912 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2913 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2914 << SS.getScopeRep()
2915 << NameInfo.getName().getAsString() << SS.getRange();
2916 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2917 return ExprError();
2918 }
2919
2920 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2921 }
2922
2923 /// \brief Form a dependent template name.
2924 ///
2925 /// This action forms a dependent template name given the template
2926 /// name and its (presumably dependent) scope specifier. For
2927 /// example, given "MetaFun::template apply", the scope specifier \p
2928 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2929 /// of the "template" keyword, and "apply" is the \p Name.
ActOnDependentTemplateName(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Name,ParsedType ObjectType,bool EnteringContext,TemplateTy & Result)2930 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2931 CXXScopeSpec &SS,
2932 SourceLocation TemplateKWLoc,
2933 UnqualifiedId &Name,
2934 ParsedType ObjectType,
2935 bool EnteringContext,
2936 TemplateTy &Result) {
2937 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2938 Diag(TemplateKWLoc,
2939 getLangOpts().CPlusPlus11 ?
2940 diag::warn_cxx98_compat_template_outside_of_template :
2941 diag::ext_template_outside_of_template)
2942 << FixItHint::CreateRemoval(TemplateKWLoc);
2943
2944 DeclContext *LookupCtx = nullptr;
2945 if (SS.isSet())
2946 LookupCtx = computeDeclContext(SS, EnteringContext);
2947 if (!LookupCtx && ObjectType)
2948 LookupCtx = computeDeclContext(ObjectType.get());
2949 if (LookupCtx) {
2950 // C++0x [temp.names]p5:
2951 // If a name prefixed by the keyword template is not the name of
2952 // a template, the program is ill-formed. [Note: the keyword
2953 // template may not be applied to non-template members of class
2954 // templates. -end note ] [ Note: as is the case with the
2955 // typename prefix, the template prefix is allowed in cases
2956 // where it is not strictly necessary; i.e., when the
2957 // nested-name-specifier or the expression on the left of the ->
2958 // or . is not dependent on a template-parameter, or the use
2959 // does not appear in the scope of a template. -end note]
2960 //
2961 // Note: C++03 was more strict here, because it banned the use of
2962 // the "template" keyword prior to a template-name that was not a
2963 // dependent name. C++ DR468 relaxed this requirement (the
2964 // "template" keyword is now permitted). We follow the C++0x
2965 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2966 bool MemberOfUnknownSpecialization;
2967 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2968 ObjectType, EnteringContext, Result,
2969 MemberOfUnknownSpecialization);
2970 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2971 isa<CXXRecordDecl>(LookupCtx) &&
2972 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2973 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2974 // This is a dependent template. Handle it below.
2975 } else if (TNK == TNK_Non_template) {
2976 Diag(Name.getLocStart(),
2977 diag::err_template_kw_refers_to_non_template)
2978 << GetNameFromUnqualifiedId(Name).getName()
2979 << Name.getSourceRange()
2980 << TemplateKWLoc;
2981 return TNK_Non_template;
2982 } else {
2983 // We found something; return it.
2984 return TNK;
2985 }
2986 }
2987
2988 NestedNameSpecifier *Qualifier = SS.getScopeRep();
2989
2990 switch (Name.getKind()) {
2991 case UnqualifiedId::IK_Identifier:
2992 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2993 Name.Identifier));
2994 return TNK_Dependent_template_name;
2995
2996 case UnqualifiedId::IK_OperatorFunctionId:
2997 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2998 Name.OperatorFunctionId.Operator));
2999 return TNK_Function_template;
3000
3001 case UnqualifiedId::IK_LiteralOperatorId:
3002 llvm_unreachable("literal operator id cannot have a dependent scope");
3003
3004 default:
3005 break;
3006 }
3007
3008 Diag(Name.getLocStart(),
3009 diag::err_template_kw_refers_to_non_template)
3010 << GetNameFromUnqualifiedId(Name).getName()
3011 << Name.getSourceRange()
3012 << TemplateKWLoc;
3013 return TNK_Non_template;
3014 }
3015
CheckTemplateTypeArgument(TemplateTypeParmDecl * Param,TemplateArgumentLoc & AL,SmallVectorImpl<TemplateArgument> & Converted)3016 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3017 TemplateArgumentLoc &AL,
3018 SmallVectorImpl<TemplateArgument> &Converted) {
3019 const TemplateArgument &Arg = AL.getArgument();
3020 QualType ArgType;
3021 TypeSourceInfo *TSI = nullptr;
3022
3023 // Check template type parameter.
3024 switch(Arg.getKind()) {
3025 case TemplateArgument::Type:
3026 // C++ [temp.arg.type]p1:
3027 // A template-argument for a template-parameter which is a
3028 // type shall be a type-id.
3029 ArgType = Arg.getAsType();
3030 TSI = AL.getTypeSourceInfo();
3031 break;
3032 case TemplateArgument::Template: {
3033 // We have a template type parameter but the template argument
3034 // is a template without any arguments.
3035 SourceRange SR = AL.getSourceRange();
3036 TemplateName Name = Arg.getAsTemplate();
3037 Diag(SR.getBegin(), diag::err_template_missing_args)
3038 << Name << SR;
3039 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3040 Diag(Decl->getLocation(), diag::note_template_decl_here);
3041
3042 return true;
3043 }
3044 case TemplateArgument::Expression: {
3045 // We have a template type parameter but the template argument is an
3046 // expression; see if maybe it is missing the "typename" keyword.
3047 CXXScopeSpec SS;
3048 DeclarationNameInfo NameInfo;
3049
3050 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3051 SS.Adopt(ArgExpr->getQualifierLoc());
3052 NameInfo = ArgExpr->getNameInfo();
3053 } else if (DependentScopeDeclRefExpr *ArgExpr =
3054 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3055 SS.Adopt(ArgExpr->getQualifierLoc());
3056 NameInfo = ArgExpr->getNameInfo();
3057 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3058 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3059 if (ArgExpr->isImplicitAccess()) {
3060 SS.Adopt(ArgExpr->getQualifierLoc());
3061 NameInfo = ArgExpr->getMemberNameInfo();
3062 }
3063 }
3064
3065 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3066 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3067 LookupParsedName(Result, CurScope, &SS);
3068
3069 if (Result.getAsSingle<TypeDecl>() ||
3070 Result.getResultKind() ==
3071 LookupResult::NotFoundInCurrentInstantiation) {
3072 // Suggest that the user add 'typename' before the NNS.
3073 SourceLocation Loc = AL.getSourceRange().getBegin();
3074 Diag(Loc, getLangOpts().MSVCCompat
3075 ? diag::ext_ms_template_type_arg_missing_typename
3076 : diag::err_template_arg_must_be_type_suggest)
3077 << FixItHint::CreateInsertion(Loc, "typename ");
3078 Diag(Param->getLocation(), diag::note_template_param_here);
3079
3080 // Recover by synthesizing a type using the location information that we
3081 // already have.
3082 ArgType =
3083 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3084 TypeLocBuilder TLB;
3085 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3086 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3087 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3088 TL.setNameLoc(NameInfo.getLoc());
3089 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3090
3091 // Overwrite our input TemplateArgumentLoc so that we can recover
3092 // properly.
3093 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3094 TemplateArgumentLocInfo(TSI));
3095
3096 break;
3097 }
3098 }
3099 // fallthrough
3100 }
3101 default: {
3102 // We have a template type parameter but the template argument
3103 // is not a type.
3104 SourceRange SR = AL.getSourceRange();
3105 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3106 Diag(Param->getLocation(), diag::note_template_param_here);
3107
3108 return true;
3109 }
3110 }
3111
3112 if (CheckTemplateArgument(Param, TSI))
3113 return true;
3114
3115 // Add the converted template type argument.
3116 ArgType = Context.getCanonicalType(ArgType);
3117
3118 // Objective-C ARC:
3119 // If an explicitly-specified template argument type is a lifetime type
3120 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3121 if (getLangOpts().ObjCAutoRefCount &&
3122 ArgType->isObjCLifetimeType() &&
3123 !ArgType.getObjCLifetime()) {
3124 Qualifiers Qs;
3125 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3126 ArgType = Context.getQualifiedType(ArgType, Qs);
3127 }
3128
3129 Converted.push_back(TemplateArgument(ArgType));
3130 return false;
3131 }
3132
3133 /// \brief Substitute template arguments into the default template argument for
3134 /// the given template type parameter.
3135 ///
3136 /// \param SemaRef the semantic analysis object for which we are performing
3137 /// the substitution.
3138 ///
3139 /// \param Template the template that we are synthesizing template arguments
3140 /// for.
3141 ///
3142 /// \param TemplateLoc the location of the template name that started the
3143 /// template-id we are checking.
3144 ///
3145 /// \param RAngleLoc the location of the right angle bracket ('>') that
3146 /// terminates the template-id.
3147 ///
3148 /// \param Param the template template parameter whose default we are
3149 /// substituting into.
3150 ///
3151 /// \param Converted the list of template arguments provided for template
3152 /// parameters that precede \p Param in the template parameter list.
3153 /// \returns the substituted template argument, or NULL if an error occurred.
3154 static TypeSourceInfo *
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTypeParmDecl * Param,SmallVectorImpl<TemplateArgument> & Converted)3155 SubstDefaultTemplateArgument(Sema &SemaRef,
3156 TemplateDecl *Template,
3157 SourceLocation TemplateLoc,
3158 SourceLocation RAngleLoc,
3159 TemplateTypeParmDecl *Param,
3160 SmallVectorImpl<TemplateArgument> &Converted) {
3161 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3162
3163 // If the argument type is dependent, instantiate it now based
3164 // on the previously-computed template arguments.
3165 if (ArgType->getType()->isDependentType()) {
3166 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3167 Template, Converted,
3168 SourceRange(TemplateLoc, RAngleLoc));
3169 if (Inst.isInvalid())
3170 return nullptr;
3171
3172 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3173 Converted.data(), Converted.size());
3174
3175 // Only substitute for the innermost template argument list.
3176 MultiLevelTemplateArgumentList TemplateArgLists;
3177 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3178 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3179 TemplateArgLists.addOuterTemplateArguments(None);
3180
3181 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3182 ArgType =
3183 SemaRef.SubstType(ArgType, TemplateArgLists,
3184 Param->getDefaultArgumentLoc(), Param->getDeclName());
3185 }
3186
3187 return ArgType;
3188 }
3189
3190 /// \brief Substitute template arguments into the default template argument for
3191 /// the given non-type template parameter.
3192 ///
3193 /// \param SemaRef the semantic analysis object for which we are performing
3194 /// the substitution.
3195 ///
3196 /// \param Template the template that we are synthesizing template arguments
3197 /// for.
3198 ///
3199 /// \param TemplateLoc the location of the template name that started the
3200 /// template-id we are checking.
3201 ///
3202 /// \param RAngleLoc the location of the right angle bracket ('>') that
3203 /// terminates the template-id.
3204 ///
3205 /// \param Param the non-type template parameter whose default we are
3206 /// substituting into.
3207 ///
3208 /// \param Converted the list of template arguments provided for template
3209 /// parameters that precede \p Param in the template parameter list.
3210 ///
3211 /// \returns the substituted template argument, or NULL if an error occurred.
3212 static ExprResult
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,NonTypeTemplateParmDecl * Param,SmallVectorImpl<TemplateArgument> & Converted)3213 SubstDefaultTemplateArgument(Sema &SemaRef,
3214 TemplateDecl *Template,
3215 SourceLocation TemplateLoc,
3216 SourceLocation RAngleLoc,
3217 NonTypeTemplateParmDecl *Param,
3218 SmallVectorImpl<TemplateArgument> &Converted) {
3219 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3220 Template, Converted,
3221 SourceRange(TemplateLoc, RAngleLoc));
3222 if (Inst.isInvalid())
3223 return ExprError();
3224
3225 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3226 Converted.data(), Converted.size());
3227
3228 // Only substitute for the innermost template argument list.
3229 MultiLevelTemplateArgumentList TemplateArgLists;
3230 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3231 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3232 TemplateArgLists.addOuterTemplateArguments(None);
3233
3234 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3235 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3236 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3237 }
3238
3239 /// \brief Substitute template arguments into the default template argument for
3240 /// the given template template parameter.
3241 ///
3242 /// \param SemaRef the semantic analysis object for which we are performing
3243 /// the substitution.
3244 ///
3245 /// \param Template the template that we are synthesizing template arguments
3246 /// for.
3247 ///
3248 /// \param TemplateLoc the location of the template name that started the
3249 /// template-id we are checking.
3250 ///
3251 /// \param RAngleLoc the location of the right angle bracket ('>') that
3252 /// terminates the template-id.
3253 ///
3254 /// \param Param the template template parameter whose default we are
3255 /// substituting into.
3256 ///
3257 /// \param Converted the list of template arguments provided for template
3258 /// parameters that precede \p Param in the template parameter list.
3259 ///
3260 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3261 /// source-location information) that precedes the template name.
3262 ///
3263 /// \returns the substituted template argument, or NULL if an error occurred.
3264 static TemplateName
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTemplateParmDecl * Param,SmallVectorImpl<TemplateArgument> & Converted,NestedNameSpecifierLoc & QualifierLoc)3265 SubstDefaultTemplateArgument(Sema &SemaRef,
3266 TemplateDecl *Template,
3267 SourceLocation TemplateLoc,
3268 SourceLocation RAngleLoc,
3269 TemplateTemplateParmDecl *Param,
3270 SmallVectorImpl<TemplateArgument> &Converted,
3271 NestedNameSpecifierLoc &QualifierLoc) {
3272 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3273 SourceRange(TemplateLoc, RAngleLoc));
3274 if (Inst.isInvalid())
3275 return TemplateName();
3276
3277 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3278 Converted.data(), Converted.size());
3279
3280 // Only substitute for the innermost template argument list.
3281 MultiLevelTemplateArgumentList TemplateArgLists;
3282 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3283 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3284 TemplateArgLists.addOuterTemplateArguments(None);
3285
3286 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3287 // Substitute into the nested-name-specifier first,
3288 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3289 if (QualifierLoc) {
3290 QualifierLoc =
3291 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3292 if (!QualifierLoc)
3293 return TemplateName();
3294 }
3295
3296 return SemaRef.SubstTemplateName(
3297 QualifierLoc,
3298 Param->getDefaultArgument().getArgument().getAsTemplate(),
3299 Param->getDefaultArgument().getTemplateNameLoc(),
3300 TemplateArgLists);
3301 }
3302
3303 /// \brief If the given template parameter has a default template
3304 /// argument, substitute into that default template argument and
3305 /// return the corresponding template argument.
3306 TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,Decl * Param,SmallVectorImpl<TemplateArgument> & Converted,bool & HasDefaultArg)3307 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3308 SourceLocation TemplateLoc,
3309 SourceLocation RAngleLoc,
3310 Decl *Param,
3311 SmallVectorImpl<TemplateArgument>
3312 &Converted,
3313 bool &HasDefaultArg) {
3314 HasDefaultArg = false;
3315
3316 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3317 if (!TypeParm->hasDefaultArgument())
3318 return TemplateArgumentLoc();
3319
3320 HasDefaultArg = true;
3321 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3322 TemplateLoc,
3323 RAngleLoc,
3324 TypeParm,
3325 Converted);
3326 if (DI)
3327 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3328
3329 return TemplateArgumentLoc();
3330 }
3331
3332 if (NonTypeTemplateParmDecl *NonTypeParm
3333 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3334 if (!NonTypeParm->hasDefaultArgument())
3335 return TemplateArgumentLoc();
3336
3337 HasDefaultArg = true;
3338 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3339 TemplateLoc,
3340 RAngleLoc,
3341 NonTypeParm,
3342 Converted);
3343 if (Arg.isInvalid())
3344 return TemplateArgumentLoc();
3345
3346 Expr *ArgE = Arg.getAs<Expr>();
3347 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3348 }
3349
3350 TemplateTemplateParmDecl *TempTempParm
3351 = cast<TemplateTemplateParmDecl>(Param);
3352 if (!TempTempParm->hasDefaultArgument())
3353 return TemplateArgumentLoc();
3354
3355 HasDefaultArg = true;
3356 NestedNameSpecifierLoc QualifierLoc;
3357 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3358 TemplateLoc,
3359 RAngleLoc,
3360 TempTempParm,
3361 Converted,
3362 QualifierLoc);
3363 if (TName.isNull())
3364 return TemplateArgumentLoc();
3365
3366 return TemplateArgumentLoc(TemplateArgument(TName),
3367 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3368 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3369 }
3370
3371 /// \brief Check that the given template argument corresponds to the given
3372 /// template parameter.
3373 ///
3374 /// \param Param The template parameter against which the argument will be
3375 /// checked.
3376 ///
3377 /// \param Arg The template argument, which may be updated due to conversions.
3378 ///
3379 /// \param Template The template in which the template argument resides.
3380 ///
3381 /// \param TemplateLoc The location of the template name for the template
3382 /// whose argument list we're matching.
3383 ///
3384 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3385 /// the template argument list.
3386 ///
3387 /// \param ArgumentPackIndex The index into the argument pack where this
3388 /// argument will be placed. Only valid if the parameter is a parameter pack.
3389 ///
3390 /// \param Converted The checked, converted argument will be added to the
3391 /// end of this small vector.
3392 ///
3393 /// \param CTAK Describes how we arrived at this particular template argument:
3394 /// explicitly written, deduced, etc.
3395 ///
3396 /// \returns true on error, false otherwise.
CheckTemplateArgument(NamedDecl * Param,TemplateArgumentLoc & Arg,NamedDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,unsigned ArgumentPackIndex,SmallVectorImpl<TemplateArgument> & Converted,CheckTemplateArgumentKind CTAK)3397 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3398 TemplateArgumentLoc &Arg,
3399 NamedDecl *Template,
3400 SourceLocation TemplateLoc,
3401 SourceLocation RAngleLoc,
3402 unsigned ArgumentPackIndex,
3403 SmallVectorImpl<TemplateArgument> &Converted,
3404 CheckTemplateArgumentKind CTAK) {
3405 // Check template type parameters.
3406 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3407 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3408
3409 // Check non-type template parameters.
3410 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3411 // Do substitution on the type of the non-type template parameter
3412 // with the template arguments we've seen thus far. But if the
3413 // template has a dependent context then we cannot substitute yet.
3414 QualType NTTPType = NTTP->getType();
3415 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3416 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3417
3418 if (NTTPType->isDependentType() &&
3419 !isa<TemplateTemplateParmDecl>(Template) &&
3420 !Template->getDeclContext()->isDependentContext()) {
3421 // Do substitution on the type of the non-type template parameter.
3422 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3423 NTTP, Converted,
3424 SourceRange(TemplateLoc, RAngleLoc));
3425 if (Inst.isInvalid())
3426 return true;
3427
3428 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3429 Converted.data(), Converted.size());
3430 NTTPType = SubstType(NTTPType,
3431 MultiLevelTemplateArgumentList(TemplateArgs),
3432 NTTP->getLocation(),
3433 NTTP->getDeclName());
3434 // If that worked, check the non-type template parameter type
3435 // for validity.
3436 if (!NTTPType.isNull())
3437 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3438 NTTP->getLocation());
3439 if (NTTPType.isNull())
3440 return true;
3441 }
3442
3443 switch (Arg.getArgument().getKind()) {
3444 case TemplateArgument::Null:
3445 llvm_unreachable("Should never see a NULL template argument here");
3446
3447 case TemplateArgument::Expression: {
3448 TemplateArgument Result;
3449 ExprResult Res =
3450 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3451 Result, CTAK);
3452 if (Res.isInvalid())
3453 return true;
3454
3455 // If the resulting expression is new, then use it in place of the
3456 // old expression in the template argument.
3457 if (Res.get() != Arg.getArgument().getAsExpr()) {
3458 TemplateArgument TA(Res.get());
3459 Arg = TemplateArgumentLoc(TA, Res.get());
3460 }
3461
3462 Converted.push_back(Result);
3463 break;
3464 }
3465
3466 case TemplateArgument::Declaration:
3467 case TemplateArgument::Integral:
3468 case TemplateArgument::NullPtr:
3469 // We've already checked this template argument, so just copy
3470 // it to the list of converted arguments.
3471 Converted.push_back(Arg.getArgument());
3472 break;
3473
3474 case TemplateArgument::Template:
3475 case TemplateArgument::TemplateExpansion:
3476 // We were given a template template argument. It may not be ill-formed;
3477 // see below.
3478 if (DependentTemplateName *DTN
3479 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3480 .getAsDependentTemplateName()) {
3481 // We have a template argument such as \c T::template X, which we
3482 // parsed as a template template argument. However, since we now
3483 // know that we need a non-type template argument, convert this
3484 // template name into an expression.
3485
3486 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3487 Arg.getTemplateNameLoc());
3488
3489 CXXScopeSpec SS;
3490 SS.Adopt(Arg.getTemplateQualifierLoc());
3491 // FIXME: the template-template arg was a DependentTemplateName,
3492 // so it was provided with a template keyword. However, its source
3493 // location is not stored in the template argument structure.
3494 SourceLocation TemplateKWLoc;
3495 ExprResult E = DependentScopeDeclRefExpr::Create(
3496 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3497 nullptr);
3498
3499 // If we parsed the template argument as a pack expansion, create a
3500 // pack expansion expression.
3501 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3502 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3503 if (E.isInvalid())
3504 return true;
3505 }
3506
3507 TemplateArgument Result;
3508 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3509 if (E.isInvalid())
3510 return true;
3511
3512 Converted.push_back(Result);
3513 break;
3514 }
3515
3516 // We have a template argument that actually does refer to a class
3517 // template, alias template, or template template parameter, and
3518 // therefore cannot be a non-type template argument.
3519 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3520 << Arg.getSourceRange();
3521
3522 Diag(Param->getLocation(), diag::note_template_param_here);
3523 return true;
3524
3525 case TemplateArgument::Type: {
3526 // We have a non-type template parameter but the template
3527 // argument is a type.
3528
3529 // C++ [temp.arg]p2:
3530 // In a template-argument, an ambiguity between a type-id and
3531 // an expression is resolved to a type-id, regardless of the
3532 // form of the corresponding template-parameter.
3533 //
3534 // We warn specifically about this case, since it can be rather
3535 // confusing for users.
3536 QualType T = Arg.getArgument().getAsType();
3537 SourceRange SR = Arg.getSourceRange();
3538 if (T->isFunctionType())
3539 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3540 else
3541 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3542 Diag(Param->getLocation(), diag::note_template_param_here);
3543 return true;
3544 }
3545
3546 case TemplateArgument::Pack:
3547 llvm_unreachable("Caller must expand template argument packs");
3548 }
3549
3550 return false;
3551 }
3552
3553
3554 // Check template template parameters.
3555 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3556
3557 // Substitute into the template parameter list of the template
3558 // template parameter, since previously-supplied template arguments
3559 // may appear within the template template parameter.
3560 {
3561 // Set up a template instantiation context.
3562 LocalInstantiationScope Scope(*this);
3563 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3564 TempParm, Converted,
3565 SourceRange(TemplateLoc, RAngleLoc));
3566 if (Inst.isInvalid())
3567 return true;
3568
3569 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3570 Converted.data(), Converted.size());
3571 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3572 SubstDecl(TempParm, CurContext,
3573 MultiLevelTemplateArgumentList(TemplateArgs)));
3574 if (!TempParm)
3575 return true;
3576 }
3577
3578 switch (Arg.getArgument().getKind()) {
3579 case TemplateArgument::Null:
3580 llvm_unreachable("Should never see a NULL template argument here");
3581
3582 case TemplateArgument::Template:
3583 case TemplateArgument::TemplateExpansion:
3584 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3585 return true;
3586
3587 Converted.push_back(Arg.getArgument());
3588 break;
3589
3590 case TemplateArgument::Expression:
3591 case TemplateArgument::Type:
3592 // We have a template template parameter but the template
3593 // argument does not refer to a template.
3594 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3595 << getLangOpts().CPlusPlus11;
3596 return true;
3597
3598 case TemplateArgument::Declaration:
3599 llvm_unreachable("Declaration argument with template template parameter");
3600 case TemplateArgument::Integral:
3601 llvm_unreachable("Integral argument with template template parameter");
3602 case TemplateArgument::NullPtr:
3603 llvm_unreachable("Null pointer argument with template template parameter");
3604
3605 case TemplateArgument::Pack:
3606 llvm_unreachable("Caller must expand template argument packs");
3607 }
3608
3609 return false;
3610 }
3611
3612 /// \brief Diagnose an arity mismatch in the
diagnoseArityMismatch(Sema & S,TemplateDecl * Template,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3613 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3614 SourceLocation TemplateLoc,
3615 TemplateArgumentListInfo &TemplateArgs) {
3616 TemplateParameterList *Params = Template->getTemplateParameters();
3617 unsigned NumParams = Params->size();
3618 unsigned NumArgs = TemplateArgs.size();
3619
3620 SourceRange Range;
3621 if (NumArgs > NumParams)
3622 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3623 TemplateArgs.getRAngleLoc());
3624 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3625 << (NumArgs > NumParams)
3626 << (isa<ClassTemplateDecl>(Template)? 0 :
3627 isa<FunctionTemplateDecl>(Template)? 1 :
3628 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3629 << Template << Range;
3630 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3631 << Params->getSourceRange();
3632 return true;
3633 }
3634
3635 /// \brief Check whether the template parameter is a pack expansion, and if so,
3636 /// determine the number of parameters produced by that expansion. For instance:
3637 ///
3638 /// \code
3639 /// template<typename ...Ts> struct A {
3640 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3641 /// };
3642 /// \endcode
3643 ///
3644 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3645 /// is not a pack expansion, so returns an empty Optional.
getExpandedPackSize(NamedDecl * Param)3646 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3647 if (NonTypeTemplateParmDecl *NTTP
3648 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3649 if (NTTP->isExpandedParameterPack())
3650 return NTTP->getNumExpansionTypes();
3651 }
3652
3653 if (TemplateTemplateParmDecl *TTP
3654 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3655 if (TTP->isExpandedParameterPack())
3656 return TTP->getNumExpansionTemplateParameters();
3657 }
3658
3659 return None;
3660 }
3661
3662 /// \brief Check that the given template argument list is well-formed
3663 /// for specializing the given template.
CheckTemplateArgumentList(TemplateDecl * Template,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs,bool PartialTemplateArgs,SmallVectorImpl<TemplateArgument> & Converted)3664 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3665 SourceLocation TemplateLoc,
3666 TemplateArgumentListInfo &TemplateArgs,
3667 bool PartialTemplateArgs,
3668 SmallVectorImpl<TemplateArgument> &Converted) {
3669 // Make a copy of the template arguments for processing. Only make the
3670 // changes at the end when successful in matching the arguments to the
3671 // template.
3672 TemplateArgumentListInfo NewArgs = TemplateArgs;
3673
3674 TemplateParameterList *Params = Template->getTemplateParameters();
3675
3676 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3677
3678 // C++ [temp.arg]p1:
3679 // [...] The type and form of each template-argument specified in
3680 // a template-id shall match the type and form specified for the
3681 // corresponding parameter declared by the template in its
3682 // template-parameter-list.
3683 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3684 SmallVector<TemplateArgument, 2> ArgumentPack;
3685 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3686 LocalInstantiationScope InstScope(*this, true);
3687 for (TemplateParameterList::iterator Param = Params->begin(),
3688 ParamEnd = Params->end();
3689 Param != ParamEnd; /* increment in loop */) {
3690 // If we have an expanded parameter pack, make sure we don't have too
3691 // many arguments.
3692 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3693 if (*Expansions == ArgumentPack.size()) {
3694 // We're done with this parameter pack. Pack up its arguments and add
3695 // them to the list.
3696 Converted.push_back(
3697 TemplateArgument::CreatePackCopy(Context,
3698 ArgumentPack.data(),
3699 ArgumentPack.size()));
3700 ArgumentPack.clear();
3701
3702 // This argument is assigned to the next parameter.
3703 ++Param;
3704 continue;
3705 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3706 // Not enough arguments for this parameter pack.
3707 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3708 << false
3709 << (isa<ClassTemplateDecl>(Template)? 0 :
3710 isa<FunctionTemplateDecl>(Template)? 1 :
3711 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3712 << Template;
3713 Diag(Template->getLocation(), diag::note_template_decl_here)
3714 << Params->getSourceRange();
3715 return true;
3716 }
3717 }
3718
3719 if (ArgIdx < NumArgs) {
3720 // Check the template argument we were given.
3721 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3722 TemplateLoc, RAngleLoc,
3723 ArgumentPack.size(), Converted))
3724 return true;
3725
3726 bool PackExpansionIntoNonPack =
3727 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3728 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3729 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3730 // Core issue 1430: we have a pack expansion as an argument to an
3731 // alias template, and it's not part of a parameter pack. This
3732 // can't be canonicalized, so reject it now.
3733 Diag(NewArgs[ArgIdx].getLocation(),
3734 diag::err_alias_template_expansion_into_fixed_list)
3735 << NewArgs[ArgIdx].getSourceRange();
3736 Diag((*Param)->getLocation(), diag::note_template_param_here);
3737 return true;
3738 }
3739
3740 // We're now done with this argument.
3741 ++ArgIdx;
3742
3743 if ((*Param)->isTemplateParameterPack()) {
3744 // The template parameter was a template parameter pack, so take the
3745 // deduced argument and place it on the argument pack. Note that we
3746 // stay on the same template parameter so that we can deduce more
3747 // arguments.
3748 ArgumentPack.push_back(Converted.pop_back_val());
3749 } else {
3750 // Move to the next template parameter.
3751 ++Param;
3752 }
3753
3754 // If we just saw a pack expansion into a non-pack, then directly convert
3755 // the remaining arguments, because we don't know what parameters they'll
3756 // match up with.
3757 if (PackExpansionIntoNonPack) {
3758 if (!ArgumentPack.empty()) {
3759 // If we were part way through filling in an expanded parameter pack,
3760 // fall back to just producing individual arguments.
3761 Converted.insert(Converted.end(),
3762 ArgumentPack.begin(), ArgumentPack.end());
3763 ArgumentPack.clear();
3764 }
3765
3766 while (ArgIdx < NumArgs) {
3767 Converted.push_back(NewArgs[ArgIdx].getArgument());
3768 ++ArgIdx;
3769 }
3770
3771 return false;
3772 }
3773
3774 continue;
3775 }
3776
3777 // If we're checking a partial template argument list, we're done.
3778 if (PartialTemplateArgs) {
3779 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3780 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3781 ArgumentPack.data(),
3782 ArgumentPack.size()));
3783
3784 return false;
3785 }
3786
3787 // If we have a template parameter pack with no more corresponding
3788 // arguments, just break out now and we'll fill in the argument pack below.
3789 if ((*Param)->isTemplateParameterPack()) {
3790 assert(!getExpandedPackSize(*Param) &&
3791 "Should have dealt with this already");
3792
3793 // A non-expanded parameter pack before the end of the parameter list
3794 // only occurs for an ill-formed template parameter list, unless we've
3795 // got a partial argument list for a function template, so just bail out.
3796 if (Param + 1 != ParamEnd)
3797 return true;
3798
3799 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3800 ArgumentPack.data(),
3801 ArgumentPack.size()));
3802 ArgumentPack.clear();
3803
3804 ++Param;
3805 continue;
3806 }
3807
3808 // Check whether we have a default argument.
3809 TemplateArgumentLoc Arg;
3810
3811 // Retrieve the default template argument from the template
3812 // parameter. For each kind of template parameter, we substitute the
3813 // template arguments provided thus far and any "outer" template arguments
3814 // (when the template parameter was part of a nested template) into
3815 // the default argument.
3816 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3817 if (!TTP->hasDefaultArgument())
3818 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3819
3820 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3821 Template,
3822 TemplateLoc,
3823 RAngleLoc,
3824 TTP,
3825 Converted);
3826 if (!ArgType)
3827 return true;
3828
3829 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3830 ArgType);
3831 } else if (NonTypeTemplateParmDecl *NTTP
3832 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3833 if (!NTTP->hasDefaultArgument())
3834 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3835
3836 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3837 TemplateLoc,
3838 RAngleLoc,
3839 NTTP,
3840 Converted);
3841 if (E.isInvalid())
3842 return true;
3843
3844 Expr *Ex = E.getAs<Expr>();
3845 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3846 } else {
3847 TemplateTemplateParmDecl *TempParm
3848 = cast<TemplateTemplateParmDecl>(*Param);
3849
3850 if (!TempParm->hasDefaultArgument())
3851 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3852
3853 NestedNameSpecifierLoc QualifierLoc;
3854 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3855 TemplateLoc,
3856 RAngleLoc,
3857 TempParm,
3858 Converted,
3859 QualifierLoc);
3860 if (Name.isNull())
3861 return true;
3862
3863 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3864 TempParm->getDefaultArgument().getTemplateNameLoc());
3865 }
3866
3867 // Introduce an instantiation record that describes where we are using
3868 // the default template argument.
3869 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3870 SourceRange(TemplateLoc, RAngleLoc));
3871 if (Inst.isInvalid())
3872 return true;
3873
3874 // Check the default template argument.
3875 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3876 RAngleLoc, 0, Converted))
3877 return true;
3878
3879 // Core issue 150 (assumed resolution): if this is a template template
3880 // parameter, keep track of the default template arguments from the
3881 // template definition.
3882 if (isTemplateTemplateParameter)
3883 NewArgs.addArgument(Arg);
3884
3885 // Move to the next template parameter and argument.
3886 ++Param;
3887 ++ArgIdx;
3888 }
3889
3890 // If we're performing a partial argument substitution, allow any trailing
3891 // pack expansions; they might be empty. This can happen even if
3892 // PartialTemplateArgs is false (the list of arguments is complete but
3893 // still dependent).
3894 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3895 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3896 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3897 Converted.push_back(NewArgs[ArgIdx++].getArgument());
3898 }
3899
3900 // If we have any leftover arguments, then there were too many arguments.
3901 // Complain and fail.
3902 if (ArgIdx < NumArgs)
3903 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3904
3905 // No problems found with the new argument list, propagate changes back
3906 // to caller.
3907 TemplateArgs = NewArgs;
3908
3909 return false;
3910 }
3911
3912 namespace {
3913 class UnnamedLocalNoLinkageFinder
3914 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3915 {
3916 Sema &S;
3917 SourceRange SR;
3918
3919 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3920
3921 public:
UnnamedLocalNoLinkageFinder(Sema & S,SourceRange SR)3922 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3923
Visit(QualType T)3924 bool Visit(QualType T) {
3925 return inherited::Visit(T.getTypePtr());
3926 }
3927
3928 #define TYPE(Class, Parent) \
3929 bool Visit##Class##Type(const Class##Type *);
3930 #define ABSTRACT_TYPE(Class, Parent) \
3931 bool Visit##Class##Type(const Class##Type *) { return false; }
3932 #define NON_CANONICAL_TYPE(Class, Parent) \
3933 bool Visit##Class##Type(const Class##Type *) { return false; }
3934 #include "clang/AST/TypeNodes.def"
3935
3936 bool VisitTagDecl(const TagDecl *Tag);
3937 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3938 };
3939 }
3940
VisitBuiltinType(const BuiltinType *)3941 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3942 return false;
3943 }
3944
VisitComplexType(const ComplexType * T)3945 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3946 return Visit(T->getElementType());
3947 }
3948
VisitPointerType(const PointerType * T)3949 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3950 return Visit(T->getPointeeType());
3951 }
3952
VisitBlockPointerType(const BlockPointerType * T)3953 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3954 const BlockPointerType* T) {
3955 return Visit(T->getPointeeType());
3956 }
3957
VisitLValueReferenceType(const LValueReferenceType * T)3958 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3959 const LValueReferenceType* T) {
3960 return Visit(T->getPointeeType());
3961 }
3962
VisitRValueReferenceType(const RValueReferenceType * T)3963 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3964 const RValueReferenceType* T) {
3965 return Visit(T->getPointeeType());
3966 }
3967
VisitMemberPointerType(const MemberPointerType * T)3968 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3969 const MemberPointerType* T) {
3970 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3971 }
3972
VisitConstantArrayType(const ConstantArrayType * T)3973 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3974 const ConstantArrayType* T) {
3975 return Visit(T->getElementType());
3976 }
3977
VisitIncompleteArrayType(const IncompleteArrayType * T)3978 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3979 const IncompleteArrayType* T) {
3980 return Visit(T->getElementType());
3981 }
3982
VisitVariableArrayType(const VariableArrayType * T)3983 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3984 const VariableArrayType* T) {
3985 return Visit(T->getElementType());
3986 }
3987
VisitDependentSizedArrayType(const DependentSizedArrayType * T)3988 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3989 const DependentSizedArrayType* T) {
3990 return Visit(T->getElementType());
3991 }
3992
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)3993 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3994 const DependentSizedExtVectorType* T) {
3995 return Visit(T->getElementType());
3996 }
3997
VisitVectorType(const VectorType * T)3998 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3999 return Visit(T->getElementType());
4000 }
4001
VisitExtVectorType(const ExtVectorType * T)4002 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4003 return Visit(T->getElementType());
4004 }
4005
VisitFunctionProtoType(const FunctionProtoType * T)4006 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4007 const FunctionProtoType* T) {
4008 for (const auto &A : T->param_types()) {
4009 if (Visit(A))
4010 return true;
4011 }
4012
4013 return Visit(T->getReturnType());
4014 }
4015
VisitFunctionNoProtoType(const FunctionNoProtoType * T)4016 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4017 const FunctionNoProtoType* T) {
4018 return Visit(T->getReturnType());
4019 }
4020
VisitUnresolvedUsingType(const UnresolvedUsingType *)4021 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4022 const UnresolvedUsingType*) {
4023 return false;
4024 }
4025
VisitTypeOfExprType(const TypeOfExprType *)4026 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4027 return false;
4028 }
4029
VisitTypeOfType(const TypeOfType * T)4030 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4031 return Visit(T->getUnderlyingType());
4032 }
4033
VisitDecltypeType(const DecltypeType *)4034 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4035 return false;
4036 }
4037
VisitUnaryTransformType(const UnaryTransformType *)4038 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4039 const UnaryTransformType*) {
4040 return false;
4041 }
4042
VisitAutoType(const AutoType * T)4043 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4044 return Visit(T->getDeducedType());
4045 }
4046
VisitRecordType(const RecordType * T)4047 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4048 return VisitTagDecl(T->getDecl());
4049 }
4050
VisitEnumType(const EnumType * T)4051 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4052 return VisitTagDecl(T->getDecl());
4053 }
4054
VisitTemplateTypeParmType(const TemplateTypeParmType *)4055 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4056 const TemplateTypeParmType*) {
4057 return false;
4058 }
4059
VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *)4060 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4061 const SubstTemplateTypeParmPackType *) {
4062 return false;
4063 }
4064
VisitTemplateSpecializationType(const TemplateSpecializationType *)4065 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4066 const TemplateSpecializationType*) {
4067 return false;
4068 }
4069
VisitInjectedClassNameType(const InjectedClassNameType * T)4070 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4071 const InjectedClassNameType* T) {
4072 return VisitTagDecl(T->getDecl());
4073 }
4074
VisitDependentNameType(const DependentNameType * T)4075 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4076 const DependentNameType* T) {
4077 return VisitNestedNameSpecifier(T->getQualifier());
4078 }
4079
VisitDependentTemplateSpecializationType(const DependentTemplateSpecializationType * T)4080 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4081 const DependentTemplateSpecializationType* T) {
4082 return VisitNestedNameSpecifier(T->getQualifier());
4083 }
4084
VisitPackExpansionType(const PackExpansionType * T)4085 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4086 const PackExpansionType* T) {
4087 return Visit(T->getPattern());
4088 }
4089
VisitObjCObjectType(const ObjCObjectType *)4090 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4091 return false;
4092 }
4093
VisitObjCInterfaceType(const ObjCInterfaceType *)4094 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4095 const ObjCInterfaceType *) {
4096 return false;
4097 }
4098
VisitObjCObjectPointerType(const ObjCObjectPointerType *)4099 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4100 const ObjCObjectPointerType *) {
4101 return false;
4102 }
4103
VisitAtomicType(const AtomicType * T)4104 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4105 return Visit(T->getValueType());
4106 }
4107
VisitTagDecl(const TagDecl * Tag)4108 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4109 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4110 S.Diag(SR.getBegin(),
4111 S.getLangOpts().CPlusPlus11 ?
4112 diag::warn_cxx98_compat_template_arg_local_type :
4113 diag::ext_template_arg_local_type)
4114 << S.Context.getTypeDeclType(Tag) << SR;
4115 return true;
4116 }
4117
4118 if (!Tag->hasNameForLinkage()) {
4119 S.Diag(SR.getBegin(),
4120 S.getLangOpts().CPlusPlus11 ?
4121 diag::warn_cxx98_compat_template_arg_unnamed_type :
4122 diag::ext_template_arg_unnamed_type) << SR;
4123 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4124 return true;
4125 }
4126
4127 return false;
4128 }
4129
VisitNestedNameSpecifier(NestedNameSpecifier * NNS)4130 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4131 NestedNameSpecifier *NNS) {
4132 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4133 return true;
4134
4135 switch (NNS->getKind()) {
4136 case NestedNameSpecifier::Identifier:
4137 case NestedNameSpecifier::Namespace:
4138 case NestedNameSpecifier::NamespaceAlias:
4139 case NestedNameSpecifier::Global:
4140 case NestedNameSpecifier::Super:
4141 return false;
4142
4143 case NestedNameSpecifier::TypeSpec:
4144 case NestedNameSpecifier::TypeSpecWithTemplate:
4145 return Visit(QualType(NNS->getAsType(), 0));
4146 }
4147 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4148 }
4149
4150
4151 /// \brief Check a template argument against its corresponding
4152 /// template type parameter.
4153 ///
4154 /// This routine implements the semantics of C++ [temp.arg.type]. It
4155 /// returns true if an error occurred, and false otherwise.
CheckTemplateArgument(TemplateTypeParmDecl * Param,TypeSourceInfo * ArgInfo)4156 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4157 TypeSourceInfo *ArgInfo) {
4158 assert(ArgInfo && "invalid TypeSourceInfo");
4159 QualType Arg = ArgInfo->getType();
4160 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4161
4162 if (Arg->isVariablyModifiedType()) {
4163 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4164 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4165 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4166 }
4167
4168 // C++03 [temp.arg.type]p2:
4169 // A local type, a type with no linkage, an unnamed type or a type
4170 // compounded from any of these types shall not be used as a
4171 // template-argument for a template type-parameter.
4172 //
4173 // C++11 allows these, and even in C++03 we allow them as an extension with
4174 // a warning.
4175 bool NeedsCheck;
4176 if (LangOpts.CPlusPlus11)
4177 NeedsCheck =
4178 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4179 SR.getBegin()) ||
4180 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4181 SR.getBegin());
4182 else
4183 NeedsCheck = Arg->hasUnnamedOrLocalType();
4184
4185 if (NeedsCheck) {
4186 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4187 (void)Finder.Visit(Context.getCanonicalType(Arg));
4188 }
4189
4190 return false;
4191 }
4192
4193 enum NullPointerValueKind {
4194 NPV_NotNullPointer,
4195 NPV_NullPointer,
4196 NPV_Error
4197 };
4198
4199 /// \brief Determine whether the given template argument is a null pointer
4200 /// value of the appropriate type.
4201 static NullPointerValueKind
isNullPointerValueTemplateArgument(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg)4202 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4203 QualType ParamType, Expr *Arg) {
4204 if (Arg->isValueDependent() || Arg->isTypeDependent())
4205 return NPV_NotNullPointer;
4206
4207 if (!S.getLangOpts().CPlusPlus11)
4208 return NPV_NotNullPointer;
4209
4210 // Determine whether we have a constant expression.
4211 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4212 if (ArgRV.isInvalid())
4213 return NPV_Error;
4214 Arg = ArgRV.get();
4215
4216 Expr::EvalResult EvalResult;
4217 SmallVector<PartialDiagnosticAt, 8> Notes;
4218 EvalResult.Diag = &Notes;
4219 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4220 EvalResult.HasSideEffects) {
4221 SourceLocation DiagLoc = Arg->getExprLoc();
4222
4223 // If our only note is the usual "invalid subexpression" note, just point
4224 // the caret at its location rather than producing an essentially
4225 // redundant note.
4226 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4227 diag::note_invalid_subexpr_in_const_expr) {
4228 DiagLoc = Notes[0].first;
4229 Notes.clear();
4230 }
4231
4232 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4233 << Arg->getType() << Arg->getSourceRange();
4234 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4235 S.Diag(Notes[I].first, Notes[I].second);
4236
4237 S.Diag(Param->getLocation(), diag::note_template_param_here);
4238 return NPV_Error;
4239 }
4240
4241 // C++11 [temp.arg.nontype]p1:
4242 // - an address constant expression of type std::nullptr_t
4243 if (Arg->getType()->isNullPtrType())
4244 return NPV_NullPointer;
4245
4246 // - a constant expression that evaluates to a null pointer value (4.10); or
4247 // - a constant expression that evaluates to a null member pointer value
4248 // (4.11); or
4249 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4250 (EvalResult.Val.isMemberPointer() &&
4251 !EvalResult.Val.getMemberPointerDecl())) {
4252 // If our expression has an appropriate type, we've succeeded.
4253 bool ObjCLifetimeConversion;
4254 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4255 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4256 ObjCLifetimeConversion))
4257 return NPV_NullPointer;
4258
4259 // The types didn't match, but we know we got a null pointer; complain,
4260 // then recover as if the types were correct.
4261 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4262 << Arg->getType() << ParamType << Arg->getSourceRange();
4263 S.Diag(Param->getLocation(), diag::note_template_param_here);
4264 return NPV_NullPointer;
4265 }
4266
4267 // If we don't have a null pointer value, but we do have a NULL pointer
4268 // constant, suggest a cast to the appropriate type.
4269 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4270 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4271 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4272 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4273 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4274 ")");
4275 S.Diag(Param->getLocation(), diag::note_template_param_here);
4276 return NPV_NullPointer;
4277 }
4278
4279 // FIXME: If we ever want to support general, address-constant expressions
4280 // as non-type template arguments, we should return the ExprResult here to
4281 // be interpreted by the caller.
4282 return NPV_NotNullPointer;
4283 }
4284
4285 /// \brief Checks whether the given template argument is compatible with its
4286 /// template parameter.
CheckTemplateArgumentIsCompatibleWithParameter(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,Expr * Arg,QualType ArgType)4287 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4288 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4289 Expr *Arg, QualType ArgType) {
4290 bool ObjCLifetimeConversion;
4291 if (ParamType->isPointerType() &&
4292 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4293 S.IsQualificationConversion(ArgType, ParamType, false,
4294 ObjCLifetimeConversion)) {
4295 // For pointer-to-object types, qualification conversions are
4296 // permitted.
4297 } else {
4298 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4299 if (!ParamRef->getPointeeType()->isFunctionType()) {
4300 // C++ [temp.arg.nontype]p5b3:
4301 // For a non-type template-parameter of type reference to
4302 // object, no conversions apply. The type referred to by the
4303 // reference may be more cv-qualified than the (otherwise
4304 // identical) type of the template- argument. The
4305 // template-parameter is bound directly to the
4306 // template-argument, which shall be an lvalue.
4307
4308 // FIXME: Other qualifiers?
4309 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4310 unsigned ArgQuals = ArgType.getCVRQualifiers();
4311
4312 if ((ParamQuals | ArgQuals) != ParamQuals) {
4313 S.Diag(Arg->getLocStart(),
4314 diag::err_template_arg_ref_bind_ignores_quals)
4315 << ParamType << Arg->getType() << Arg->getSourceRange();
4316 S.Diag(Param->getLocation(), diag::note_template_param_here);
4317 return true;
4318 }
4319 }
4320 }
4321
4322 // At this point, the template argument refers to an object or
4323 // function with external linkage. We now need to check whether the
4324 // argument and parameter types are compatible.
4325 if (!S.Context.hasSameUnqualifiedType(ArgType,
4326 ParamType.getNonReferenceType())) {
4327 // We can't perform this conversion or binding.
4328 if (ParamType->isReferenceType())
4329 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4330 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4331 else
4332 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4333 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4334 S.Diag(Param->getLocation(), diag::note_template_param_here);
4335 return true;
4336 }
4337 }
4338
4339 return false;
4340 }
4341
4342 /// \brief Checks whether the given template argument is the address
4343 /// of an object or function according to C++ [temp.arg.nontype]p1.
4344 static bool
CheckTemplateArgumentAddressOfObjectOrFunction(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,TemplateArgument & Converted)4345 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4346 NonTypeTemplateParmDecl *Param,
4347 QualType ParamType,
4348 Expr *ArgIn,
4349 TemplateArgument &Converted) {
4350 bool Invalid = false;
4351 Expr *Arg = ArgIn;
4352 QualType ArgType = Arg->getType();
4353
4354 bool AddressTaken = false;
4355 SourceLocation AddrOpLoc;
4356 if (S.getLangOpts().MicrosoftExt) {
4357 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4358 // dereference and address-of operators.
4359 Arg = Arg->IgnoreParenCasts();
4360
4361 bool ExtWarnMSTemplateArg = false;
4362 UnaryOperatorKind FirstOpKind;
4363 SourceLocation FirstOpLoc;
4364 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4365 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4366 if (UnOpKind == UO_Deref)
4367 ExtWarnMSTemplateArg = true;
4368 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4369 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4370 if (!AddrOpLoc.isValid()) {
4371 FirstOpKind = UnOpKind;
4372 FirstOpLoc = UnOp->getOperatorLoc();
4373 }
4374 } else
4375 break;
4376 }
4377 if (FirstOpLoc.isValid()) {
4378 if (ExtWarnMSTemplateArg)
4379 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4380 << ArgIn->getSourceRange();
4381
4382 if (FirstOpKind == UO_AddrOf)
4383 AddressTaken = true;
4384 else if (Arg->getType()->isPointerType()) {
4385 // We cannot let pointers get dereferenced here, that is obviously not a
4386 // constant expression.
4387 assert(FirstOpKind == UO_Deref);
4388 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4389 << Arg->getSourceRange();
4390 }
4391 }
4392 } else {
4393 // See through any implicit casts we added to fix the type.
4394 Arg = Arg->IgnoreImpCasts();
4395
4396 // C++ [temp.arg.nontype]p1:
4397 //
4398 // A template-argument for a non-type, non-template
4399 // template-parameter shall be one of: [...]
4400 //
4401 // -- the address of an object or function with external
4402 // linkage, including function templates and function
4403 // template-ids but excluding non-static class members,
4404 // expressed as & id-expression where the & is optional if
4405 // the name refers to a function or array, or if the
4406 // corresponding template-parameter is a reference; or
4407
4408 // In C++98/03 mode, give an extension warning on any extra parentheses.
4409 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4410 bool ExtraParens = false;
4411 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4412 if (!Invalid && !ExtraParens) {
4413 S.Diag(Arg->getLocStart(),
4414 S.getLangOpts().CPlusPlus11
4415 ? diag::warn_cxx98_compat_template_arg_extra_parens
4416 : diag::ext_template_arg_extra_parens)
4417 << Arg->getSourceRange();
4418 ExtraParens = true;
4419 }
4420
4421 Arg = Parens->getSubExpr();
4422 }
4423
4424 while (SubstNonTypeTemplateParmExpr *subst =
4425 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4426 Arg = subst->getReplacement()->IgnoreImpCasts();
4427
4428 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4429 if (UnOp->getOpcode() == UO_AddrOf) {
4430 Arg = UnOp->getSubExpr();
4431 AddressTaken = true;
4432 AddrOpLoc = UnOp->getOperatorLoc();
4433 }
4434 }
4435
4436 while (SubstNonTypeTemplateParmExpr *subst =
4437 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4438 Arg = subst->getReplacement()->IgnoreImpCasts();
4439 }
4440
4441 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4442 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4443
4444 // If our parameter has pointer type, check for a null template value.
4445 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4446 NullPointerValueKind NPV;
4447 // dllimport'd entities aren't constant but are available inside of template
4448 // arguments.
4449 if (Entity && Entity->hasAttr<DLLImportAttr>())
4450 NPV = NPV_NotNullPointer;
4451 else
4452 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4453 switch (NPV) {
4454 case NPV_NullPointer:
4455 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4456 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4457 /*isNullPtr=*/true);
4458 return false;
4459
4460 case NPV_Error:
4461 return true;
4462
4463 case NPV_NotNullPointer:
4464 break;
4465 }
4466 }
4467
4468 // Stop checking the precise nature of the argument if it is value dependent,
4469 // it should be checked when instantiated.
4470 if (Arg->isValueDependent()) {
4471 Converted = TemplateArgument(ArgIn);
4472 return false;
4473 }
4474
4475 if (isa<CXXUuidofExpr>(Arg)) {
4476 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4477 ArgIn, Arg, ArgType))
4478 return true;
4479
4480 Converted = TemplateArgument(ArgIn);
4481 return false;
4482 }
4483
4484 if (!DRE) {
4485 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4486 << Arg->getSourceRange();
4487 S.Diag(Param->getLocation(), diag::note_template_param_here);
4488 return true;
4489 }
4490
4491 // Cannot refer to non-static data members
4492 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4493 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4494 << Entity << Arg->getSourceRange();
4495 S.Diag(Param->getLocation(), diag::note_template_param_here);
4496 return true;
4497 }
4498
4499 // Cannot refer to non-static member functions
4500 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4501 if (!Method->isStatic()) {
4502 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4503 << Method << Arg->getSourceRange();
4504 S.Diag(Param->getLocation(), diag::note_template_param_here);
4505 return true;
4506 }
4507 }
4508
4509 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4510 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4511
4512 // A non-type template argument must refer to an object or function.
4513 if (!Func && !Var) {
4514 // We found something, but we don't know specifically what it is.
4515 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4516 << Arg->getSourceRange();
4517 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4518 return true;
4519 }
4520
4521 // Address / reference template args must have external linkage in C++98.
4522 if (Entity->getFormalLinkage() == InternalLinkage) {
4523 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4524 diag::warn_cxx98_compat_template_arg_object_internal :
4525 diag::ext_template_arg_object_internal)
4526 << !Func << Entity << Arg->getSourceRange();
4527 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4528 << !Func;
4529 } else if (!Entity->hasLinkage()) {
4530 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4531 << !Func << Entity << Arg->getSourceRange();
4532 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4533 << !Func;
4534 return true;
4535 }
4536
4537 if (Func) {
4538 // If the template parameter has pointer type, the function decays.
4539 if (ParamType->isPointerType() && !AddressTaken)
4540 ArgType = S.Context.getPointerType(Func->getType());
4541 else if (AddressTaken && ParamType->isReferenceType()) {
4542 // If we originally had an address-of operator, but the
4543 // parameter has reference type, complain and (if things look
4544 // like they will work) drop the address-of operator.
4545 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4546 ParamType.getNonReferenceType())) {
4547 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4548 << ParamType;
4549 S.Diag(Param->getLocation(), diag::note_template_param_here);
4550 return true;
4551 }
4552
4553 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4554 << ParamType
4555 << FixItHint::CreateRemoval(AddrOpLoc);
4556 S.Diag(Param->getLocation(), diag::note_template_param_here);
4557
4558 ArgType = Func->getType();
4559 }
4560 } else {
4561 // A value of reference type is not an object.
4562 if (Var->getType()->isReferenceType()) {
4563 S.Diag(Arg->getLocStart(),
4564 diag::err_template_arg_reference_var)
4565 << Var->getType() << Arg->getSourceRange();
4566 S.Diag(Param->getLocation(), diag::note_template_param_here);
4567 return true;
4568 }
4569
4570 // A template argument must have static storage duration.
4571 if (Var->getTLSKind()) {
4572 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4573 << Arg->getSourceRange();
4574 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4575 return true;
4576 }
4577
4578 // If the template parameter has pointer type, we must have taken
4579 // the address of this object.
4580 if (ParamType->isReferenceType()) {
4581 if (AddressTaken) {
4582 // If we originally had an address-of operator, but the
4583 // parameter has reference type, complain and (if things look
4584 // like they will work) drop the address-of operator.
4585 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4586 ParamType.getNonReferenceType())) {
4587 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4588 << ParamType;
4589 S.Diag(Param->getLocation(), diag::note_template_param_here);
4590 return true;
4591 }
4592
4593 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4594 << ParamType
4595 << FixItHint::CreateRemoval(AddrOpLoc);
4596 S.Diag(Param->getLocation(), diag::note_template_param_here);
4597
4598 ArgType = Var->getType();
4599 }
4600 } else if (!AddressTaken && ParamType->isPointerType()) {
4601 if (Var->getType()->isArrayType()) {
4602 // Array-to-pointer decay.
4603 ArgType = S.Context.getArrayDecayedType(Var->getType());
4604 } else {
4605 // If the template parameter has pointer type but the address of
4606 // this object was not taken, complain and (possibly) recover by
4607 // taking the address of the entity.
4608 ArgType = S.Context.getPointerType(Var->getType());
4609 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4610 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4611 << ParamType;
4612 S.Diag(Param->getLocation(), diag::note_template_param_here);
4613 return true;
4614 }
4615
4616 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4617 << ParamType
4618 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4619
4620 S.Diag(Param->getLocation(), diag::note_template_param_here);
4621 }
4622 }
4623 }
4624
4625 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4626 Arg, ArgType))
4627 return true;
4628
4629 // Create the template argument.
4630 Converted =
4631 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4632 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4633 return false;
4634 }
4635
4636 /// \brief Checks whether the given template argument is a pointer to
4637 /// member constant according to C++ [temp.arg.nontype]p1.
CheckTemplateArgumentPointerToMember(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * & ResultArg,TemplateArgument & Converted)4638 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4639 NonTypeTemplateParmDecl *Param,
4640 QualType ParamType,
4641 Expr *&ResultArg,
4642 TemplateArgument &Converted) {
4643 bool Invalid = false;
4644
4645 // Check for a null pointer value.
4646 Expr *Arg = ResultArg;
4647 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4648 case NPV_Error:
4649 return true;
4650 case NPV_NullPointer:
4651 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4652 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4653 /*isNullPtr*/true);
4654 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4655 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
4656 return false;
4657 case NPV_NotNullPointer:
4658 break;
4659 }
4660
4661 bool ObjCLifetimeConversion;
4662 if (S.IsQualificationConversion(Arg->getType(),
4663 ParamType.getNonReferenceType(),
4664 false, ObjCLifetimeConversion)) {
4665 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4666 Arg->getValueKind()).get();
4667 ResultArg = Arg;
4668 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4669 ParamType.getNonReferenceType())) {
4670 // We can't perform this conversion.
4671 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4672 << Arg->getType() << ParamType << Arg->getSourceRange();
4673 S.Diag(Param->getLocation(), diag::note_template_param_here);
4674 return true;
4675 }
4676
4677 // See through any implicit casts we added to fix the type.
4678 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4679 Arg = Cast->getSubExpr();
4680
4681 // C++ [temp.arg.nontype]p1:
4682 //
4683 // A template-argument for a non-type, non-template
4684 // template-parameter shall be one of: [...]
4685 //
4686 // -- a pointer to member expressed as described in 5.3.1.
4687 DeclRefExpr *DRE = nullptr;
4688
4689 // In C++98/03 mode, give an extension warning on any extra parentheses.
4690 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4691 bool ExtraParens = false;
4692 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4693 if (!Invalid && !ExtraParens) {
4694 S.Diag(Arg->getLocStart(),
4695 S.getLangOpts().CPlusPlus11 ?
4696 diag::warn_cxx98_compat_template_arg_extra_parens :
4697 diag::ext_template_arg_extra_parens)
4698 << Arg->getSourceRange();
4699 ExtraParens = true;
4700 }
4701
4702 Arg = Parens->getSubExpr();
4703 }
4704
4705 while (SubstNonTypeTemplateParmExpr *subst =
4706 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4707 Arg = subst->getReplacement()->IgnoreImpCasts();
4708
4709 // A pointer-to-member constant written &Class::member.
4710 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4711 if (UnOp->getOpcode() == UO_AddrOf) {
4712 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4713 if (DRE && !DRE->getQualifier())
4714 DRE = nullptr;
4715 }
4716 }
4717 // A constant of pointer-to-member type.
4718 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4719 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4720 if (VD->getType()->isMemberPointerType()) {
4721 if (isa<NonTypeTemplateParmDecl>(VD)) {
4722 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4723 Converted = TemplateArgument(Arg);
4724 } else {
4725 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4726 Converted = TemplateArgument(VD, ParamType);
4727 }
4728 return Invalid;
4729 }
4730 }
4731 }
4732
4733 DRE = nullptr;
4734 }
4735
4736 if (!DRE)
4737 return S.Diag(Arg->getLocStart(),
4738 diag::err_template_arg_not_pointer_to_member_form)
4739 << Arg->getSourceRange();
4740
4741 if (isa<FieldDecl>(DRE->getDecl()) ||
4742 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4743 isa<CXXMethodDecl>(DRE->getDecl())) {
4744 assert((isa<FieldDecl>(DRE->getDecl()) ||
4745 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4746 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4747 "Only non-static member pointers can make it here");
4748
4749 // Okay: this is the address of a non-static member, and therefore
4750 // a member pointer constant.
4751 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4752 Converted = TemplateArgument(Arg);
4753 } else {
4754 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4755 Converted = TemplateArgument(D, ParamType);
4756 }
4757 return Invalid;
4758 }
4759
4760 // We found something else, but we don't know specifically what it is.
4761 S.Diag(Arg->getLocStart(),
4762 diag::err_template_arg_not_pointer_to_member_form)
4763 << Arg->getSourceRange();
4764 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4765 return true;
4766 }
4767
4768 /// \brief Check a template argument against its corresponding
4769 /// non-type template parameter.
4770 ///
4771 /// This routine implements the semantics of C++ [temp.arg.nontype].
4772 /// If an error occurred, it returns ExprError(); otherwise, it
4773 /// returns the converted template argument. \p ParamType is the
4774 /// type of the non-type template parameter after it has been instantiated.
CheckTemplateArgument(NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg,TemplateArgument & Converted,CheckTemplateArgumentKind CTAK)4775 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4776 QualType ParamType, Expr *Arg,
4777 TemplateArgument &Converted,
4778 CheckTemplateArgumentKind CTAK) {
4779 SourceLocation StartLoc = Arg->getLocStart();
4780
4781 // If either the parameter has a dependent type or the argument is
4782 // type-dependent, there's nothing we can check now.
4783 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4784 // FIXME: Produce a cloned, canonical expression?
4785 Converted = TemplateArgument(Arg);
4786 return Arg;
4787 }
4788
4789 // We should have already dropped all cv-qualifiers by now.
4790 assert(!ParamType.hasQualifiers() &&
4791 "non-type template parameter type cannot be qualified");
4792
4793 if (CTAK == CTAK_Deduced &&
4794 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4795 // C++ [temp.deduct.type]p17:
4796 // If, in the declaration of a function template with a non-type
4797 // template-parameter, the non-type template-parameter is used
4798 // in an expression in the function parameter-list and, if the
4799 // corresponding template-argument is deduced, the
4800 // template-argument type shall match the type of the
4801 // template-parameter exactly, except that a template-argument
4802 // deduced from an array bound may be of any integral type.
4803 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4804 << Arg->getType().getUnqualifiedType()
4805 << ParamType.getUnqualifiedType();
4806 Diag(Param->getLocation(), diag::note_template_param_here);
4807 return ExprError();
4808 }
4809
4810 if (getLangOpts().CPlusPlus1z) {
4811 // FIXME: We can do some limited checking for a value-dependent but not
4812 // type-dependent argument.
4813 if (Arg->isValueDependent()) {
4814 Converted = TemplateArgument(Arg);
4815 return Arg;
4816 }
4817
4818 // C++1z [temp.arg.nontype]p1:
4819 // A template-argument for a non-type template parameter shall be
4820 // a converted constant expression of the type of the template-parameter.
4821 APValue Value;
4822 ExprResult ArgResult = CheckConvertedConstantExpression(
4823 Arg, ParamType, Value, CCEK_TemplateArg);
4824 if (ArgResult.isInvalid())
4825 return ExprError();
4826
4827 QualType CanonParamType = Context.getCanonicalType(ParamType);
4828
4829 // Convert the APValue to a TemplateArgument.
4830 switch (Value.getKind()) {
4831 case APValue::Uninitialized:
4832 assert(ParamType->isNullPtrType());
4833 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4834 break;
4835 case APValue::Int:
4836 assert(ParamType->isIntegralOrEnumerationType());
4837 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4838 break;
4839 case APValue::MemberPointer: {
4840 assert(ParamType->isMemberPointerType());
4841
4842 // FIXME: We need TemplateArgument representation and mangling for these.
4843 if (!Value.getMemberPointerPath().empty()) {
4844 Diag(Arg->getLocStart(),
4845 diag::err_template_arg_member_ptr_base_derived_not_supported)
4846 << Value.getMemberPointerDecl() << ParamType
4847 << Arg->getSourceRange();
4848 return ExprError();
4849 }
4850
4851 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4852 Converted = VD ? TemplateArgument(VD, CanonParamType)
4853 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4854 break;
4855 }
4856 case APValue::LValue: {
4857 // For a non-type template-parameter of pointer or reference type,
4858 // the value of the constant expression shall not refer to
4859 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4860 ParamType->isNullPtrType());
4861 // -- a temporary object
4862 // -- a string literal
4863 // -- the result of a typeid expression, or
4864 // -- a predefind __func__ variable
4865 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4866 if (isa<CXXUuidofExpr>(E)) {
4867 Converted = TemplateArgument(const_cast<Expr*>(E));
4868 break;
4869 }
4870 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4871 << Arg->getSourceRange();
4872 return ExprError();
4873 }
4874 auto *VD = const_cast<ValueDecl *>(
4875 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4876 // -- a subobject
4877 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4878 VD && VD->getType()->isArrayType() &&
4879 Value.getLValuePath()[0].ArrayIndex == 0 &&
4880 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4881 // Per defect report (no number yet):
4882 // ... other than a pointer to the first element of a complete array
4883 // object.
4884 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4885 Value.isLValueOnePastTheEnd()) {
4886 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4887 << Value.getAsString(Context, ParamType);
4888 return ExprError();
4889 }
4890 assert((VD || !ParamType->isReferenceType()) &&
4891 "null reference should not be a constant expression");
4892 assert((!VD || !ParamType->isNullPtrType()) &&
4893 "non-null value of type nullptr_t?");
4894 Converted = VD ? TemplateArgument(VD, CanonParamType)
4895 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4896 break;
4897 }
4898 case APValue::AddrLabelDiff:
4899 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4900 case APValue::Float:
4901 case APValue::ComplexInt:
4902 case APValue::ComplexFloat:
4903 case APValue::Vector:
4904 case APValue::Array:
4905 case APValue::Struct:
4906 case APValue::Union:
4907 llvm_unreachable("invalid kind for template argument");
4908 }
4909
4910 return ArgResult.get();
4911 }
4912
4913 // C++ [temp.arg.nontype]p5:
4914 // The following conversions are performed on each expression used
4915 // as a non-type template-argument. If a non-type
4916 // template-argument cannot be converted to the type of the
4917 // corresponding template-parameter then the program is
4918 // ill-formed.
4919 if (ParamType->isIntegralOrEnumerationType()) {
4920 // C++11:
4921 // -- for a non-type template-parameter of integral or
4922 // enumeration type, conversions permitted in a converted
4923 // constant expression are applied.
4924 //
4925 // C++98:
4926 // -- for a non-type template-parameter of integral or
4927 // enumeration type, integral promotions (4.5) and integral
4928 // conversions (4.7) are applied.
4929
4930 if (getLangOpts().CPlusPlus11) {
4931 // We can't check arbitrary value-dependent arguments.
4932 // FIXME: If there's no viable conversion to the template parameter type,
4933 // we should be able to diagnose that prior to instantiation.
4934 if (Arg->isValueDependent()) {
4935 Converted = TemplateArgument(Arg);
4936 return Arg;
4937 }
4938
4939 // C++ [temp.arg.nontype]p1:
4940 // A template-argument for a non-type, non-template template-parameter
4941 // shall be one of:
4942 //
4943 // -- for a non-type template-parameter of integral or enumeration
4944 // type, a converted constant expression of the type of the
4945 // template-parameter; or
4946 llvm::APSInt Value;
4947 ExprResult ArgResult =
4948 CheckConvertedConstantExpression(Arg, ParamType, Value,
4949 CCEK_TemplateArg);
4950 if (ArgResult.isInvalid())
4951 return ExprError();
4952
4953 // Widen the argument value to sizeof(parameter type). This is almost
4954 // always a no-op, except when the parameter type is bool. In
4955 // that case, this may extend the argument from 1 bit to 8 bits.
4956 QualType IntegerType = ParamType;
4957 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4958 IntegerType = Enum->getDecl()->getIntegerType();
4959 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4960
4961 Converted = TemplateArgument(Context, Value,
4962 Context.getCanonicalType(ParamType));
4963 return ArgResult;
4964 }
4965
4966 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4967 if (ArgResult.isInvalid())
4968 return ExprError();
4969 Arg = ArgResult.get();
4970
4971 QualType ArgType = Arg->getType();
4972
4973 // C++ [temp.arg.nontype]p1:
4974 // A template-argument for a non-type, non-template
4975 // template-parameter shall be one of:
4976 //
4977 // -- an integral constant-expression of integral or enumeration
4978 // type; or
4979 // -- the name of a non-type template-parameter; or
4980 SourceLocation NonConstantLoc;
4981 llvm::APSInt Value;
4982 if (!ArgType->isIntegralOrEnumerationType()) {
4983 Diag(Arg->getLocStart(),
4984 diag::err_template_arg_not_integral_or_enumeral)
4985 << ArgType << Arg->getSourceRange();
4986 Diag(Param->getLocation(), diag::note_template_param_here);
4987 return ExprError();
4988 } else if (!Arg->isValueDependent()) {
4989 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4990 QualType T;
4991
4992 public:
4993 TmplArgICEDiagnoser(QualType T) : T(T) { }
4994
4995 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4996 SourceRange SR) override {
4997 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4998 }
4999 } Diagnoser(ArgType);
5000
5001 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5002 false).get();
5003 if (!Arg)
5004 return ExprError();
5005 }
5006
5007 // From here on out, all we care about is the unqualified form
5008 // of the argument type.
5009 ArgType = ArgType.getUnqualifiedType();
5010
5011 // Try to convert the argument to the parameter's type.
5012 if (Context.hasSameType(ParamType, ArgType)) {
5013 // Okay: no conversion necessary
5014 } else if (ParamType->isBooleanType()) {
5015 // This is an integral-to-boolean conversion.
5016 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5017 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5018 !ParamType->isEnumeralType()) {
5019 // This is an integral promotion or conversion.
5020 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5021 } else {
5022 // We can't perform this conversion.
5023 Diag(Arg->getLocStart(),
5024 diag::err_template_arg_not_convertible)
5025 << Arg->getType() << ParamType << Arg->getSourceRange();
5026 Diag(Param->getLocation(), diag::note_template_param_here);
5027 return ExprError();
5028 }
5029
5030 // Add the value of this argument to the list of converted
5031 // arguments. We use the bitwidth and signedness of the template
5032 // parameter.
5033 if (Arg->isValueDependent()) {
5034 // The argument is value-dependent. Create a new
5035 // TemplateArgument with the converted expression.
5036 Converted = TemplateArgument(Arg);
5037 return Arg;
5038 }
5039
5040 QualType IntegerType = Context.getCanonicalType(ParamType);
5041 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5042 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5043
5044 if (ParamType->isBooleanType()) {
5045 // Value must be zero or one.
5046 Value = Value != 0;
5047 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5048 if (Value.getBitWidth() != AllowedBits)
5049 Value = Value.extOrTrunc(AllowedBits);
5050 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5051 } else {
5052 llvm::APSInt OldValue = Value;
5053
5054 // Coerce the template argument's value to the value it will have
5055 // based on the template parameter's type.
5056 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5057 if (Value.getBitWidth() != AllowedBits)
5058 Value = Value.extOrTrunc(AllowedBits);
5059 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5060
5061 // Complain if an unsigned parameter received a negative value.
5062 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5063 && (OldValue.isSigned() && OldValue.isNegative())) {
5064 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5065 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5066 << Arg->getSourceRange();
5067 Diag(Param->getLocation(), diag::note_template_param_here);
5068 }
5069
5070 // Complain if we overflowed the template parameter's type.
5071 unsigned RequiredBits;
5072 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5073 RequiredBits = OldValue.getActiveBits();
5074 else if (OldValue.isUnsigned())
5075 RequiredBits = OldValue.getActiveBits() + 1;
5076 else
5077 RequiredBits = OldValue.getMinSignedBits();
5078 if (RequiredBits > AllowedBits) {
5079 Diag(Arg->getLocStart(),
5080 diag::warn_template_arg_too_large)
5081 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5082 << Arg->getSourceRange();
5083 Diag(Param->getLocation(), diag::note_template_param_here);
5084 }
5085 }
5086
5087 Converted = TemplateArgument(Context, Value,
5088 ParamType->isEnumeralType()
5089 ? Context.getCanonicalType(ParamType)
5090 : IntegerType);
5091 return Arg;
5092 }
5093
5094 QualType ArgType = Arg->getType();
5095 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5096
5097 // Handle pointer-to-function, reference-to-function, and
5098 // pointer-to-member-function all in (roughly) the same way.
5099 if (// -- For a non-type template-parameter of type pointer to
5100 // function, only the function-to-pointer conversion (4.3) is
5101 // applied. If the template-argument represents a set of
5102 // overloaded functions (or a pointer to such), the matching
5103 // function is selected from the set (13.4).
5104 (ParamType->isPointerType() &&
5105 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5106 // -- For a non-type template-parameter of type reference to
5107 // function, no conversions apply. If the template-argument
5108 // represents a set of overloaded functions, the matching
5109 // function is selected from the set (13.4).
5110 (ParamType->isReferenceType() &&
5111 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5112 // -- For a non-type template-parameter of type pointer to
5113 // member function, no conversions apply. If the
5114 // template-argument represents a set of overloaded member
5115 // functions, the matching member function is selected from
5116 // the set (13.4).
5117 (ParamType->isMemberPointerType() &&
5118 ParamType->getAs<MemberPointerType>()->getPointeeType()
5119 ->isFunctionType())) {
5120
5121 if (Arg->getType() == Context.OverloadTy) {
5122 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5123 true,
5124 FoundResult)) {
5125 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5126 return ExprError();
5127
5128 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5129 ArgType = Arg->getType();
5130 } else
5131 return ExprError();
5132 }
5133
5134 if (!ParamType->isMemberPointerType()) {
5135 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5136 ParamType,
5137 Arg, Converted))
5138 return ExprError();
5139 return Arg;
5140 }
5141
5142 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5143 Converted))
5144 return ExprError();
5145 return Arg;
5146 }
5147
5148 if (ParamType->isPointerType()) {
5149 // -- for a non-type template-parameter of type pointer to
5150 // object, qualification conversions (4.4) and the
5151 // array-to-pointer conversion (4.2) are applied.
5152 // C++0x also allows a value of std::nullptr_t.
5153 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5154 "Only object pointers allowed here");
5155
5156 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5157 ParamType,
5158 Arg, Converted))
5159 return ExprError();
5160 return Arg;
5161 }
5162
5163 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5164 // -- For a non-type template-parameter of type reference to
5165 // object, no conversions apply. The type referred to by the
5166 // reference may be more cv-qualified than the (otherwise
5167 // identical) type of the template-argument. The
5168 // template-parameter is bound directly to the
5169 // template-argument, which must be an lvalue.
5170 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5171 "Only object references allowed here");
5172
5173 if (Arg->getType() == Context.OverloadTy) {
5174 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5175 ParamRefType->getPointeeType(),
5176 true,
5177 FoundResult)) {
5178 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5179 return ExprError();
5180
5181 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5182 ArgType = Arg->getType();
5183 } else
5184 return ExprError();
5185 }
5186
5187 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5188 ParamType,
5189 Arg, Converted))
5190 return ExprError();
5191 return Arg;
5192 }
5193
5194 // Deal with parameters of type std::nullptr_t.
5195 if (ParamType->isNullPtrType()) {
5196 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5197 Converted = TemplateArgument(Arg);
5198 return Arg;
5199 }
5200
5201 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5202 case NPV_NotNullPointer:
5203 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5204 << Arg->getType() << ParamType;
5205 Diag(Param->getLocation(), diag::note_template_param_here);
5206 return ExprError();
5207
5208 case NPV_Error:
5209 return ExprError();
5210
5211 case NPV_NullPointer:
5212 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5213 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5214 /*isNullPtr*/true);
5215 return Arg;
5216 }
5217 }
5218
5219 // -- For a non-type template-parameter of type pointer to data
5220 // member, qualification conversions (4.4) are applied.
5221 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5222
5223 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5224 Converted))
5225 return ExprError();
5226 return Arg;
5227 }
5228
5229 /// \brief Check a template argument against its corresponding
5230 /// template template parameter.
5231 ///
5232 /// This routine implements the semantics of C++ [temp.arg.template].
5233 /// It returns true if an error occurred, and false otherwise.
CheckTemplateArgument(TemplateTemplateParmDecl * Param,TemplateArgumentLoc & Arg,unsigned ArgumentPackIndex)5234 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5235 TemplateArgumentLoc &Arg,
5236 unsigned ArgumentPackIndex) {
5237 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5238 TemplateDecl *Template = Name.getAsTemplateDecl();
5239 if (!Template) {
5240 // Any dependent template name is fine.
5241 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5242 return false;
5243 }
5244
5245 // C++0x [temp.arg.template]p1:
5246 // A template-argument for a template template-parameter shall be
5247 // the name of a class template or an alias template, expressed as an
5248 // id-expression. When the template-argument names a class template, only
5249 // primary class templates are considered when matching the
5250 // template template argument with the corresponding parameter;
5251 // partial specializations are not considered even if their
5252 // parameter lists match that of the template template parameter.
5253 //
5254 // Note that we also allow template template parameters here, which
5255 // will happen when we are dealing with, e.g., class template
5256 // partial specializations.
5257 if (!isa<ClassTemplateDecl>(Template) &&
5258 !isa<TemplateTemplateParmDecl>(Template) &&
5259 !isa<TypeAliasTemplateDecl>(Template)) {
5260 assert(isa<FunctionTemplateDecl>(Template) &&
5261 "Only function templates are possible here");
5262 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5263 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5264 << Template;
5265 }
5266
5267 TemplateParameterList *Params = Param->getTemplateParameters();
5268 if (Param->isExpandedParameterPack())
5269 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5270
5271 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5272 Params,
5273 true,
5274 TPL_TemplateTemplateArgumentMatch,
5275 Arg.getLocation());
5276 }
5277
5278 /// \brief Given a non-type template argument that refers to a
5279 /// declaration and the type of its corresponding non-type template
5280 /// parameter, produce an expression that properly refers to that
5281 /// declaration.
5282 ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument & Arg,QualType ParamType,SourceLocation Loc)5283 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5284 QualType ParamType,
5285 SourceLocation Loc) {
5286 // C++ [temp.param]p8:
5287 //
5288 // A non-type template-parameter of type "array of T" or
5289 // "function returning T" is adjusted to be of type "pointer to
5290 // T" or "pointer to function returning T", respectively.
5291 if (ParamType->isArrayType())
5292 ParamType = Context.getArrayDecayedType(ParamType);
5293 else if (ParamType->isFunctionType())
5294 ParamType = Context.getPointerType(ParamType);
5295
5296 // For a NULL non-type template argument, return nullptr casted to the
5297 // parameter's type.
5298 if (Arg.getKind() == TemplateArgument::NullPtr) {
5299 return ImpCastExprToType(
5300 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5301 ParamType,
5302 ParamType->getAs<MemberPointerType>()
5303 ? CK_NullToMemberPointer
5304 : CK_NullToPointer);
5305 }
5306 assert(Arg.getKind() == TemplateArgument::Declaration &&
5307 "Only declaration template arguments permitted here");
5308
5309 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5310
5311 if (VD->getDeclContext()->isRecord() &&
5312 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5313 isa<IndirectFieldDecl>(VD))) {
5314 // If the value is a class member, we might have a pointer-to-member.
5315 // Determine whether the non-type template template parameter is of
5316 // pointer-to-member type. If so, we need to build an appropriate
5317 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5318 // would refer to the member itself.
5319 if (ParamType->isMemberPointerType()) {
5320 QualType ClassType
5321 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5322 NestedNameSpecifier *Qualifier
5323 = NestedNameSpecifier::Create(Context, nullptr, false,
5324 ClassType.getTypePtr());
5325 CXXScopeSpec SS;
5326 SS.MakeTrivial(Context, Qualifier, Loc);
5327
5328 // The actual value-ness of this is unimportant, but for
5329 // internal consistency's sake, references to instance methods
5330 // are r-values.
5331 ExprValueKind VK = VK_LValue;
5332 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5333 VK = VK_RValue;
5334
5335 ExprResult RefExpr = BuildDeclRefExpr(VD,
5336 VD->getType().getNonReferenceType(),
5337 VK,
5338 Loc,
5339 &SS);
5340 if (RefExpr.isInvalid())
5341 return ExprError();
5342
5343 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5344
5345 // We might need to perform a trailing qualification conversion, since
5346 // the element type on the parameter could be more qualified than the
5347 // element type in the expression we constructed.
5348 bool ObjCLifetimeConversion;
5349 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5350 ParamType.getUnqualifiedType(), false,
5351 ObjCLifetimeConversion))
5352 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5353
5354 assert(!RefExpr.isInvalid() &&
5355 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5356 ParamType.getUnqualifiedType()));
5357 return RefExpr;
5358 }
5359 }
5360
5361 QualType T = VD->getType().getNonReferenceType();
5362
5363 if (ParamType->isPointerType()) {
5364 // When the non-type template parameter is a pointer, take the
5365 // address of the declaration.
5366 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5367 if (RefExpr.isInvalid())
5368 return ExprError();
5369
5370 if (T->isFunctionType() || T->isArrayType()) {
5371 // Decay functions and arrays.
5372 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5373 if (RefExpr.isInvalid())
5374 return ExprError();
5375
5376 return RefExpr;
5377 }
5378
5379 // Take the address of everything else
5380 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5381 }
5382
5383 ExprValueKind VK = VK_RValue;
5384
5385 // If the non-type template parameter has reference type, qualify the
5386 // resulting declaration reference with the extra qualifiers on the
5387 // type that the reference refers to.
5388 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5389 VK = VK_LValue;
5390 T = Context.getQualifiedType(T,
5391 TargetRef->getPointeeType().getQualifiers());
5392 } else if (isa<FunctionDecl>(VD)) {
5393 // References to functions are always lvalues.
5394 VK = VK_LValue;
5395 }
5396
5397 return BuildDeclRefExpr(VD, T, VK, Loc);
5398 }
5399
5400 /// \brief Construct a new expression that refers to the given
5401 /// integral template argument with the given source-location
5402 /// information.
5403 ///
5404 /// This routine takes care of the mapping from an integral template
5405 /// argument (which may have any integral type) to the appropriate
5406 /// literal value.
5407 ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument & Arg,SourceLocation Loc)5408 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5409 SourceLocation Loc) {
5410 assert(Arg.getKind() == TemplateArgument::Integral &&
5411 "Operation is only valid for integral template arguments");
5412 QualType OrigT = Arg.getIntegralType();
5413
5414 // If this is an enum type that we're instantiating, we need to use an integer
5415 // type the same size as the enumerator. We don't want to build an
5416 // IntegerLiteral with enum type. The integer type of an enum type can be of
5417 // any integral type with C++11 enum classes, make sure we create the right
5418 // type of literal for it.
5419 QualType T = OrigT;
5420 if (const EnumType *ET = OrigT->getAs<EnumType>())
5421 T = ET->getDecl()->getIntegerType();
5422
5423 Expr *E;
5424 if (T->isAnyCharacterType()) {
5425 CharacterLiteral::CharacterKind Kind;
5426 if (T->isWideCharType())
5427 Kind = CharacterLiteral::Wide;
5428 else if (T->isChar16Type())
5429 Kind = CharacterLiteral::UTF16;
5430 else if (T->isChar32Type())
5431 Kind = CharacterLiteral::UTF32;
5432 else
5433 Kind = CharacterLiteral::Ascii;
5434
5435 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5436 Kind, T, Loc);
5437 } else if (T->isBooleanType()) {
5438 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5439 T, Loc);
5440 } else if (T->isNullPtrType()) {
5441 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5442 } else {
5443 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5444 }
5445
5446 if (OrigT->isEnumeralType()) {
5447 // FIXME: This is a hack. We need a better way to handle substituted
5448 // non-type template parameters.
5449 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5450 nullptr,
5451 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5452 Loc, Loc);
5453 }
5454
5455 return E;
5456 }
5457
5458 /// \brief Match two template parameters within template parameter lists.
MatchTemplateParameterKind(Sema & S,NamedDecl * New,NamedDecl * Old,bool Complain,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)5459 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5460 bool Complain,
5461 Sema::TemplateParameterListEqualKind Kind,
5462 SourceLocation TemplateArgLoc) {
5463 // Check the actual kind (type, non-type, template).
5464 if (Old->getKind() != New->getKind()) {
5465 if (Complain) {
5466 unsigned NextDiag = diag::err_template_param_different_kind;
5467 if (TemplateArgLoc.isValid()) {
5468 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5469 NextDiag = diag::note_template_param_different_kind;
5470 }
5471 S.Diag(New->getLocation(), NextDiag)
5472 << (Kind != Sema::TPL_TemplateMatch);
5473 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5474 << (Kind != Sema::TPL_TemplateMatch);
5475 }
5476
5477 return false;
5478 }
5479
5480 // Check that both are parameter packs are neither are parameter packs.
5481 // However, if we are matching a template template argument to a
5482 // template template parameter, the template template parameter can have
5483 // a parameter pack where the template template argument does not.
5484 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5485 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5486 Old->isTemplateParameterPack())) {
5487 if (Complain) {
5488 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5489 if (TemplateArgLoc.isValid()) {
5490 S.Diag(TemplateArgLoc,
5491 diag::err_template_arg_template_params_mismatch);
5492 NextDiag = diag::note_template_parameter_pack_non_pack;
5493 }
5494
5495 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5496 : isa<NonTypeTemplateParmDecl>(New)? 1
5497 : 2;
5498 S.Diag(New->getLocation(), NextDiag)
5499 << ParamKind << New->isParameterPack();
5500 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5501 << ParamKind << Old->isParameterPack();
5502 }
5503
5504 return false;
5505 }
5506
5507 // For non-type template parameters, check the type of the parameter.
5508 if (NonTypeTemplateParmDecl *OldNTTP
5509 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5510 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5511
5512 // If we are matching a template template argument to a template
5513 // template parameter and one of the non-type template parameter types
5514 // is dependent, then we must wait until template instantiation time
5515 // to actually compare the arguments.
5516 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5517 (OldNTTP->getType()->isDependentType() ||
5518 NewNTTP->getType()->isDependentType()))
5519 return true;
5520
5521 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5522 if (Complain) {
5523 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5524 if (TemplateArgLoc.isValid()) {
5525 S.Diag(TemplateArgLoc,
5526 diag::err_template_arg_template_params_mismatch);
5527 NextDiag = diag::note_template_nontype_parm_different_type;
5528 }
5529 S.Diag(NewNTTP->getLocation(), NextDiag)
5530 << NewNTTP->getType()
5531 << (Kind != Sema::TPL_TemplateMatch);
5532 S.Diag(OldNTTP->getLocation(),
5533 diag::note_template_nontype_parm_prev_declaration)
5534 << OldNTTP->getType();
5535 }
5536
5537 return false;
5538 }
5539
5540 return true;
5541 }
5542
5543 // For template template parameters, check the template parameter types.
5544 // The template parameter lists of template template
5545 // parameters must agree.
5546 if (TemplateTemplateParmDecl *OldTTP
5547 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5548 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5549 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5550 OldTTP->getTemplateParameters(),
5551 Complain,
5552 (Kind == Sema::TPL_TemplateMatch
5553 ? Sema::TPL_TemplateTemplateParmMatch
5554 : Kind),
5555 TemplateArgLoc);
5556 }
5557
5558 return true;
5559 }
5560
5561 /// \brief Diagnose a known arity mismatch when comparing template argument
5562 /// lists.
5563 static
DiagnoseTemplateParameterListArityMismatch(Sema & S,TemplateParameterList * New,TemplateParameterList * Old,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)5564 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5565 TemplateParameterList *New,
5566 TemplateParameterList *Old,
5567 Sema::TemplateParameterListEqualKind Kind,
5568 SourceLocation TemplateArgLoc) {
5569 unsigned NextDiag = diag::err_template_param_list_different_arity;
5570 if (TemplateArgLoc.isValid()) {
5571 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5572 NextDiag = diag::note_template_param_list_different_arity;
5573 }
5574 S.Diag(New->getTemplateLoc(), NextDiag)
5575 << (New->size() > Old->size())
5576 << (Kind != Sema::TPL_TemplateMatch)
5577 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5578 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5579 << (Kind != Sema::TPL_TemplateMatch)
5580 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5581 }
5582
5583 /// \brief Determine whether the given template parameter lists are
5584 /// equivalent.
5585 ///
5586 /// \param New The new template parameter list, typically written in the
5587 /// source code as part of a new template declaration.
5588 ///
5589 /// \param Old The old template parameter list, typically found via
5590 /// name lookup of the template declared with this template parameter
5591 /// list.
5592 ///
5593 /// \param Complain If true, this routine will produce a diagnostic if
5594 /// the template parameter lists are not equivalent.
5595 ///
5596 /// \param Kind describes how we are to match the template parameter lists.
5597 ///
5598 /// \param TemplateArgLoc If this source location is valid, then we
5599 /// are actually checking the template parameter list of a template
5600 /// argument (New) against the template parameter list of its
5601 /// corresponding template template parameter (Old). We produce
5602 /// slightly different diagnostics in this scenario.
5603 ///
5604 /// \returns True if the template parameter lists are equal, false
5605 /// otherwise.
5606 bool
TemplateParameterListsAreEqual(TemplateParameterList * New,TemplateParameterList * Old,bool Complain,TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)5607 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5608 TemplateParameterList *Old,
5609 bool Complain,
5610 TemplateParameterListEqualKind Kind,
5611 SourceLocation TemplateArgLoc) {
5612 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5613 if (Complain)
5614 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5615 TemplateArgLoc);
5616
5617 return false;
5618 }
5619
5620 // C++0x [temp.arg.template]p3:
5621 // A template-argument matches a template template-parameter (call it P)
5622 // when each of the template parameters in the template-parameter-list of
5623 // the template-argument's corresponding class template or alias template
5624 // (call it A) matches the corresponding template parameter in the
5625 // template-parameter-list of P. [...]
5626 TemplateParameterList::iterator NewParm = New->begin();
5627 TemplateParameterList::iterator NewParmEnd = New->end();
5628 for (TemplateParameterList::iterator OldParm = Old->begin(),
5629 OldParmEnd = Old->end();
5630 OldParm != OldParmEnd; ++OldParm) {
5631 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5632 !(*OldParm)->isTemplateParameterPack()) {
5633 if (NewParm == NewParmEnd) {
5634 if (Complain)
5635 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5636 TemplateArgLoc);
5637
5638 return false;
5639 }
5640
5641 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5642 Kind, TemplateArgLoc))
5643 return false;
5644
5645 ++NewParm;
5646 continue;
5647 }
5648
5649 // C++0x [temp.arg.template]p3:
5650 // [...] When P's template- parameter-list contains a template parameter
5651 // pack (14.5.3), the template parameter pack will match zero or more
5652 // template parameters or template parameter packs in the
5653 // template-parameter-list of A with the same type and form as the
5654 // template parameter pack in P (ignoring whether those template
5655 // parameters are template parameter packs).
5656 for (; NewParm != NewParmEnd; ++NewParm) {
5657 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5658 Kind, TemplateArgLoc))
5659 return false;
5660 }
5661 }
5662
5663 // Make sure we exhausted all of the arguments.
5664 if (NewParm != NewParmEnd) {
5665 if (Complain)
5666 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5667 TemplateArgLoc);
5668
5669 return false;
5670 }
5671
5672 return true;
5673 }
5674
5675 /// \brief Check whether a template can be declared within this scope.
5676 ///
5677 /// If the template declaration is valid in this scope, returns
5678 /// false. Otherwise, issues a diagnostic and returns true.
5679 bool
CheckTemplateDeclScope(Scope * S,TemplateParameterList * TemplateParams)5680 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5681 if (!S)
5682 return false;
5683
5684 // Find the nearest enclosing declaration scope.
5685 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5686 (S->getFlags() & Scope::TemplateParamScope) != 0)
5687 S = S->getParent();
5688
5689 // C++ [temp]p4:
5690 // A template [...] shall not have C linkage.
5691 DeclContext *Ctx = S->getEntity();
5692 if (Ctx && Ctx->isExternCContext())
5693 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5694 << TemplateParams->getSourceRange();
5695
5696 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5697 Ctx = Ctx->getParent();
5698
5699 // C++ [temp]p2:
5700 // A template-declaration can appear only as a namespace scope or
5701 // class scope declaration.
5702 if (Ctx) {
5703 if (Ctx->isFileContext())
5704 return false;
5705 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5706 // C++ [temp.mem]p2:
5707 // A local class shall not have member templates.
5708 if (RD->isLocalClass())
5709 return Diag(TemplateParams->getTemplateLoc(),
5710 diag::err_template_inside_local_class)
5711 << TemplateParams->getSourceRange();
5712 else
5713 return false;
5714 }
5715 }
5716
5717 return Diag(TemplateParams->getTemplateLoc(),
5718 diag::err_template_outside_namespace_or_class_scope)
5719 << TemplateParams->getSourceRange();
5720 }
5721
5722 /// \brief Determine what kind of template specialization the given declaration
5723 /// is.
getTemplateSpecializationKind(Decl * D)5724 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5725 if (!D)
5726 return TSK_Undeclared;
5727
5728 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5729 return Record->getTemplateSpecializationKind();
5730 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5731 return Function->getTemplateSpecializationKind();
5732 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5733 return Var->getTemplateSpecializationKind();
5734
5735 return TSK_Undeclared;
5736 }
5737
5738 /// \brief Check whether a specialization is well-formed in the current
5739 /// context.
5740 ///
5741 /// This routine determines whether a template specialization can be declared
5742 /// in the current context (C++ [temp.expl.spec]p2).
5743 ///
5744 /// \param S the semantic analysis object for which this check is being
5745 /// performed.
5746 ///
5747 /// \param Specialized the entity being specialized or instantiated, which
5748 /// may be a kind of template (class template, function template, etc.) or
5749 /// a member of a class template (member function, static data member,
5750 /// member class).
5751 ///
5752 /// \param PrevDecl the previous declaration of this entity, if any.
5753 ///
5754 /// \param Loc the location of the explicit specialization or instantiation of
5755 /// this entity.
5756 ///
5757 /// \param IsPartialSpecialization whether this is a partial specialization of
5758 /// a class template.
5759 ///
5760 /// \returns true if there was an error that we cannot recover from, false
5761 /// otherwise.
CheckTemplateSpecializationScope(Sema & S,NamedDecl * Specialized,NamedDecl * PrevDecl,SourceLocation Loc,bool IsPartialSpecialization)5762 static bool CheckTemplateSpecializationScope(Sema &S,
5763 NamedDecl *Specialized,
5764 NamedDecl *PrevDecl,
5765 SourceLocation Loc,
5766 bool IsPartialSpecialization) {
5767 // Keep these "kind" numbers in sync with the %select statements in the
5768 // various diagnostics emitted by this routine.
5769 int EntityKind = 0;
5770 if (isa<ClassTemplateDecl>(Specialized))
5771 EntityKind = IsPartialSpecialization? 1 : 0;
5772 else if (isa<VarTemplateDecl>(Specialized))
5773 EntityKind = IsPartialSpecialization ? 3 : 2;
5774 else if (isa<FunctionTemplateDecl>(Specialized))
5775 EntityKind = 4;
5776 else if (isa<CXXMethodDecl>(Specialized))
5777 EntityKind = 5;
5778 else if (isa<VarDecl>(Specialized))
5779 EntityKind = 6;
5780 else if (isa<RecordDecl>(Specialized))
5781 EntityKind = 7;
5782 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5783 EntityKind = 8;
5784 else {
5785 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5786 << S.getLangOpts().CPlusPlus11;
5787 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5788 return true;
5789 }
5790
5791 // C++ [temp.expl.spec]p2:
5792 // An explicit specialization shall be declared in the namespace
5793 // of which the template is a member, or, for member templates, in
5794 // the namespace of which the enclosing class or enclosing class
5795 // template is a member. An explicit specialization of a member
5796 // function, member class or static data member of a class
5797 // template shall be declared in the namespace of which the class
5798 // template is a member. Such a declaration may also be a
5799 // definition. If the declaration is not a definition, the
5800 // specialization may be defined later in the name- space in which
5801 // the explicit specialization was declared, or in a namespace
5802 // that encloses the one in which the explicit specialization was
5803 // declared.
5804 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5805 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5806 << Specialized;
5807 return true;
5808 }
5809
5810 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5811 if (S.getLangOpts().MicrosoftExt) {
5812 // Do not warn for class scope explicit specialization during
5813 // instantiation, warning was already emitted during pattern
5814 // semantic analysis.
5815 if (!S.ActiveTemplateInstantiations.size())
5816 S.Diag(Loc, diag::ext_function_specialization_in_class)
5817 << Specialized;
5818 } else {
5819 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5820 << Specialized;
5821 return true;
5822 }
5823 }
5824
5825 if (S.CurContext->isRecord() &&
5826 !S.CurContext->Equals(Specialized->getDeclContext())) {
5827 // Make sure that we're specializing in the right record context.
5828 // Otherwise, things can go horribly wrong.
5829 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5830 << Specialized;
5831 return true;
5832 }
5833
5834 // C++ [temp.class.spec]p6:
5835 // A class template partial specialization may be declared or redeclared
5836 // in any namespace scope in which its definition may be defined (14.5.1
5837 // and 14.5.2).
5838 DeclContext *SpecializedContext
5839 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5840 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5841
5842 // Make sure that this redeclaration (or definition) occurs in an enclosing
5843 // namespace.
5844 // Note that HandleDeclarator() performs this check for explicit
5845 // specializations of function templates, static data members, and member
5846 // functions, so we skip the check here for those kinds of entities.
5847 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5848 // Should we refactor that check, so that it occurs later?
5849 if (!DC->Encloses(SpecializedContext) &&
5850 !(isa<FunctionTemplateDecl>(Specialized) ||
5851 isa<FunctionDecl>(Specialized) ||
5852 isa<VarTemplateDecl>(Specialized) ||
5853 isa<VarDecl>(Specialized))) {
5854 if (isa<TranslationUnitDecl>(SpecializedContext))
5855 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5856 << EntityKind << Specialized;
5857 else if (isa<NamespaceDecl>(SpecializedContext)) {
5858 int Diag = diag::err_template_spec_redecl_out_of_scope;
5859 if (S.getLangOpts().MicrosoftExt)
5860 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5861 S.Diag(Loc, Diag) << EntityKind << Specialized
5862 << cast<NamedDecl>(SpecializedContext);
5863 } else
5864 llvm_unreachable("unexpected namespace context for specialization");
5865
5866 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5867 } else if ((!PrevDecl ||
5868 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5869 getTemplateSpecializationKind(PrevDecl) ==
5870 TSK_ImplicitInstantiation)) {
5871 // C++ [temp.exp.spec]p2:
5872 // An explicit specialization shall be declared in the namespace of which
5873 // the template is a member, or, for member templates, in the namespace
5874 // of which the enclosing class or enclosing class template is a member.
5875 // An explicit specialization of a member function, member class or
5876 // static data member of a class template shall be declared in the
5877 // namespace of which the class template is a member.
5878 //
5879 // C++11 [temp.expl.spec]p2:
5880 // An explicit specialization shall be declared in a namespace enclosing
5881 // the specialized template.
5882 // C++11 [temp.explicit]p3:
5883 // An explicit instantiation shall appear in an enclosing namespace of its
5884 // template.
5885 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5886 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5887 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5888 assert(!IsCPlusPlus11Extension &&
5889 "DC encloses TU but isn't in enclosing namespace set");
5890 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5891 << EntityKind << Specialized;
5892 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5893 int Diag;
5894 if (!IsCPlusPlus11Extension)
5895 Diag = diag::err_template_spec_decl_out_of_scope;
5896 else if (!S.getLangOpts().CPlusPlus11)
5897 Diag = diag::ext_template_spec_decl_out_of_scope;
5898 else
5899 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5900 S.Diag(Loc, Diag)
5901 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5902 }
5903
5904 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5905 }
5906 }
5907
5908 return false;
5909 }
5910
findTemplateParameter(unsigned Depth,Expr * E)5911 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5912 if (!E->isInstantiationDependent())
5913 return SourceLocation();
5914 DependencyChecker Checker(Depth);
5915 Checker.TraverseStmt(E);
5916 if (Checker.Match && Checker.MatchLoc.isInvalid())
5917 return E->getSourceRange();
5918 return Checker.MatchLoc;
5919 }
5920
findTemplateParameter(unsigned Depth,TypeLoc TL)5921 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5922 if (!TL.getType()->isDependentType())
5923 return SourceLocation();
5924 DependencyChecker Checker(Depth);
5925 Checker.TraverseTypeLoc(TL);
5926 if (Checker.Match && Checker.MatchLoc.isInvalid())
5927 return TL.getSourceRange();
5928 return Checker.MatchLoc;
5929 }
5930
5931 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5932 /// that checks non-type template partial specialization arguments.
CheckNonTypeTemplatePartialSpecializationArgs(Sema & S,SourceLocation TemplateNameLoc,NonTypeTemplateParmDecl * Param,const TemplateArgument * Args,unsigned NumArgs,bool IsDefaultArgument)5933 static bool CheckNonTypeTemplatePartialSpecializationArgs(
5934 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5935 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
5936 for (unsigned I = 0; I != NumArgs; ++I) {
5937 if (Args[I].getKind() == TemplateArgument::Pack) {
5938 if (CheckNonTypeTemplatePartialSpecializationArgs(
5939 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5940 Args[I].pack_size(), IsDefaultArgument))
5941 return true;
5942
5943 continue;
5944 }
5945
5946 if (Args[I].getKind() != TemplateArgument::Expression)
5947 continue;
5948
5949 Expr *ArgExpr = Args[I].getAsExpr();
5950
5951 // We can have a pack expansion of any of the bullets below.
5952 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5953 ArgExpr = Expansion->getPattern();
5954
5955 // Strip off any implicit casts we added as part of type checking.
5956 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5957 ArgExpr = ICE->getSubExpr();
5958
5959 // C++ [temp.class.spec]p8:
5960 // A non-type argument is non-specialized if it is the name of a
5961 // non-type parameter. All other non-type arguments are
5962 // specialized.
5963 //
5964 // Below, we check the two conditions that only apply to
5965 // specialized non-type arguments, so skip any non-specialized
5966 // arguments.
5967 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5968 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5969 continue;
5970
5971 // C++ [temp.class.spec]p9:
5972 // Within the argument list of a class template partial
5973 // specialization, the following restrictions apply:
5974 // -- A partially specialized non-type argument expression
5975 // shall not involve a template parameter of the partial
5976 // specialization except when the argument expression is a
5977 // simple identifier.
5978 SourceRange ParamUseRange =
5979 findTemplateParameter(Param->getDepth(), ArgExpr);
5980 if (ParamUseRange.isValid()) {
5981 if (IsDefaultArgument) {
5982 S.Diag(TemplateNameLoc,
5983 diag::err_dependent_non_type_arg_in_partial_spec);
5984 S.Diag(ParamUseRange.getBegin(),
5985 diag::note_dependent_non_type_default_arg_in_partial_spec)
5986 << ParamUseRange;
5987 } else {
5988 S.Diag(ParamUseRange.getBegin(),
5989 diag::err_dependent_non_type_arg_in_partial_spec)
5990 << ParamUseRange;
5991 }
5992 return true;
5993 }
5994
5995 // -- The type of a template parameter corresponding to a
5996 // specialized non-type argument shall not be dependent on a
5997 // parameter of the specialization.
5998 //
5999 // FIXME: We need to delay this check until instantiation in some cases:
6000 //
6001 // template<template<typename> class X> struct A {
6002 // template<typename T, X<T> N> struct B;
6003 // template<typename T> struct B<T, 0>;
6004 // };
6005 // template<typename> using X = int;
6006 // A<X>::B<int, 0> b;
6007 ParamUseRange = findTemplateParameter(
6008 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6009 if (ParamUseRange.isValid()) {
6010 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6011 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6012 << Param->getType() << ParamUseRange;
6013 S.Diag(Param->getLocation(), diag::note_template_param_here)
6014 << (IsDefaultArgument ? ParamUseRange : SourceRange());
6015 return true;
6016 }
6017 }
6018
6019 return false;
6020 }
6021
6022 /// \brief Check the non-type template arguments of a class template
6023 /// partial specialization according to C++ [temp.class.spec]p9.
6024 ///
6025 /// \param TemplateNameLoc the location of the template name.
6026 /// \param TemplateParams the template parameters of the primary class
6027 /// template.
6028 /// \param NumExplicit the number of explicitly-specified template arguments.
6029 /// \param TemplateArgs the template arguments of the class template
6030 /// partial specialization.
6031 ///
6032 /// \returns \c true if there was an error, \c false otherwise.
CheckTemplatePartialSpecializationArgs(Sema & S,SourceLocation TemplateNameLoc,TemplateParameterList * TemplateParams,unsigned NumExplicit,SmallVectorImpl<TemplateArgument> & TemplateArgs)6033 static bool CheckTemplatePartialSpecializationArgs(
6034 Sema &S, SourceLocation TemplateNameLoc,
6035 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6036 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6037 const TemplateArgument *ArgList = TemplateArgs.data();
6038
6039 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6040 NonTypeTemplateParmDecl *Param
6041 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6042 if (!Param)
6043 continue;
6044
6045 if (CheckNonTypeTemplatePartialSpecializationArgs(
6046 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6047 return true;
6048 }
6049
6050 return false;
6051 }
6052
6053 DeclResult
ActOnClassTemplateSpecialization(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,SourceLocation ModulePrivateLoc,TemplateIdAnnotation & TemplateId,AttributeList * Attr,MultiTemplateParamsArg TemplateParameterLists)6054 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6055 TagUseKind TUK,
6056 SourceLocation KWLoc,
6057 SourceLocation ModulePrivateLoc,
6058 TemplateIdAnnotation &TemplateId,
6059 AttributeList *Attr,
6060 MultiTemplateParamsArg TemplateParameterLists) {
6061 assert(TUK != TUK_Reference && "References are not specializations");
6062
6063 CXXScopeSpec &SS = TemplateId.SS;
6064
6065 // NOTE: KWLoc is the location of the tag keyword. This will instead
6066 // store the location of the outermost template keyword in the declaration.
6067 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6068 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6069 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6070 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6071 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6072
6073 // Find the class template we're specializing
6074 TemplateName Name = TemplateId.Template.get();
6075 ClassTemplateDecl *ClassTemplate
6076 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6077
6078 if (!ClassTemplate) {
6079 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6080 << (Name.getAsTemplateDecl() &&
6081 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6082 return true;
6083 }
6084
6085 bool isExplicitSpecialization = false;
6086 bool isPartialSpecialization = false;
6087
6088 // Check the validity of the template headers that introduce this
6089 // template.
6090 // FIXME: We probably shouldn't complain about these headers for
6091 // friend declarations.
6092 bool Invalid = false;
6093 TemplateParameterList *TemplateParams =
6094 MatchTemplateParametersToScopeSpecifier(
6095 KWLoc, TemplateNameLoc, SS, &TemplateId,
6096 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6097 Invalid);
6098 if (Invalid)
6099 return true;
6100
6101 if (TemplateParams && TemplateParams->size() > 0) {
6102 isPartialSpecialization = true;
6103
6104 if (TUK == TUK_Friend) {
6105 Diag(KWLoc, diag::err_partial_specialization_friend)
6106 << SourceRange(LAngleLoc, RAngleLoc);
6107 return true;
6108 }
6109
6110 // C++ [temp.class.spec]p10:
6111 // The template parameter list of a specialization shall not
6112 // contain default template argument values.
6113 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6114 Decl *Param = TemplateParams->getParam(I);
6115 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6116 if (TTP->hasDefaultArgument()) {
6117 Diag(TTP->getDefaultArgumentLoc(),
6118 diag::err_default_arg_in_partial_spec);
6119 TTP->removeDefaultArgument();
6120 }
6121 } else if (NonTypeTemplateParmDecl *NTTP
6122 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6123 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6124 Diag(NTTP->getDefaultArgumentLoc(),
6125 diag::err_default_arg_in_partial_spec)
6126 << DefArg->getSourceRange();
6127 NTTP->removeDefaultArgument();
6128 }
6129 } else {
6130 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6131 if (TTP->hasDefaultArgument()) {
6132 Diag(TTP->getDefaultArgument().getLocation(),
6133 diag::err_default_arg_in_partial_spec)
6134 << TTP->getDefaultArgument().getSourceRange();
6135 TTP->removeDefaultArgument();
6136 }
6137 }
6138 }
6139 } else if (TemplateParams) {
6140 if (TUK == TUK_Friend)
6141 Diag(KWLoc, diag::err_template_spec_friend)
6142 << FixItHint::CreateRemoval(
6143 SourceRange(TemplateParams->getTemplateLoc(),
6144 TemplateParams->getRAngleLoc()))
6145 << SourceRange(LAngleLoc, RAngleLoc);
6146 else
6147 isExplicitSpecialization = true;
6148 } else {
6149 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6150 }
6151
6152 // Check that the specialization uses the same tag kind as the
6153 // original template.
6154 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6155 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6156 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6157 Kind, TUK == TUK_Definition, KWLoc,
6158 *ClassTemplate->getIdentifier())) {
6159 Diag(KWLoc, diag::err_use_with_wrong_tag)
6160 << ClassTemplate
6161 << FixItHint::CreateReplacement(KWLoc,
6162 ClassTemplate->getTemplatedDecl()->getKindName());
6163 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6164 diag::note_previous_use);
6165 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6166 }
6167
6168 // Translate the parser's template argument list in our AST format.
6169 TemplateArgumentListInfo TemplateArgs =
6170 makeTemplateArgumentListInfo(*this, TemplateId);
6171
6172 // Check for unexpanded parameter packs in any of the template arguments.
6173 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6174 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6175 UPPC_PartialSpecialization))
6176 return true;
6177
6178 // Check that the template argument list is well-formed for this
6179 // template.
6180 SmallVector<TemplateArgument, 4> Converted;
6181 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6182 TemplateArgs, false, Converted))
6183 return true;
6184
6185 // Find the class template (partial) specialization declaration that
6186 // corresponds to these arguments.
6187 if (isPartialSpecialization) {
6188 if (CheckTemplatePartialSpecializationArgs(
6189 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6190 TemplateArgs.size(), Converted))
6191 return true;
6192
6193 bool InstantiationDependent;
6194 if (!Name.isDependent() &&
6195 !TemplateSpecializationType::anyDependentTemplateArguments(
6196 TemplateArgs.getArgumentArray(),
6197 TemplateArgs.size(),
6198 InstantiationDependent)) {
6199 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6200 << ClassTemplate->getDeclName();
6201 isPartialSpecialization = false;
6202 }
6203 }
6204
6205 void *InsertPos = nullptr;
6206 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6207
6208 if (isPartialSpecialization)
6209 // FIXME: Template parameter list matters, too
6210 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6211 else
6212 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6213
6214 ClassTemplateSpecializationDecl *Specialization = nullptr;
6215
6216 // Check whether we can declare a class template specialization in
6217 // the current scope.
6218 if (TUK != TUK_Friend &&
6219 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6220 TemplateNameLoc,
6221 isPartialSpecialization))
6222 return true;
6223
6224 // The canonical type
6225 QualType CanonType;
6226 if (isPartialSpecialization) {
6227 // Build the canonical type that describes the converted template
6228 // arguments of the class template partial specialization.
6229 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6230 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6231 Converted.data(),
6232 Converted.size());
6233
6234 if (Context.hasSameType(CanonType,
6235 ClassTemplate->getInjectedClassNameSpecialization())) {
6236 // C++ [temp.class.spec]p9b3:
6237 //
6238 // -- The argument list of the specialization shall not be identical
6239 // to the implicit argument list of the primary template.
6240 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6241 << /*class template*/0 << (TUK == TUK_Definition)
6242 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6243 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6244 ClassTemplate->getIdentifier(),
6245 TemplateNameLoc,
6246 Attr,
6247 TemplateParams,
6248 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6249 /*FriendLoc*/SourceLocation(),
6250 TemplateParameterLists.size() - 1,
6251 TemplateParameterLists.data());
6252 }
6253
6254 // Create a new class template partial specialization declaration node.
6255 ClassTemplatePartialSpecializationDecl *PrevPartial
6256 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6257 ClassTemplatePartialSpecializationDecl *Partial
6258 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6259 ClassTemplate->getDeclContext(),
6260 KWLoc, TemplateNameLoc,
6261 TemplateParams,
6262 ClassTemplate,
6263 Converted.data(),
6264 Converted.size(),
6265 TemplateArgs,
6266 CanonType,
6267 PrevPartial);
6268 SetNestedNameSpecifier(Partial, SS);
6269 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6270 Partial->setTemplateParameterListsInfo(Context,
6271 TemplateParameterLists.size() - 1,
6272 TemplateParameterLists.data());
6273 }
6274
6275 if (!PrevPartial)
6276 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6277 Specialization = Partial;
6278
6279 // If we are providing an explicit specialization of a member class
6280 // template specialization, make a note of that.
6281 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6282 PrevPartial->setMemberSpecialization();
6283
6284 // Check that all of the template parameters of the class template
6285 // partial specialization are deducible from the template
6286 // arguments. If not, this class template partial specialization
6287 // will never be used.
6288 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6289 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6290 TemplateParams->getDepth(),
6291 DeducibleParams);
6292
6293 if (!DeducibleParams.all()) {
6294 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6295 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6296 << /*class template*/0 << (NumNonDeducible > 1)
6297 << SourceRange(TemplateNameLoc, RAngleLoc);
6298 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6299 if (!DeducibleParams[I]) {
6300 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6301 if (Param->getDeclName())
6302 Diag(Param->getLocation(),
6303 diag::note_partial_spec_unused_parameter)
6304 << Param->getDeclName();
6305 else
6306 Diag(Param->getLocation(),
6307 diag::note_partial_spec_unused_parameter)
6308 << "(anonymous)";
6309 }
6310 }
6311 }
6312 } else {
6313 // Create a new class template specialization declaration node for
6314 // this explicit specialization or friend declaration.
6315 Specialization
6316 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6317 ClassTemplate->getDeclContext(),
6318 KWLoc, TemplateNameLoc,
6319 ClassTemplate,
6320 Converted.data(),
6321 Converted.size(),
6322 PrevDecl);
6323 SetNestedNameSpecifier(Specialization, SS);
6324 if (TemplateParameterLists.size() > 0) {
6325 Specialization->setTemplateParameterListsInfo(Context,
6326 TemplateParameterLists.size(),
6327 TemplateParameterLists.data());
6328 }
6329
6330 if (!PrevDecl)
6331 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6332
6333 CanonType = Context.getTypeDeclType(Specialization);
6334 }
6335
6336 // C++ [temp.expl.spec]p6:
6337 // If a template, a member template or the member of a class template is
6338 // explicitly specialized then that specialization shall be declared
6339 // before the first use of that specialization that would cause an implicit
6340 // instantiation to take place, in every translation unit in which such a
6341 // use occurs; no diagnostic is required.
6342 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6343 bool Okay = false;
6344 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6345 // Is there any previous explicit specialization declaration?
6346 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6347 Okay = true;
6348 break;
6349 }
6350 }
6351
6352 if (!Okay) {
6353 SourceRange Range(TemplateNameLoc, RAngleLoc);
6354 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6355 << Context.getTypeDeclType(Specialization) << Range;
6356
6357 Diag(PrevDecl->getPointOfInstantiation(),
6358 diag::note_instantiation_required_here)
6359 << (PrevDecl->getTemplateSpecializationKind()
6360 != TSK_ImplicitInstantiation);
6361 return true;
6362 }
6363 }
6364
6365 // If this is not a friend, note that this is an explicit specialization.
6366 if (TUK != TUK_Friend)
6367 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6368
6369 // Check that this isn't a redefinition of this specialization.
6370 if (TUK == TUK_Definition) {
6371 if (RecordDecl *Def = Specialization->getDefinition()) {
6372 SourceRange Range(TemplateNameLoc, RAngleLoc);
6373 Diag(TemplateNameLoc, diag::err_redefinition)
6374 << Context.getTypeDeclType(Specialization) << Range;
6375 Diag(Def->getLocation(), diag::note_previous_definition);
6376 Specialization->setInvalidDecl();
6377 return true;
6378 }
6379 }
6380
6381 if (Attr)
6382 ProcessDeclAttributeList(S, Specialization, Attr);
6383
6384 // Add alignment attributes if necessary; these attributes are checked when
6385 // the ASTContext lays out the structure.
6386 if (TUK == TUK_Definition) {
6387 AddAlignmentAttributesForRecord(Specialization);
6388 AddMsStructLayoutForRecord(Specialization);
6389 }
6390
6391 if (ModulePrivateLoc.isValid())
6392 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6393 << (isPartialSpecialization? 1 : 0)
6394 << FixItHint::CreateRemoval(ModulePrivateLoc);
6395
6396 // Build the fully-sugared type for this class template
6397 // specialization as the user wrote in the specialization
6398 // itself. This means that we'll pretty-print the type retrieved
6399 // from the specialization's declaration the way that the user
6400 // actually wrote the specialization, rather than formatting the
6401 // name based on the "canonical" representation used to store the
6402 // template arguments in the specialization.
6403 TypeSourceInfo *WrittenTy
6404 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6405 TemplateArgs, CanonType);
6406 if (TUK != TUK_Friend) {
6407 Specialization->setTypeAsWritten(WrittenTy);
6408 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6409 }
6410
6411 // C++ [temp.expl.spec]p9:
6412 // A template explicit specialization is in the scope of the
6413 // namespace in which the template was defined.
6414 //
6415 // We actually implement this paragraph where we set the semantic
6416 // context (in the creation of the ClassTemplateSpecializationDecl),
6417 // but we also maintain the lexical context where the actual
6418 // definition occurs.
6419 Specialization->setLexicalDeclContext(CurContext);
6420
6421 // We may be starting the definition of this specialization.
6422 if (TUK == TUK_Definition)
6423 Specialization->startDefinition();
6424
6425 if (TUK == TUK_Friend) {
6426 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6427 TemplateNameLoc,
6428 WrittenTy,
6429 /*FIXME:*/KWLoc);
6430 Friend->setAccess(AS_public);
6431 CurContext->addDecl(Friend);
6432 } else {
6433 // Add the specialization into its lexical context, so that it can
6434 // be seen when iterating through the list of declarations in that
6435 // context. However, specializations are not found by name lookup.
6436 CurContext->addDecl(Specialization);
6437 }
6438 return Specialization;
6439 }
6440
ActOnTemplateDeclarator(Scope * S,MultiTemplateParamsArg TemplateParameterLists,Declarator & D)6441 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6442 MultiTemplateParamsArg TemplateParameterLists,
6443 Declarator &D) {
6444 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6445 ActOnDocumentableDecl(NewDecl);
6446 return NewDecl;
6447 }
6448
ActOnStartOfFunctionTemplateDef(Scope * FnBodyScope,MultiTemplateParamsArg TemplateParameterLists,Declarator & D)6449 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
6450 MultiTemplateParamsArg TemplateParameterLists,
6451 Declarator &D) {
6452 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
6453 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6454
6455 if (FTI.hasPrototype) {
6456 // FIXME: Diagnose arguments without names in C.
6457 }
6458
6459 Scope *ParentScope = FnBodyScope->getParent();
6460
6461 D.setFunctionDefinitionKind(FDK_Definition);
6462 Decl *DP = HandleDeclarator(ParentScope, D,
6463 TemplateParameterLists);
6464 return ActOnStartOfFunctionDef(FnBodyScope, DP);
6465 }
6466
6467 /// \brief Strips various properties off an implicit instantiation
6468 /// that has just been explicitly specialized.
StripImplicitInstantiation(NamedDecl * D)6469 static void StripImplicitInstantiation(NamedDecl *D) {
6470 D->dropAttr<DLLImportAttr>();
6471 D->dropAttr<DLLExportAttr>();
6472
6473 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6474 FD->setInlineSpecified(false);
6475 }
6476
6477 /// \brief Compute the diagnostic location for an explicit instantiation
6478 // declaration or definition.
DiagLocForExplicitInstantiation(NamedDecl * D,SourceLocation PointOfInstantiation)6479 static SourceLocation DiagLocForExplicitInstantiation(
6480 NamedDecl* D, SourceLocation PointOfInstantiation) {
6481 // Explicit instantiations following a specialization have no effect and
6482 // hence no PointOfInstantiation. In that case, walk decl backwards
6483 // until a valid name loc is found.
6484 SourceLocation PrevDiagLoc = PointOfInstantiation;
6485 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6486 Prev = Prev->getPreviousDecl()) {
6487 PrevDiagLoc = Prev->getLocation();
6488 }
6489 assert(PrevDiagLoc.isValid() &&
6490 "Explicit instantiation without point of instantiation?");
6491 return PrevDiagLoc;
6492 }
6493
6494 /// \brief Diagnose cases where we have an explicit template specialization
6495 /// before/after an explicit template instantiation, producing diagnostics
6496 /// for those cases where they are required and determining whether the
6497 /// new specialization/instantiation will have any effect.
6498 ///
6499 /// \param NewLoc the location of the new explicit specialization or
6500 /// instantiation.
6501 ///
6502 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6503 ///
6504 /// \param PrevDecl the previous declaration of the entity.
6505 ///
6506 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6507 ///
6508 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6509 /// declaration was instantiated (either implicitly or explicitly).
6510 ///
6511 /// \param HasNoEffect will be set to true to indicate that the new
6512 /// specialization or instantiation has no effect and should be ignored.
6513 ///
6514 /// \returns true if there was an error that should prevent the introduction of
6515 /// the new declaration into the AST, false otherwise.
6516 bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,TemplateSpecializationKind NewTSK,NamedDecl * PrevDecl,TemplateSpecializationKind PrevTSK,SourceLocation PrevPointOfInstantiation,bool & HasNoEffect)6517 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6518 TemplateSpecializationKind NewTSK,
6519 NamedDecl *PrevDecl,
6520 TemplateSpecializationKind PrevTSK,
6521 SourceLocation PrevPointOfInstantiation,
6522 bool &HasNoEffect) {
6523 HasNoEffect = false;
6524
6525 switch (NewTSK) {
6526 case TSK_Undeclared:
6527 case TSK_ImplicitInstantiation:
6528 assert(
6529 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6530 "previous declaration must be implicit!");
6531 return false;
6532
6533 case TSK_ExplicitSpecialization:
6534 switch (PrevTSK) {
6535 case TSK_Undeclared:
6536 case TSK_ExplicitSpecialization:
6537 // Okay, we're just specializing something that is either already
6538 // explicitly specialized or has merely been mentioned without any
6539 // instantiation.
6540 return false;
6541
6542 case TSK_ImplicitInstantiation:
6543 if (PrevPointOfInstantiation.isInvalid()) {
6544 // The declaration itself has not actually been instantiated, so it is
6545 // still okay to specialize it.
6546 StripImplicitInstantiation(PrevDecl);
6547 return false;
6548 }
6549 // Fall through
6550
6551 case TSK_ExplicitInstantiationDeclaration:
6552 case TSK_ExplicitInstantiationDefinition:
6553 assert((PrevTSK == TSK_ImplicitInstantiation ||
6554 PrevPointOfInstantiation.isValid()) &&
6555 "Explicit instantiation without point of instantiation?");
6556
6557 // C++ [temp.expl.spec]p6:
6558 // If a template, a member template or the member of a class template
6559 // is explicitly specialized then that specialization shall be declared
6560 // before the first use of that specialization that would cause an
6561 // implicit instantiation to take place, in every translation unit in
6562 // which such a use occurs; no diagnostic is required.
6563 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6564 // Is there any previous explicit specialization declaration?
6565 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6566 return false;
6567 }
6568
6569 Diag(NewLoc, diag::err_specialization_after_instantiation)
6570 << PrevDecl;
6571 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6572 << (PrevTSK != TSK_ImplicitInstantiation);
6573
6574 return true;
6575 }
6576
6577 case TSK_ExplicitInstantiationDeclaration:
6578 switch (PrevTSK) {
6579 case TSK_ExplicitInstantiationDeclaration:
6580 // This explicit instantiation declaration is redundant (that's okay).
6581 HasNoEffect = true;
6582 return false;
6583
6584 case TSK_Undeclared:
6585 case TSK_ImplicitInstantiation:
6586 // We're explicitly instantiating something that may have already been
6587 // implicitly instantiated; that's fine.
6588 return false;
6589
6590 case TSK_ExplicitSpecialization:
6591 // C++0x [temp.explicit]p4:
6592 // For a given set of template parameters, if an explicit instantiation
6593 // of a template appears after a declaration of an explicit
6594 // specialization for that template, the explicit instantiation has no
6595 // effect.
6596 HasNoEffect = true;
6597 return false;
6598
6599 case TSK_ExplicitInstantiationDefinition:
6600 // C++0x [temp.explicit]p10:
6601 // If an entity is the subject of both an explicit instantiation
6602 // declaration and an explicit instantiation definition in the same
6603 // translation unit, the definition shall follow the declaration.
6604 Diag(NewLoc,
6605 diag::err_explicit_instantiation_declaration_after_definition);
6606
6607 // Explicit instantiations following a specialization have no effect and
6608 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6609 // until a valid name loc is found.
6610 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6611 diag::note_explicit_instantiation_definition_here);
6612 HasNoEffect = true;
6613 return false;
6614 }
6615
6616 case TSK_ExplicitInstantiationDefinition:
6617 switch (PrevTSK) {
6618 case TSK_Undeclared:
6619 case TSK_ImplicitInstantiation:
6620 // We're explicitly instantiating something that may have already been
6621 // implicitly instantiated; that's fine.
6622 return false;
6623
6624 case TSK_ExplicitSpecialization:
6625 // C++ DR 259, C++0x [temp.explicit]p4:
6626 // For a given set of template parameters, if an explicit
6627 // instantiation of a template appears after a declaration of
6628 // an explicit specialization for that template, the explicit
6629 // instantiation has no effect.
6630 //
6631 // In C++98/03 mode, we only give an extension warning here, because it
6632 // is not harmful to try to explicitly instantiate something that
6633 // has been explicitly specialized.
6634 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6635 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6636 diag::ext_explicit_instantiation_after_specialization)
6637 << PrevDecl;
6638 Diag(PrevDecl->getLocation(),
6639 diag::note_previous_template_specialization);
6640 HasNoEffect = true;
6641 return false;
6642
6643 case TSK_ExplicitInstantiationDeclaration:
6644 // We're explicity instantiating a definition for something for which we
6645 // were previously asked to suppress instantiations. That's fine.
6646
6647 // C++0x [temp.explicit]p4:
6648 // For a given set of template parameters, if an explicit instantiation
6649 // of a template appears after a declaration of an explicit
6650 // specialization for that template, the explicit instantiation has no
6651 // effect.
6652 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6653 // Is there any previous explicit specialization declaration?
6654 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6655 HasNoEffect = true;
6656 break;
6657 }
6658 }
6659
6660 return false;
6661
6662 case TSK_ExplicitInstantiationDefinition:
6663 // C++0x [temp.spec]p5:
6664 // For a given template and a given set of template-arguments,
6665 // - an explicit instantiation definition shall appear at most once
6666 // in a program,
6667
6668 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6669 Diag(NewLoc, (getLangOpts().MSVCCompat)
6670 ? diag::ext_explicit_instantiation_duplicate
6671 : diag::err_explicit_instantiation_duplicate)
6672 << PrevDecl;
6673 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6674 diag::note_previous_explicit_instantiation);
6675 HasNoEffect = true;
6676 return false;
6677 }
6678 }
6679
6680 llvm_unreachable("Missing specialization/instantiation case?");
6681 }
6682
6683 /// \brief Perform semantic analysis for the given dependent function
6684 /// template specialization.
6685 ///
6686 /// The only possible way to get a dependent function template specialization
6687 /// is with a friend declaration, like so:
6688 ///
6689 /// \code
6690 /// template \<class T> void foo(T);
6691 /// template \<class T> class A {
6692 /// friend void foo<>(T);
6693 /// };
6694 /// \endcode
6695 ///
6696 /// There really isn't any useful analysis we can do here, so we
6697 /// just store the information.
6698 bool
CheckDependentFunctionTemplateSpecialization(FunctionDecl * FD,const TemplateArgumentListInfo & ExplicitTemplateArgs,LookupResult & Previous)6699 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6700 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6701 LookupResult &Previous) {
6702 // Remove anything from Previous that isn't a function template in
6703 // the correct context.
6704 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6705 LookupResult::Filter F = Previous.makeFilter();
6706 while (F.hasNext()) {
6707 NamedDecl *D = F.next()->getUnderlyingDecl();
6708 if (!isa<FunctionTemplateDecl>(D) ||
6709 !FDLookupContext->InEnclosingNamespaceSetOf(
6710 D->getDeclContext()->getRedeclContext()))
6711 F.erase();
6712 }
6713 F.done();
6714
6715 // Should this be diagnosed here?
6716 if (Previous.empty()) return true;
6717
6718 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6719 ExplicitTemplateArgs);
6720 return false;
6721 }
6722
6723 /// \brief Perform semantic analysis for the given function template
6724 /// specialization.
6725 ///
6726 /// This routine performs all of the semantic analysis required for an
6727 /// explicit function template specialization. On successful completion,
6728 /// the function declaration \p FD will become a function template
6729 /// specialization.
6730 ///
6731 /// \param FD the function declaration, which will be updated to become a
6732 /// function template specialization.
6733 ///
6734 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6735 /// if any. Note that this may be valid info even when 0 arguments are
6736 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6737 /// as it anyway contains info on the angle brackets locations.
6738 ///
6739 /// \param Previous the set of declarations that may be specialized by
6740 /// this function specialization.
CheckFunctionTemplateSpecialization(FunctionDecl * FD,TemplateArgumentListInfo * ExplicitTemplateArgs,LookupResult & Previous)6741 bool Sema::CheckFunctionTemplateSpecialization(
6742 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6743 LookupResult &Previous) {
6744 // The set of function template specializations that could match this
6745 // explicit function template specialization.
6746 UnresolvedSet<8> Candidates;
6747 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6748
6749 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6750 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6751 I != E; ++I) {
6752 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6753 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6754 // Only consider templates found within the same semantic lookup scope as
6755 // FD.
6756 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6757 Ovl->getDeclContext()->getRedeclContext()))
6758 continue;
6759
6760 // When matching a constexpr member function template specialization
6761 // against the primary template, we don't yet know whether the
6762 // specialization has an implicit 'const' (because we don't know whether
6763 // it will be a static member function until we know which template it
6764 // specializes), so adjust it now assuming it specializes this template.
6765 QualType FT = FD->getType();
6766 if (FD->isConstexpr()) {
6767 CXXMethodDecl *OldMD =
6768 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6769 if (OldMD && OldMD->isConst()) {
6770 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6771 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6772 EPI.TypeQuals |= Qualifiers::Const;
6773 FT = Context.getFunctionType(FPT->getReturnType(),
6774 FPT->getParamTypes(), EPI);
6775 }
6776 }
6777
6778 // C++ [temp.expl.spec]p11:
6779 // A trailing template-argument can be left unspecified in the
6780 // template-id naming an explicit function template specialization
6781 // provided it can be deduced from the function argument type.
6782 // Perform template argument deduction to determine whether we may be
6783 // specializing this template.
6784 // FIXME: It is somewhat wasteful to build
6785 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6786 FunctionDecl *Specialization = nullptr;
6787 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6788 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6789 ExplicitTemplateArgs, FT, Specialization, Info)) {
6790 // Template argument deduction failed; record why it failed, so
6791 // that we can provide nifty diagnostics.
6792 FailedCandidates.addCandidate()
6793 .set(FunTmpl->getTemplatedDecl(),
6794 MakeDeductionFailureInfo(Context, TDK, Info));
6795 (void)TDK;
6796 continue;
6797 }
6798
6799 // Record this candidate.
6800 Candidates.addDecl(Specialization, I.getAccess());
6801 }
6802 }
6803
6804 // Find the most specialized function template.
6805 UnresolvedSetIterator Result = getMostSpecialized(
6806 Candidates.begin(), Candidates.end(), FailedCandidates,
6807 FD->getLocation(),
6808 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6809 PDiag(diag::err_function_template_spec_ambiguous)
6810 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6811 PDiag(diag::note_function_template_spec_matched));
6812
6813 if (Result == Candidates.end())
6814 return true;
6815
6816 // Ignore access information; it doesn't figure into redeclaration checking.
6817 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6818
6819 FunctionTemplateSpecializationInfo *SpecInfo
6820 = Specialization->getTemplateSpecializationInfo();
6821 assert(SpecInfo && "Function template specialization info missing?");
6822
6823 // Note: do not overwrite location info if previous template
6824 // specialization kind was explicit.
6825 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6826 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6827 Specialization->setLocation(FD->getLocation());
6828 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6829 // function can differ from the template declaration with respect to
6830 // the constexpr specifier.
6831 Specialization->setConstexpr(FD->isConstexpr());
6832 }
6833
6834 // FIXME: Check if the prior specialization has a point of instantiation.
6835 // If so, we have run afoul of .
6836
6837 // If this is a friend declaration, then we're not really declaring
6838 // an explicit specialization.
6839 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6840
6841 // Check the scope of this explicit specialization.
6842 if (!isFriend &&
6843 CheckTemplateSpecializationScope(*this,
6844 Specialization->getPrimaryTemplate(),
6845 Specialization, FD->getLocation(),
6846 false))
6847 return true;
6848
6849 // C++ [temp.expl.spec]p6:
6850 // If a template, a member template or the member of a class template is
6851 // explicitly specialized then that specialization shall be declared
6852 // before the first use of that specialization that would cause an implicit
6853 // instantiation to take place, in every translation unit in which such a
6854 // use occurs; no diagnostic is required.
6855 bool HasNoEffect = false;
6856 if (!isFriend &&
6857 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6858 TSK_ExplicitSpecialization,
6859 Specialization,
6860 SpecInfo->getTemplateSpecializationKind(),
6861 SpecInfo->getPointOfInstantiation(),
6862 HasNoEffect))
6863 return true;
6864
6865 // Mark the prior declaration as an explicit specialization, so that later
6866 // clients know that this is an explicit specialization.
6867 if (!isFriend) {
6868 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6869 MarkUnusedFileScopedDecl(Specialization);
6870 }
6871
6872 // Turn the given function declaration into a function template
6873 // specialization, with the template arguments from the previous
6874 // specialization.
6875 // Take copies of (semantic and syntactic) template argument lists.
6876 const TemplateArgumentList* TemplArgs = new (Context)
6877 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6878 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6879 TemplArgs, /*InsertPos=*/nullptr,
6880 SpecInfo->getTemplateSpecializationKind(),
6881 ExplicitTemplateArgs);
6882
6883 // The "previous declaration" for this function template specialization is
6884 // the prior function template specialization.
6885 Previous.clear();
6886 Previous.addDecl(Specialization);
6887 return false;
6888 }
6889
6890 /// \brief Perform semantic analysis for the given non-template member
6891 /// specialization.
6892 ///
6893 /// This routine performs all of the semantic analysis required for an
6894 /// explicit member function specialization. On successful completion,
6895 /// the function declaration \p FD will become a member function
6896 /// specialization.
6897 ///
6898 /// \param Member the member declaration, which will be updated to become a
6899 /// specialization.
6900 ///
6901 /// \param Previous the set of declarations, one of which may be specialized
6902 /// by this function specialization; the set will be modified to contain the
6903 /// redeclared member.
6904 bool
CheckMemberSpecialization(NamedDecl * Member,LookupResult & Previous)6905 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6906 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6907
6908 // Try to find the member we are instantiating.
6909 NamedDecl *Instantiation = nullptr;
6910 NamedDecl *InstantiatedFrom = nullptr;
6911 MemberSpecializationInfo *MSInfo = nullptr;
6912
6913 if (Previous.empty()) {
6914 // Nowhere to look anyway.
6915 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6916 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6917 I != E; ++I) {
6918 NamedDecl *D = (*I)->getUnderlyingDecl();
6919 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6920 QualType Adjusted = Function->getType();
6921 if (!hasExplicitCallingConv(Adjusted))
6922 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6923 if (Context.hasSameType(Adjusted, Method->getType())) {
6924 Instantiation = Method;
6925 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6926 MSInfo = Method->getMemberSpecializationInfo();
6927 break;
6928 }
6929 }
6930 }
6931 } else if (isa<VarDecl>(Member)) {
6932 VarDecl *PrevVar;
6933 if (Previous.isSingleResult() &&
6934 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6935 if (PrevVar->isStaticDataMember()) {
6936 Instantiation = PrevVar;
6937 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6938 MSInfo = PrevVar->getMemberSpecializationInfo();
6939 }
6940 } else if (isa<RecordDecl>(Member)) {
6941 CXXRecordDecl *PrevRecord;
6942 if (Previous.isSingleResult() &&
6943 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6944 Instantiation = PrevRecord;
6945 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6946 MSInfo = PrevRecord->getMemberSpecializationInfo();
6947 }
6948 } else if (isa<EnumDecl>(Member)) {
6949 EnumDecl *PrevEnum;
6950 if (Previous.isSingleResult() &&
6951 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6952 Instantiation = PrevEnum;
6953 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6954 MSInfo = PrevEnum->getMemberSpecializationInfo();
6955 }
6956 }
6957
6958 if (!Instantiation) {
6959 // There is no previous declaration that matches. Since member
6960 // specializations are always out-of-line, the caller will complain about
6961 // this mismatch later.
6962 return false;
6963 }
6964
6965 // If this is a friend, just bail out here before we start turning
6966 // things into explicit specializations.
6967 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6968 // Preserve instantiation information.
6969 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6970 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6971 cast<CXXMethodDecl>(InstantiatedFrom),
6972 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6973 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6974 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6975 cast<CXXRecordDecl>(InstantiatedFrom),
6976 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6977 }
6978
6979 Previous.clear();
6980 Previous.addDecl(Instantiation);
6981 return false;
6982 }
6983
6984 // Make sure that this is a specialization of a member.
6985 if (!InstantiatedFrom) {
6986 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6987 << Member;
6988 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6989 return true;
6990 }
6991
6992 // C++ [temp.expl.spec]p6:
6993 // If a template, a member template or the member of a class template is
6994 // explicitly specialized then that specialization shall be declared
6995 // before the first use of that specialization that would cause an implicit
6996 // instantiation to take place, in every translation unit in which such a
6997 // use occurs; no diagnostic is required.
6998 assert(MSInfo && "Member specialization info missing?");
6999
7000 bool HasNoEffect = false;
7001 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7002 TSK_ExplicitSpecialization,
7003 Instantiation,
7004 MSInfo->getTemplateSpecializationKind(),
7005 MSInfo->getPointOfInstantiation(),
7006 HasNoEffect))
7007 return true;
7008
7009 // Check the scope of this explicit specialization.
7010 if (CheckTemplateSpecializationScope(*this,
7011 InstantiatedFrom,
7012 Instantiation, Member->getLocation(),
7013 false))
7014 return true;
7015
7016 // Note that this is an explicit instantiation of a member.
7017 // the original declaration to note that it is an explicit specialization
7018 // (if it was previously an implicit instantiation). This latter step
7019 // makes bookkeeping easier.
7020 if (isa<FunctionDecl>(Member)) {
7021 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7022 if (InstantiationFunction->getTemplateSpecializationKind() ==
7023 TSK_ImplicitInstantiation) {
7024 InstantiationFunction->setTemplateSpecializationKind(
7025 TSK_ExplicitSpecialization);
7026 InstantiationFunction->setLocation(Member->getLocation());
7027 }
7028
7029 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7030 cast<CXXMethodDecl>(InstantiatedFrom),
7031 TSK_ExplicitSpecialization);
7032 MarkUnusedFileScopedDecl(InstantiationFunction);
7033 } else if (isa<VarDecl>(Member)) {
7034 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7035 if (InstantiationVar->getTemplateSpecializationKind() ==
7036 TSK_ImplicitInstantiation) {
7037 InstantiationVar->setTemplateSpecializationKind(
7038 TSK_ExplicitSpecialization);
7039 InstantiationVar->setLocation(Member->getLocation());
7040 }
7041
7042 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7043 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7044 MarkUnusedFileScopedDecl(InstantiationVar);
7045 } else if (isa<CXXRecordDecl>(Member)) {
7046 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7047 if (InstantiationClass->getTemplateSpecializationKind() ==
7048 TSK_ImplicitInstantiation) {
7049 InstantiationClass->setTemplateSpecializationKind(
7050 TSK_ExplicitSpecialization);
7051 InstantiationClass->setLocation(Member->getLocation());
7052 }
7053
7054 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7055 cast<CXXRecordDecl>(InstantiatedFrom),
7056 TSK_ExplicitSpecialization);
7057 } else {
7058 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7059 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7060 if (InstantiationEnum->getTemplateSpecializationKind() ==
7061 TSK_ImplicitInstantiation) {
7062 InstantiationEnum->setTemplateSpecializationKind(
7063 TSK_ExplicitSpecialization);
7064 InstantiationEnum->setLocation(Member->getLocation());
7065 }
7066
7067 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7068 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7069 }
7070
7071 // Save the caller the trouble of having to figure out which declaration
7072 // this specialization matches.
7073 Previous.clear();
7074 Previous.addDecl(Instantiation);
7075 return false;
7076 }
7077
7078 /// \brief Check the scope of an explicit instantiation.
7079 ///
7080 /// \returns true if a serious error occurs, false otherwise.
CheckExplicitInstantiationScope(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName)7081 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7082 SourceLocation InstLoc,
7083 bool WasQualifiedName) {
7084 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7085 DeclContext *CurContext = S.CurContext->getRedeclContext();
7086
7087 if (CurContext->isRecord()) {
7088 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7089 << D;
7090 return true;
7091 }
7092
7093 // C++11 [temp.explicit]p3:
7094 // An explicit instantiation shall appear in an enclosing namespace of its
7095 // template. If the name declared in the explicit instantiation is an
7096 // unqualified name, the explicit instantiation shall appear in the
7097 // namespace where its template is declared or, if that namespace is inline
7098 // (7.3.1), any namespace from its enclosing namespace set.
7099 //
7100 // This is DR275, which we do not retroactively apply to C++98/03.
7101 if (WasQualifiedName) {
7102 if (CurContext->Encloses(OrigContext))
7103 return false;
7104 } else {
7105 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7106 return false;
7107 }
7108
7109 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7110 if (WasQualifiedName)
7111 S.Diag(InstLoc,
7112 S.getLangOpts().CPlusPlus11?
7113 diag::err_explicit_instantiation_out_of_scope :
7114 diag::warn_explicit_instantiation_out_of_scope_0x)
7115 << D << NS;
7116 else
7117 S.Diag(InstLoc,
7118 S.getLangOpts().CPlusPlus11?
7119 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7120 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7121 << D << NS;
7122 } else
7123 S.Diag(InstLoc,
7124 S.getLangOpts().CPlusPlus11?
7125 diag::err_explicit_instantiation_must_be_global :
7126 diag::warn_explicit_instantiation_must_be_global_0x)
7127 << D;
7128 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7129 return false;
7130 }
7131
7132 /// \brief Determine whether the given scope specifier has a template-id in it.
ScopeSpecifierHasTemplateId(const CXXScopeSpec & SS)7133 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7134 if (!SS.isSet())
7135 return false;
7136
7137 // C++11 [temp.explicit]p3:
7138 // If the explicit instantiation is for a member function, a member class
7139 // or a static data member of a class template specialization, the name of
7140 // the class template specialization in the qualified-id for the member
7141 // name shall be a simple-template-id.
7142 //
7143 // C++98 has the same restriction, just worded differently.
7144 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7145 NNS = NNS->getPrefix())
7146 if (const Type *T = NNS->getAsType())
7147 if (isa<TemplateSpecializationType>(T))
7148 return true;
7149
7150 return false;
7151 }
7152
7153 // Explicit instantiation of a class template specialization
7154 DeclResult
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,const CXXScopeSpec & SS,TemplateTy TemplateD,SourceLocation TemplateNameLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,AttributeList * Attr)7155 Sema::ActOnExplicitInstantiation(Scope *S,
7156 SourceLocation ExternLoc,
7157 SourceLocation TemplateLoc,
7158 unsigned TagSpec,
7159 SourceLocation KWLoc,
7160 const CXXScopeSpec &SS,
7161 TemplateTy TemplateD,
7162 SourceLocation TemplateNameLoc,
7163 SourceLocation LAngleLoc,
7164 ASTTemplateArgsPtr TemplateArgsIn,
7165 SourceLocation RAngleLoc,
7166 AttributeList *Attr) {
7167 // Find the class template we're specializing
7168 TemplateName Name = TemplateD.get();
7169 TemplateDecl *TD = Name.getAsTemplateDecl();
7170 // Check that the specialization uses the same tag kind as the
7171 // original template.
7172 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7173 assert(Kind != TTK_Enum &&
7174 "Invalid enum tag in class template explicit instantiation!");
7175
7176 if (isa<TypeAliasTemplateDecl>(TD)) {
7177 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7178 Diag(TD->getTemplatedDecl()->getLocation(),
7179 diag::note_previous_use);
7180 return true;
7181 }
7182
7183 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7184
7185 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7186 Kind, /*isDefinition*/false, KWLoc,
7187 *ClassTemplate->getIdentifier())) {
7188 Diag(KWLoc, diag::err_use_with_wrong_tag)
7189 << ClassTemplate
7190 << FixItHint::CreateReplacement(KWLoc,
7191 ClassTemplate->getTemplatedDecl()->getKindName());
7192 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7193 diag::note_previous_use);
7194 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7195 }
7196
7197 // C++0x [temp.explicit]p2:
7198 // There are two forms of explicit instantiation: an explicit instantiation
7199 // definition and an explicit instantiation declaration. An explicit
7200 // instantiation declaration begins with the extern keyword. [...]
7201 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7202 ? TSK_ExplicitInstantiationDefinition
7203 : TSK_ExplicitInstantiationDeclaration;
7204
7205 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7206 // Check for dllexport class template instantiation declarations.
7207 for (AttributeList *A = Attr; A; A = A->getNext()) {
7208 if (A->getKind() == AttributeList::AT_DLLExport) {
7209 Diag(ExternLoc,
7210 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7211 Diag(A->getLoc(), diag::note_attribute);
7212 break;
7213 }
7214 }
7215
7216 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7217 Diag(ExternLoc,
7218 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7219 Diag(A->getLocation(), diag::note_attribute);
7220 }
7221 }
7222
7223 // Translate the parser's template argument list in our AST format.
7224 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7225 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7226
7227 // Check that the template argument list is well-formed for this
7228 // template.
7229 SmallVector<TemplateArgument, 4> Converted;
7230 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7231 TemplateArgs, false, Converted))
7232 return true;
7233
7234 // Find the class template specialization declaration that
7235 // corresponds to these arguments.
7236 void *InsertPos = nullptr;
7237 ClassTemplateSpecializationDecl *PrevDecl
7238 = ClassTemplate->findSpecialization(Converted, InsertPos);
7239
7240 TemplateSpecializationKind PrevDecl_TSK
7241 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7242
7243 // C++0x [temp.explicit]p2:
7244 // [...] An explicit instantiation shall appear in an enclosing
7245 // namespace of its template. [...]
7246 //
7247 // This is C++ DR 275.
7248 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7249 SS.isSet()))
7250 return true;
7251
7252 ClassTemplateSpecializationDecl *Specialization = nullptr;
7253
7254 bool HasNoEffect = false;
7255 if (PrevDecl) {
7256 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7257 PrevDecl, PrevDecl_TSK,
7258 PrevDecl->getPointOfInstantiation(),
7259 HasNoEffect))
7260 return PrevDecl;
7261
7262 // Even though HasNoEffect == true means that this explicit instantiation
7263 // has no effect on semantics, we go on to put its syntax in the AST.
7264
7265 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7266 PrevDecl_TSK == TSK_Undeclared) {
7267 // Since the only prior class template specialization with these
7268 // arguments was referenced but not declared, reuse that
7269 // declaration node as our own, updating the source location
7270 // for the template name to reflect our new declaration.
7271 // (Other source locations will be updated later.)
7272 Specialization = PrevDecl;
7273 Specialization->setLocation(TemplateNameLoc);
7274 PrevDecl = nullptr;
7275 }
7276 }
7277
7278 if (!Specialization) {
7279 // Create a new class template specialization declaration node for
7280 // this explicit specialization.
7281 Specialization
7282 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7283 ClassTemplate->getDeclContext(),
7284 KWLoc, TemplateNameLoc,
7285 ClassTemplate,
7286 Converted.data(),
7287 Converted.size(),
7288 PrevDecl);
7289 SetNestedNameSpecifier(Specialization, SS);
7290
7291 if (!HasNoEffect && !PrevDecl) {
7292 // Insert the new specialization.
7293 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7294 }
7295 }
7296
7297 // Build the fully-sugared type for this explicit instantiation as
7298 // the user wrote in the explicit instantiation itself. This means
7299 // that we'll pretty-print the type retrieved from the
7300 // specialization's declaration the way that the user actually wrote
7301 // the explicit instantiation, rather than formatting the name based
7302 // on the "canonical" representation used to store the template
7303 // arguments in the specialization.
7304 TypeSourceInfo *WrittenTy
7305 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7306 TemplateArgs,
7307 Context.getTypeDeclType(Specialization));
7308 Specialization->setTypeAsWritten(WrittenTy);
7309
7310 // Set source locations for keywords.
7311 Specialization->setExternLoc(ExternLoc);
7312 Specialization->setTemplateKeywordLoc(TemplateLoc);
7313 Specialization->setRBraceLoc(SourceLocation());
7314
7315 if (Attr)
7316 ProcessDeclAttributeList(S, Specialization, Attr);
7317
7318 // Add the explicit instantiation into its lexical context. However,
7319 // since explicit instantiations are never found by name lookup, we
7320 // just put it into the declaration context directly.
7321 Specialization->setLexicalDeclContext(CurContext);
7322 CurContext->addDecl(Specialization);
7323
7324 // Syntax is now OK, so return if it has no other effect on semantics.
7325 if (HasNoEffect) {
7326 // Set the template specialization kind.
7327 Specialization->setTemplateSpecializationKind(TSK);
7328 return Specialization;
7329 }
7330
7331 // C++ [temp.explicit]p3:
7332 // A definition of a class template or class member template
7333 // shall be in scope at the point of the explicit instantiation of
7334 // the class template or class member template.
7335 //
7336 // This check comes when we actually try to perform the
7337 // instantiation.
7338 ClassTemplateSpecializationDecl *Def
7339 = cast_or_null<ClassTemplateSpecializationDecl>(
7340 Specialization->getDefinition());
7341 if (!Def)
7342 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7343 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7344 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7345 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7346 }
7347
7348 // Instantiate the members of this class template specialization.
7349 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7350 Specialization->getDefinition());
7351 if (Def) {
7352 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7353
7354 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7355 // TSK_ExplicitInstantiationDefinition
7356 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7357 TSK == TSK_ExplicitInstantiationDefinition)
7358 // FIXME: Need to notify the ASTMutationListener that we did this.
7359 Def->setTemplateSpecializationKind(TSK);
7360
7361 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7362 }
7363
7364 // Set the template specialization kind.
7365 Specialization->setTemplateSpecializationKind(TSK);
7366 return Specialization;
7367 }
7368
7369 // Explicit instantiation of a member class of a class template.
7370 DeclResult
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr)7371 Sema::ActOnExplicitInstantiation(Scope *S,
7372 SourceLocation ExternLoc,
7373 SourceLocation TemplateLoc,
7374 unsigned TagSpec,
7375 SourceLocation KWLoc,
7376 CXXScopeSpec &SS,
7377 IdentifierInfo *Name,
7378 SourceLocation NameLoc,
7379 AttributeList *Attr) {
7380
7381 bool Owned = false;
7382 bool IsDependent = false;
7383 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7384 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7385 /*ModulePrivateLoc=*/SourceLocation(),
7386 MultiTemplateParamsArg(), Owned, IsDependent,
7387 SourceLocation(), false, TypeResult(),
7388 /*IsTypeSpecifier*/false);
7389 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7390
7391 if (!TagD)
7392 return true;
7393
7394 TagDecl *Tag = cast<TagDecl>(TagD);
7395 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7396
7397 if (Tag->isInvalidDecl())
7398 return true;
7399
7400 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7401 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7402 if (!Pattern) {
7403 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7404 << Context.getTypeDeclType(Record);
7405 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7406 return true;
7407 }
7408
7409 // C++0x [temp.explicit]p2:
7410 // If the explicit instantiation is for a class or member class, the
7411 // elaborated-type-specifier in the declaration shall include a
7412 // simple-template-id.
7413 //
7414 // C++98 has the same restriction, just worded differently.
7415 if (!ScopeSpecifierHasTemplateId(SS))
7416 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7417 << Record << SS.getRange();
7418
7419 // C++0x [temp.explicit]p2:
7420 // There are two forms of explicit instantiation: an explicit instantiation
7421 // definition and an explicit instantiation declaration. An explicit
7422 // instantiation declaration begins with the extern keyword. [...]
7423 TemplateSpecializationKind TSK
7424 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7425 : TSK_ExplicitInstantiationDeclaration;
7426
7427 // C++0x [temp.explicit]p2:
7428 // [...] An explicit instantiation shall appear in an enclosing
7429 // namespace of its template. [...]
7430 //
7431 // This is C++ DR 275.
7432 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7433
7434 // Verify that it is okay to explicitly instantiate here.
7435 CXXRecordDecl *PrevDecl
7436 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7437 if (!PrevDecl && Record->getDefinition())
7438 PrevDecl = Record;
7439 if (PrevDecl) {
7440 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7441 bool HasNoEffect = false;
7442 assert(MSInfo && "No member specialization information?");
7443 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7444 PrevDecl,
7445 MSInfo->getTemplateSpecializationKind(),
7446 MSInfo->getPointOfInstantiation(),
7447 HasNoEffect))
7448 return true;
7449 if (HasNoEffect)
7450 return TagD;
7451 }
7452
7453 CXXRecordDecl *RecordDef
7454 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7455 if (!RecordDef) {
7456 // C++ [temp.explicit]p3:
7457 // A definition of a member class of a class template shall be in scope
7458 // at the point of an explicit instantiation of the member class.
7459 CXXRecordDecl *Def
7460 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7461 if (!Def) {
7462 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7463 << 0 << Record->getDeclName() << Record->getDeclContext();
7464 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7465 << Pattern;
7466 return true;
7467 } else {
7468 if (InstantiateClass(NameLoc, Record, Def,
7469 getTemplateInstantiationArgs(Record),
7470 TSK))
7471 return true;
7472
7473 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7474 if (!RecordDef)
7475 return true;
7476 }
7477 }
7478
7479 // Instantiate all of the members of the class.
7480 InstantiateClassMembers(NameLoc, RecordDef,
7481 getTemplateInstantiationArgs(Record), TSK);
7482
7483 if (TSK == TSK_ExplicitInstantiationDefinition)
7484 MarkVTableUsed(NameLoc, RecordDef, true);
7485
7486 // FIXME: We don't have any representation for explicit instantiations of
7487 // member classes. Such a representation is not needed for compilation, but it
7488 // should be available for clients that want to see all of the declarations in
7489 // the source code.
7490 return TagD;
7491 }
7492
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,Declarator & D)7493 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7494 SourceLocation ExternLoc,
7495 SourceLocation TemplateLoc,
7496 Declarator &D) {
7497 // Explicit instantiations always require a name.
7498 // TODO: check if/when DNInfo should replace Name.
7499 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7500 DeclarationName Name = NameInfo.getName();
7501 if (!Name) {
7502 if (!D.isInvalidType())
7503 Diag(D.getDeclSpec().getLocStart(),
7504 diag::err_explicit_instantiation_requires_name)
7505 << D.getDeclSpec().getSourceRange()
7506 << D.getSourceRange();
7507
7508 return true;
7509 }
7510
7511 // The scope passed in may not be a decl scope. Zip up the scope tree until
7512 // we find one that is.
7513 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7514 (S->getFlags() & Scope::TemplateParamScope) != 0)
7515 S = S->getParent();
7516
7517 // Determine the type of the declaration.
7518 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7519 QualType R = T->getType();
7520 if (R.isNull())
7521 return true;
7522
7523 // C++ [dcl.stc]p1:
7524 // A storage-class-specifier shall not be specified in [...] an explicit
7525 // instantiation (14.7.2) directive.
7526 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7527 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7528 << Name;
7529 return true;
7530 } else if (D.getDeclSpec().getStorageClassSpec()
7531 != DeclSpec::SCS_unspecified) {
7532 // Complain about then remove the storage class specifier.
7533 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7534 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7535
7536 D.getMutableDeclSpec().ClearStorageClassSpecs();
7537 }
7538
7539 // C++0x [temp.explicit]p1:
7540 // [...] An explicit instantiation of a function template shall not use the
7541 // inline or constexpr specifiers.
7542 // Presumably, this also applies to member functions of class templates as
7543 // well.
7544 if (D.getDeclSpec().isInlineSpecified())
7545 Diag(D.getDeclSpec().getInlineSpecLoc(),
7546 getLangOpts().CPlusPlus11 ?
7547 diag::err_explicit_instantiation_inline :
7548 diag::warn_explicit_instantiation_inline_0x)
7549 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7550 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7551 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7552 // not already specified.
7553 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7554 diag::err_explicit_instantiation_constexpr);
7555
7556 // C++0x [temp.explicit]p2:
7557 // There are two forms of explicit instantiation: an explicit instantiation
7558 // definition and an explicit instantiation declaration. An explicit
7559 // instantiation declaration begins with the extern keyword. [...]
7560 TemplateSpecializationKind TSK
7561 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7562 : TSK_ExplicitInstantiationDeclaration;
7563
7564 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7565 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7566
7567 if (!R->isFunctionType()) {
7568 // C++ [temp.explicit]p1:
7569 // A [...] static data member of a class template can be explicitly
7570 // instantiated from the member definition associated with its class
7571 // template.
7572 // C++1y [temp.explicit]p1:
7573 // A [...] variable [...] template specialization can be explicitly
7574 // instantiated from its template.
7575 if (Previous.isAmbiguous())
7576 return true;
7577
7578 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7579 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7580
7581 if (!PrevTemplate) {
7582 if (!Prev || !Prev->isStaticDataMember()) {
7583 // We expect to see a data data member here.
7584 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7585 << Name;
7586 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7587 P != PEnd; ++P)
7588 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7589 return true;
7590 }
7591
7592 if (!Prev->getInstantiatedFromStaticDataMember()) {
7593 // FIXME: Check for explicit specialization?
7594 Diag(D.getIdentifierLoc(),
7595 diag::err_explicit_instantiation_data_member_not_instantiated)
7596 << Prev;
7597 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7598 // FIXME: Can we provide a note showing where this was declared?
7599 return true;
7600 }
7601 } else {
7602 // Explicitly instantiate a variable template.
7603
7604 // C++1y [dcl.spec.auto]p6:
7605 // ... A program that uses auto or decltype(auto) in a context not
7606 // explicitly allowed in this section is ill-formed.
7607 //
7608 // This includes auto-typed variable template instantiations.
7609 if (R->isUndeducedType()) {
7610 Diag(T->getTypeLoc().getLocStart(),
7611 diag::err_auto_not_allowed_var_inst);
7612 return true;
7613 }
7614
7615 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7616 // C++1y [temp.explicit]p3:
7617 // If the explicit instantiation is for a variable, the unqualified-id
7618 // in the declaration shall be a template-id.
7619 Diag(D.getIdentifierLoc(),
7620 diag::err_explicit_instantiation_without_template_id)
7621 << PrevTemplate;
7622 Diag(PrevTemplate->getLocation(),
7623 diag::note_explicit_instantiation_here);
7624 return true;
7625 }
7626
7627 // Translate the parser's template argument list into our AST format.
7628 TemplateArgumentListInfo TemplateArgs =
7629 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7630
7631 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7632 D.getIdentifierLoc(), TemplateArgs);
7633 if (Res.isInvalid())
7634 return true;
7635
7636 // Ignore access control bits, we don't need them for redeclaration
7637 // checking.
7638 Prev = cast<VarDecl>(Res.get());
7639 }
7640
7641 // C++0x [temp.explicit]p2:
7642 // If the explicit instantiation is for a member function, a member class
7643 // or a static data member of a class template specialization, the name of
7644 // the class template specialization in the qualified-id for the member
7645 // name shall be a simple-template-id.
7646 //
7647 // C++98 has the same restriction, just worded differently.
7648 //
7649 // This does not apply to variable template specializations, where the
7650 // template-id is in the unqualified-id instead.
7651 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7652 Diag(D.getIdentifierLoc(),
7653 diag::ext_explicit_instantiation_without_qualified_id)
7654 << Prev << D.getCXXScopeSpec().getRange();
7655
7656 // Check the scope of this explicit instantiation.
7657 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7658
7659 // Verify that it is okay to explicitly instantiate here.
7660 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7661 SourceLocation POI = Prev->getPointOfInstantiation();
7662 bool HasNoEffect = false;
7663 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7664 PrevTSK, POI, HasNoEffect))
7665 return true;
7666
7667 if (!HasNoEffect) {
7668 // Instantiate static data member or variable template.
7669
7670 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7671 if (PrevTemplate) {
7672 // Merge attributes.
7673 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7674 ProcessDeclAttributeList(S, Prev, Attr);
7675 }
7676 if (TSK == TSK_ExplicitInstantiationDefinition)
7677 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7678 }
7679
7680 // Check the new variable specialization against the parsed input.
7681 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7682 Diag(T->getTypeLoc().getLocStart(),
7683 diag::err_invalid_var_template_spec_type)
7684 << 0 << PrevTemplate << R << Prev->getType();
7685 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7686 << 2 << PrevTemplate->getDeclName();
7687 return true;
7688 }
7689
7690 // FIXME: Create an ExplicitInstantiation node?
7691 return (Decl*) nullptr;
7692 }
7693
7694 // If the declarator is a template-id, translate the parser's template
7695 // argument list into our AST format.
7696 bool HasExplicitTemplateArgs = false;
7697 TemplateArgumentListInfo TemplateArgs;
7698 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7699 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7700 HasExplicitTemplateArgs = true;
7701 }
7702
7703 // C++ [temp.explicit]p1:
7704 // A [...] function [...] can be explicitly instantiated from its template.
7705 // A member function [...] of a class template can be explicitly
7706 // instantiated from the member definition associated with its class
7707 // template.
7708 UnresolvedSet<8> Matches;
7709 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7710 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7711 P != PEnd; ++P) {
7712 NamedDecl *Prev = *P;
7713 if (!HasExplicitTemplateArgs) {
7714 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7715 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7716 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7717 Matches.clear();
7718
7719 Matches.addDecl(Method, P.getAccess());
7720 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7721 break;
7722 }
7723 }
7724 }
7725
7726 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7727 if (!FunTmpl)
7728 continue;
7729
7730 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7731 FunctionDecl *Specialization = nullptr;
7732 if (TemplateDeductionResult TDK
7733 = DeduceTemplateArguments(FunTmpl,
7734 (HasExplicitTemplateArgs ? &TemplateArgs
7735 : nullptr),
7736 R, Specialization, Info)) {
7737 // Keep track of almost-matches.
7738 FailedCandidates.addCandidate()
7739 .set(FunTmpl->getTemplatedDecl(),
7740 MakeDeductionFailureInfo(Context, TDK, Info));
7741 (void)TDK;
7742 continue;
7743 }
7744
7745 Matches.addDecl(Specialization, P.getAccess());
7746 }
7747
7748 // Find the most specialized function template specialization.
7749 UnresolvedSetIterator Result = getMostSpecialized(
7750 Matches.begin(), Matches.end(), FailedCandidates,
7751 D.getIdentifierLoc(),
7752 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7753 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7754 PDiag(diag::note_explicit_instantiation_candidate));
7755
7756 if (Result == Matches.end())
7757 return true;
7758
7759 // Ignore access control bits, we don't need them for redeclaration checking.
7760 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7761
7762 // C++11 [except.spec]p4
7763 // In an explicit instantiation an exception-specification may be specified,
7764 // but is not required.
7765 // If an exception-specification is specified in an explicit instantiation
7766 // directive, it shall be compatible with the exception-specifications of
7767 // other declarations of that function.
7768 if (auto *FPT = R->getAs<FunctionProtoType>())
7769 if (FPT->hasExceptionSpec()) {
7770 unsigned DiagID =
7771 diag::err_mismatched_exception_spec_explicit_instantiation;
7772 if (getLangOpts().MicrosoftExt)
7773 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7774 bool Result = CheckEquivalentExceptionSpec(
7775 PDiag(DiagID) << Specialization->getType(),
7776 PDiag(diag::note_explicit_instantiation_here),
7777 Specialization->getType()->getAs<FunctionProtoType>(),
7778 Specialization->getLocation(), FPT, D.getLocStart());
7779 // In Microsoft mode, mismatching exception specifications just cause a
7780 // warning.
7781 if (!getLangOpts().MicrosoftExt && Result)
7782 return true;
7783 }
7784
7785 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7786 Diag(D.getIdentifierLoc(),
7787 diag::err_explicit_instantiation_member_function_not_instantiated)
7788 << Specialization
7789 << (Specialization->getTemplateSpecializationKind() ==
7790 TSK_ExplicitSpecialization);
7791 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7792 return true;
7793 }
7794
7795 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7796 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7797 PrevDecl = Specialization;
7798
7799 if (PrevDecl) {
7800 bool HasNoEffect = false;
7801 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7802 PrevDecl,
7803 PrevDecl->getTemplateSpecializationKind(),
7804 PrevDecl->getPointOfInstantiation(),
7805 HasNoEffect))
7806 return true;
7807
7808 // FIXME: We may still want to build some representation of this
7809 // explicit specialization.
7810 if (HasNoEffect)
7811 return (Decl*) nullptr;
7812 }
7813
7814 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7815 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7816 if (Attr)
7817 ProcessDeclAttributeList(S, Specialization, Attr);
7818
7819 if (Specialization->isDefined()) {
7820 // Let the ASTConsumer know that this function has been explicitly
7821 // instantiated now, and its linkage might have changed.
7822 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7823 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7824 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7825
7826 // C++0x [temp.explicit]p2:
7827 // If the explicit instantiation is for a member function, a member class
7828 // or a static data member of a class template specialization, the name of
7829 // the class template specialization in the qualified-id for the member
7830 // name shall be a simple-template-id.
7831 //
7832 // C++98 has the same restriction, just worded differently.
7833 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7834 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7835 D.getCXXScopeSpec().isSet() &&
7836 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7837 Diag(D.getIdentifierLoc(),
7838 diag::ext_explicit_instantiation_without_qualified_id)
7839 << Specialization << D.getCXXScopeSpec().getRange();
7840
7841 CheckExplicitInstantiationScope(*this,
7842 FunTmpl? (NamedDecl *)FunTmpl
7843 : Specialization->getInstantiatedFromMemberFunction(),
7844 D.getIdentifierLoc(),
7845 D.getCXXScopeSpec().isSet());
7846
7847 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7848 return (Decl*) nullptr;
7849 }
7850
7851 TypeResult
ActOnDependentTag(Scope * S,unsigned TagSpec,TagUseKind TUK,const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation TagLoc,SourceLocation NameLoc)7852 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7853 const CXXScopeSpec &SS, IdentifierInfo *Name,
7854 SourceLocation TagLoc, SourceLocation NameLoc) {
7855 // This has to hold, because SS is expected to be defined.
7856 assert(Name && "Expected a name in a dependent tag");
7857
7858 NestedNameSpecifier *NNS = SS.getScopeRep();
7859 if (!NNS)
7860 return true;
7861
7862 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7863
7864 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7865 Diag(NameLoc, diag::err_dependent_tag_decl)
7866 << (TUK == TUK_Definition) << Kind << SS.getRange();
7867 return true;
7868 }
7869
7870 // Create the resulting type.
7871 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7872 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7873
7874 // Create type-source location information for this type.
7875 TypeLocBuilder TLB;
7876 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7877 TL.setElaboratedKeywordLoc(TagLoc);
7878 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7879 TL.setNameLoc(NameLoc);
7880 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7881 }
7882
7883 TypeResult
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,const IdentifierInfo & II,SourceLocation IdLoc)7884 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7885 const CXXScopeSpec &SS, const IdentifierInfo &II,
7886 SourceLocation IdLoc) {
7887 if (SS.isInvalid())
7888 return true;
7889
7890 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7891 Diag(TypenameLoc,
7892 getLangOpts().CPlusPlus11 ?
7893 diag::warn_cxx98_compat_typename_outside_of_template :
7894 diag::ext_typename_outside_of_template)
7895 << FixItHint::CreateRemoval(TypenameLoc);
7896
7897 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7898 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7899 TypenameLoc, QualifierLoc, II, IdLoc);
7900 if (T.isNull())
7901 return true;
7902
7903 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7904 if (isa<DependentNameType>(T)) {
7905 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7906 TL.setElaboratedKeywordLoc(TypenameLoc);
7907 TL.setQualifierLoc(QualifierLoc);
7908 TL.setNameLoc(IdLoc);
7909 } else {
7910 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7911 TL.setElaboratedKeywordLoc(TypenameLoc);
7912 TL.setQualifierLoc(QualifierLoc);
7913 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7914 }
7915
7916 return CreateParsedType(T, TSI);
7917 }
7918
7919 TypeResult
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateIn,SourceLocation TemplateNameLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)7920 Sema::ActOnTypenameType(Scope *S,
7921 SourceLocation TypenameLoc,
7922 const CXXScopeSpec &SS,
7923 SourceLocation TemplateKWLoc,
7924 TemplateTy TemplateIn,
7925 SourceLocation TemplateNameLoc,
7926 SourceLocation LAngleLoc,
7927 ASTTemplateArgsPtr TemplateArgsIn,
7928 SourceLocation RAngleLoc) {
7929 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7930 Diag(TypenameLoc,
7931 getLangOpts().CPlusPlus11 ?
7932 diag::warn_cxx98_compat_typename_outside_of_template :
7933 diag::ext_typename_outside_of_template)
7934 << FixItHint::CreateRemoval(TypenameLoc);
7935
7936 // Translate the parser's template argument list in our AST format.
7937 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7938 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7939
7940 TemplateName Template = TemplateIn.get();
7941 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7942 // Construct a dependent template specialization type.
7943 assert(DTN && "dependent template has non-dependent name?");
7944 assert(DTN->getQualifier() == SS.getScopeRep());
7945 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7946 DTN->getQualifier(),
7947 DTN->getIdentifier(),
7948 TemplateArgs);
7949
7950 // Create source-location information for this type.
7951 TypeLocBuilder Builder;
7952 DependentTemplateSpecializationTypeLoc SpecTL
7953 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7954 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7955 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7956 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7957 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7958 SpecTL.setLAngleLoc(LAngleLoc);
7959 SpecTL.setRAngleLoc(RAngleLoc);
7960 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7961 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7962 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7963 }
7964
7965 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7966 if (T.isNull())
7967 return true;
7968
7969 // Provide source-location information for the template specialization type.
7970 TypeLocBuilder Builder;
7971 TemplateSpecializationTypeLoc SpecTL
7972 = Builder.push<TemplateSpecializationTypeLoc>(T);
7973 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7974 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7975 SpecTL.setLAngleLoc(LAngleLoc);
7976 SpecTL.setRAngleLoc(RAngleLoc);
7977 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7978 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7979
7980 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7981 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
7982 TL.setElaboratedKeywordLoc(TypenameLoc);
7983 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7984
7985 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7986 return CreateParsedType(T, TSI);
7987 }
7988
7989
7990 /// Determine whether this failed name lookup should be treated as being
7991 /// disabled by a usage of std::enable_if.
isEnableIf(NestedNameSpecifierLoc NNS,const IdentifierInfo & II,SourceRange & CondRange)7992 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7993 SourceRange &CondRange) {
7994 // We must be looking for a ::type...
7995 if (!II.isStr("type"))
7996 return false;
7997
7998 // ... within an explicitly-written template specialization...
7999 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8000 return false;
8001 TypeLoc EnableIfTy = NNS.getTypeLoc();
8002 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8003 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8004 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8005 return false;
8006 const TemplateSpecializationType *EnableIfTST =
8007 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8008
8009 // ... which names a complete class template declaration...
8010 const TemplateDecl *EnableIfDecl =
8011 EnableIfTST->getTemplateName().getAsTemplateDecl();
8012 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8013 return false;
8014
8015 // ... called "enable_if".
8016 const IdentifierInfo *EnableIfII =
8017 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8018 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8019 return false;
8020
8021 // Assume the first template argument is the condition.
8022 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8023 return true;
8024 }
8025
8026 /// \brief Build the type that describes a C++ typename specifier,
8027 /// e.g., "typename T::type".
8028 QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc)8029 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8030 SourceLocation KeywordLoc,
8031 NestedNameSpecifierLoc QualifierLoc,
8032 const IdentifierInfo &II,
8033 SourceLocation IILoc) {
8034 CXXScopeSpec SS;
8035 SS.Adopt(QualifierLoc);
8036
8037 DeclContext *Ctx = computeDeclContext(SS);
8038 if (!Ctx) {
8039 // If the nested-name-specifier is dependent and couldn't be
8040 // resolved to a type, build a typename type.
8041 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8042 return Context.getDependentNameType(Keyword,
8043 QualifierLoc.getNestedNameSpecifier(),
8044 &II);
8045 }
8046
8047 // If the nested-name-specifier refers to the current instantiation,
8048 // the "typename" keyword itself is superfluous. In C++03, the
8049 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8050 // allows such extraneous "typename" keywords, and we retroactively
8051 // apply this DR to C++03 code with only a warning. In any case we continue.
8052
8053 if (RequireCompleteDeclContext(SS, Ctx))
8054 return QualType();
8055
8056 DeclarationName Name(&II);
8057 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8058 LookupQualifiedName(Result, Ctx, SS);
8059 unsigned DiagID = 0;
8060 Decl *Referenced = nullptr;
8061 switch (Result.getResultKind()) {
8062 case LookupResult::NotFound: {
8063 // If we're looking up 'type' within a template named 'enable_if', produce
8064 // a more specific diagnostic.
8065 SourceRange CondRange;
8066 if (isEnableIf(QualifierLoc, II, CondRange)) {
8067 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8068 << Ctx << CondRange;
8069 return QualType();
8070 }
8071
8072 DiagID = diag::err_typename_nested_not_found;
8073 break;
8074 }
8075
8076 case LookupResult::FoundUnresolvedValue: {
8077 // We found a using declaration that is a value. Most likely, the using
8078 // declaration itself is meant to have the 'typename' keyword.
8079 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8080 IILoc);
8081 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8082 << Name << Ctx << FullRange;
8083 if (UnresolvedUsingValueDecl *Using
8084 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8085 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8086 Diag(Loc, diag::note_using_value_decl_missing_typename)
8087 << FixItHint::CreateInsertion(Loc, "typename ");
8088 }
8089 }
8090 // Fall through to create a dependent typename type, from which we can recover
8091 // better.
8092
8093 case LookupResult::NotFoundInCurrentInstantiation:
8094 // Okay, it's a member of an unknown instantiation.
8095 return Context.getDependentNameType(Keyword,
8096 QualifierLoc.getNestedNameSpecifier(),
8097 &II);
8098
8099 case LookupResult::Found:
8100 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8101 // We found a type. Build an ElaboratedType, since the
8102 // typename-specifier was just sugar.
8103 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8104 return Context.getElaboratedType(ETK_Typename,
8105 QualifierLoc.getNestedNameSpecifier(),
8106 Context.getTypeDeclType(Type));
8107 }
8108
8109 DiagID = diag::err_typename_nested_not_type;
8110 Referenced = Result.getFoundDecl();
8111 break;
8112
8113 case LookupResult::FoundOverloaded:
8114 DiagID = diag::err_typename_nested_not_type;
8115 Referenced = *Result.begin();
8116 break;
8117
8118 case LookupResult::Ambiguous:
8119 return QualType();
8120 }
8121
8122 // If we get here, it's because name lookup did not find a
8123 // type. Emit an appropriate diagnostic and return an error.
8124 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8125 IILoc);
8126 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8127 if (Referenced)
8128 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8129 << Name;
8130 return QualType();
8131 }
8132
8133 namespace {
8134 // See Sema::RebuildTypeInCurrentInstantiation
8135 class CurrentInstantiationRebuilder
8136 : public TreeTransform<CurrentInstantiationRebuilder> {
8137 SourceLocation Loc;
8138 DeclarationName Entity;
8139
8140 public:
8141 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8142
CurrentInstantiationRebuilder(Sema & SemaRef,SourceLocation Loc,DeclarationName Entity)8143 CurrentInstantiationRebuilder(Sema &SemaRef,
8144 SourceLocation Loc,
8145 DeclarationName Entity)
8146 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8147 Loc(Loc), Entity(Entity) { }
8148
8149 /// \brief Determine whether the given type \p T has already been
8150 /// transformed.
8151 ///
8152 /// For the purposes of type reconstruction, a type has already been
8153 /// transformed if it is NULL or if it is not dependent.
AlreadyTransformed(QualType T)8154 bool AlreadyTransformed(QualType T) {
8155 return T.isNull() || !T->isDependentType();
8156 }
8157
8158 /// \brief Returns the location of the entity whose type is being
8159 /// rebuilt.
getBaseLocation()8160 SourceLocation getBaseLocation() { return Loc; }
8161
8162 /// \brief Returns the name of the entity whose type is being rebuilt.
getBaseEntity()8163 DeclarationName getBaseEntity() { return Entity; }
8164
8165 /// \brief Sets the "base" location and entity when that
8166 /// information is known based on another transformation.
setBase(SourceLocation Loc,DeclarationName Entity)8167 void setBase(SourceLocation Loc, DeclarationName Entity) {
8168 this->Loc = Loc;
8169 this->Entity = Entity;
8170 }
8171
TransformLambdaExpr(LambdaExpr * E)8172 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8173 // Lambdas never need to be transformed.
8174 return E;
8175 }
8176 };
8177 }
8178
8179 /// \brief Rebuilds a type within the context of the current instantiation.
8180 ///
8181 /// The type \p T is part of the type of an out-of-line member definition of
8182 /// a class template (or class template partial specialization) that was parsed
8183 /// and constructed before we entered the scope of the class template (or
8184 /// partial specialization thereof). This routine will rebuild that type now
8185 /// that we have entered the declarator's scope, which may produce different
8186 /// canonical types, e.g.,
8187 ///
8188 /// \code
8189 /// template<typename T>
8190 /// struct X {
8191 /// typedef T* pointer;
8192 /// pointer data();
8193 /// };
8194 ///
8195 /// template<typename T>
8196 /// typename X<T>::pointer X<T>::data() { ... }
8197 /// \endcode
8198 ///
8199 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8200 /// since we do not know that we can look into X<T> when we parsed the type.
8201 /// This function will rebuild the type, performing the lookup of "pointer"
8202 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8203 /// as the canonical type of T*, allowing the return types of the out-of-line
8204 /// definition and the declaration to match.
RebuildTypeInCurrentInstantiation(TypeSourceInfo * T,SourceLocation Loc,DeclarationName Name)8205 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8206 SourceLocation Loc,
8207 DeclarationName Name) {
8208 if (!T || !T->getType()->isDependentType())
8209 return T;
8210
8211 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8212 return Rebuilder.TransformType(T);
8213 }
8214
RebuildExprInCurrentInstantiation(Expr * E)8215 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8216 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8217 DeclarationName());
8218 return Rebuilder.TransformExpr(E);
8219 }
8220
RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec & SS)8221 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8222 if (SS.isInvalid())
8223 return true;
8224
8225 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8226 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8227 DeclarationName());
8228 NestedNameSpecifierLoc Rebuilt
8229 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8230 if (!Rebuilt)
8231 return true;
8232
8233 SS.Adopt(Rebuilt);
8234 return false;
8235 }
8236
8237 /// \brief Rebuild the template parameters now that we know we're in a current
8238 /// instantiation.
RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList * Params)8239 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8240 TemplateParameterList *Params) {
8241 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8242 Decl *Param = Params->getParam(I);
8243
8244 // There is nothing to rebuild in a type parameter.
8245 if (isa<TemplateTypeParmDecl>(Param))
8246 continue;
8247
8248 // Rebuild the template parameter list of a template template parameter.
8249 if (TemplateTemplateParmDecl *TTP
8250 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8251 if (RebuildTemplateParamsInCurrentInstantiation(
8252 TTP->getTemplateParameters()))
8253 return true;
8254
8255 continue;
8256 }
8257
8258 // Rebuild the type of a non-type template parameter.
8259 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8260 TypeSourceInfo *NewTSI
8261 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8262 NTTP->getLocation(),
8263 NTTP->getDeclName());
8264 if (!NewTSI)
8265 return true;
8266
8267 if (NewTSI != NTTP->getTypeSourceInfo()) {
8268 NTTP->setTypeSourceInfo(NewTSI);
8269 NTTP->setType(NewTSI->getType());
8270 }
8271 }
8272
8273 return false;
8274 }
8275
8276 /// \brief Produces a formatted string that describes the binding of
8277 /// template parameters to template arguments.
8278 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgumentList & Args)8279 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8280 const TemplateArgumentList &Args) {
8281 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8282 }
8283
8284 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgument * Args,unsigned NumArgs)8285 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8286 const TemplateArgument *Args,
8287 unsigned NumArgs) {
8288 SmallString<128> Str;
8289 llvm::raw_svector_ostream Out(Str);
8290
8291 if (!Params || Params->size() == 0 || NumArgs == 0)
8292 return std::string();
8293
8294 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8295 if (I >= NumArgs)
8296 break;
8297
8298 if (I == 0)
8299 Out << "[with ";
8300 else
8301 Out << ", ";
8302
8303 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8304 Out << Id->getName();
8305 } else {
8306 Out << '$' << I;
8307 }
8308
8309 Out << " = ";
8310 Args[I].print(getPrintingPolicy(), Out);
8311 }
8312
8313 Out << ']';
8314 return Out.str();
8315 }
8316
MarkAsLateParsedTemplate(FunctionDecl * FD,Decl * FnD,CachedTokens & Toks)8317 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8318 CachedTokens &Toks) {
8319 if (!FD)
8320 return;
8321
8322 LateParsedTemplate *LPT = new LateParsedTemplate;
8323
8324 // Take tokens to avoid allocations
8325 LPT->Toks.swap(Toks);
8326 LPT->D = FnD;
8327 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8328
8329 FD->setLateTemplateParsed(true);
8330 }
8331
UnmarkAsLateParsedTemplate(FunctionDecl * FD)8332 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8333 if (!FD)
8334 return;
8335 FD->setLateTemplateParsed(false);
8336 }
8337
IsInsideALocalClassWithinATemplateFunction()8338 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8339 DeclContext *DC = CurContext;
8340
8341 while (DC) {
8342 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8343 const FunctionDecl *FD = RD->isLocalClass();
8344 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8345 } else if (DC->isTranslationUnit() || DC->isNamespace())
8346 return false;
8347
8348 DC = DC->getParent();
8349 }
8350 return false;
8351 }
8352