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