1 | //===- Decl.cpp - Declaration AST Node Implementation ---------------------===// |
---|---|
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file implements the Decl subclasses. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "clang/AST/Decl.h" |
14 | #include "Linkage.h" |
15 | #include "clang/AST/ASTContext.h" |
16 | #include "clang/AST/ASTDiagnostic.h" |
17 | #include "clang/AST/ASTLambda.h" |
18 | #include "clang/AST/ASTMutationListener.h" |
19 | #include "clang/AST/Attr.h" |
20 | #include "clang/AST/CanonicalType.h" |
21 | #include "clang/AST/DeclBase.h" |
22 | #include "clang/AST/DeclCXX.h" |
23 | #include "clang/AST/DeclObjC.h" |
24 | #include "clang/AST/DeclTemplate.h" |
25 | #include "clang/AST/DeclarationName.h" |
26 | #include "clang/AST/Expr.h" |
27 | #include "clang/AST/ExprCXX.h" |
28 | #include "clang/AST/ExternalASTSource.h" |
29 | #include "clang/AST/ODRHash.h" |
30 | #include "clang/AST/PrettyDeclStackTrace.h" |
31 | #include "clang/AST/PrettyPrinter.h" |
32 | #include "clang/AST/Randstruct.h" |
33 | #include "clang/AST/RecordLayout.h" |
34 | #include "clang/AST/Redeclarable.h" |
35 | #include "clang/AST/Stmt.h" |
36 | #include "clang/AST/TemplateBase.h" |
37 | #include "clang/AST/Type.h" |
38 | #include "clang/AST/TypeLoc.h" |
39 | #include "clang/Basic/Builtins.h" |
40 | #include "clang/Basic/IdentifierTable.h" |
41 | #include "clang/Basic/LLVM.h" |
42 | #include "clang/Basic/LangOptions.h" |
43 | #include "clang/Basic/Linkage.h" |
44 | #include "clang/Basic/Module.h" |
45 | #include "clang/Basic/NoSanitizeList.h" |
46 | #include "clang/Basic/PartialDiagnostic.h" |
47 | #include "clang/Basic/Sanitizers.h" |
48 | #include "clang/Basic/SourceLocation.h" |
49 | #include "clang/Basic/SourceManager.h" |
50 | #include "clang/Basic/Specifiers.h" |
51 | #include "clang/Basic/TargetCXXABI.h" |
52 | #include "clang/Basic/TargetInfo.h" |
53 | #include "clang/Basic/Visibility.h" |
54 | #include "llvm/ADT/APSInt.h" |
55 | #include "llvm/ADT/ArrayRef.h" |
56 | #include "llvm/ADT/STLExtras.h" |
57 | #include "llvm/ADT/SmallVector.h" |
58 | #include "llvm/ADT/StringRef.h" |
59 | #include "llvm/ADT/StringSwitch.h" |
60 | #include "llvm/ADT/iterator_range.h" |
61 | #include "llvm/Support/Casting.h" |
62 | #include "llvm/Support/ErrorHandling.h" |
63 | #include "llvm/Support/raw_ostream.h" |
64 | #include "llvm/TargetParser/Triple.h" |
65 | #include <algorithm> |
66 | #include <cassert> |
67 | #include <cstddef> |
68 | #include <cstring> |
69 | #include <memory> |
70 | #include <optional> |
71 | #include <string> |
72 | #include <tuple> |
73 | #include <type_traits> |
74 | |
75 | using namespace clang; |
76 | |
77 | Decl *clang::getPrimaryMergedDecl(Decl *D) { |
78 | return D->getASTContext().getPrimaryMergedDecl(D); |
79 | } |
80 | |
81 | void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { |
82 | SourceLocation Loc = this->Loc; |
83 | if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); |
84 | if (Loc.isValid()) { |
85 | Loc.print(OS, SM: Context.getSourceManager()); |
86 | OS << ": "; |
87 | } |
88 | OS << Message; |
89 | |
90 | if (auto *ND = dyn_cast_if_present<NamedDecl>(Val: TheDecl)) { |
91 | OS << " '"; |
92 | ND->getNameForDiagnostic(OS, Policy: Context.getPrintingPolicy(), Qualified: true); |
93 | OS << "'"; |
94 | } |
95 | |
96 | OS << '\n'; |
97 | } |
98 | |
99 | // Defined here so that it can be inlined into its direct callers. |
100 | bool Decl::isOutOfLine() const { |
101 | return !getLexicalDeclContext()->Equals(DC: getDeclContext()); |
102 | } |
103 | |
104 | TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx) |
105 | : Decl(TranslationUnit, nullptr, SourceLocation()), |
106 | DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {} |
107 | |
108 | //===----------------------------------------------------------------------===// |
109 | // NamedDecl Implementation |
110 | //===----------------------------------------------------------------------===// |
111 | |
112 | // Visibility rules aren't rigorously externally specified, but here |
113 | // are the basic principles behind what we implement: |
114 | // |
115 | // 1. An explicit visibility attribute is generally a direct expression |
116 | // of the user's intent and should be honored. Only the innermost |
117 | // visibility attribute applies. If no visibility attribute applies, |
118 | // global visibility settings are considered. |
119 | // |
120 | // 2. There is one caveat to the above: on or in a template pattern, |
121 | // an explicit visibility attribute is just a default rule, and |
122 | // visibility can be decreased by the visibility of template |
123 | // arguments. But this, too, has an exception: an attribute on an |
124 | // explicit specialization or instantiation causes all the visibility |
125 | // restrictions of the template arguments to be ignored. |
126 | // |
127 | // 3. A variable that does not otherwise have explicit visibility can |
128 | // be restricted by the visibility of its type. |
129 | // |
130 | // 4. A visibility restriction is explicit if it comes from an |
131 | // attribute (or something like it), not a global visibility setting. |
132 | // When emitting a reference to an external symbol, visibility |
133 | // restrictions are ignored unless they are explicit. |
134 | // |
135 | // 5. When computing the visibility of a non-type, including a |
136 | // non-type member of a class, only non-type visibility restrictions |
137 | // are considered: the 'visibility' attribute, global value-visibility |
138 | // settings, and a few special cases like __private_extern. |
139 | // |
140 | // 6. When computing the visibility of a type, including a type member |
141 | // of a class, only type visibility restrictions are considered: |
142 | // the 'type_visibility' attribute and global type-visibility settings. |
143 | // However, a 'visibility' attribute counts as a 'type_visibility' |
144 | // attribute on any declaration that only has the former. |
145 | // |
146 | // The visibility of a "secondary" entity, like a template argument, |
147 | // is computed using the kind of that entity, not the kind of the |
148 | // primary entity for which we are computing visibility. For example, |
149 | // the visibility of a specialization of either of these templates: |
150 | // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X); |
151 | // template <class T, bool (&compare)(T, X)> class matcher; |
152 | // is restricted according to the type visibility of the argument 'T', |
153 | // the type visibility of 'bool(&)(T,X)', and the value visibility of |
154 | // the argument function 'compare'. That 'has_match' is a value |
155 | // and 'matcher' is a type only matters when looking for attributes |
156 | // and settings from the immediate context. |
157 | |
158 | /// Does this computation kind permit us to consider additional |
159 | /// visibility settings from attributes and the like? |
160 | static bool hasExplicitVisibilityAlready(LVComputationKind computation) { |
161 | return computation.IgnoreExplicitVisibility; |
162 | } |
163 | |
164 | /// Given an LVComputationKind, return one of the same type/value sort |
165 | /// that records that it already has explicit visibility. |
166 | static LVComputationKind |
167 | withExplicitVisibilityAlready(LVComputationKind Kind) { |
168 | Kind.IgnoreExplicitVisibility = true; |
169 | return Kind; |
170 | } |
171 | |
172 | static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D, |
173 | LVComputationKind kind) { |
174 | assert(!kind.IgnoreExplicitVisibility && |
175 | "asking for explicit visibility when we shouldn't be"); |
176 | return D->getExplicitVisibility(kind: kind.getExplicitVisibilityKind()); |
177 | } |
178 | |
179 | /// Is the given declaration a "type" or a "value" for the purposes of |
180 | /// visibility computation? |
181 | static bool usesTypeVisibility(const NamedDecl *D) { |
182 | return isa<TypeDecl>(Val: D) || |
183 | isa<ClassTemplateDecl>(Val: D) || |
184 | isa<ObjCInterfaceDecl>(Val: D); |
185 | } |
186 | |
187 | /// Does the given declaration have member specialization information, |
188 | /// and if so, is it an explicit specialization? |
189 | template <class T> |
190 | static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool> |
191 | isExplicitMemberSpecialization(const T *D) { |
192 | if (const MemberSpecializationInfo *member = |
193 | D->getMemberSpecializationInfo()) { |
194 | return member->isExplicitSpecialization(); |
195 | } |
196 | return false; |
197 | } |
198 | |
199 | /// For templates, this question is easier: a member template can't be |
200 | /// explicitly instantiated, so there's a single bit indicating whether |
201 | /// or not this is an explicit member specialization. |
202 | static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) { |
203 | return D->isMemberSpecialization(); |
204 | } |
205 | |
206 | /// Given a visibility attribute, return the explicit visibility |
207 | /// associated with it. |
208 | template <class T> |
209 | static Visibility getVisibilityFromAttr(const T *attr) { |
210 | switch (attr->getVisibility()) { |
211 | case T::Default: |
212 | return DefaultVisibility; |
213 | case T::Hidden: |
214 | return HiddenVisibility; |
215 | case T::Protected: |
216 | return ProtectedVisibility; |
217 | } |
218 | llvm_unreachable("bad visibility kind"); |
219 | } |
220 | |
221 | /// Return the explicit visibility of the given declaration. |
222 | static std::optional<Visibility> |
223 | getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind) { |
224 | // If we're ultimately computing the visibility of a type, look for |
225 | // a 'type_visibility' attribute before looking for 'visibility'. |
226 | if (kind == NamedDecl::VisibilityForType) { |
227 | if (const auto *A = D->getAttr<TypeVisibilityAttr>()) { |
228 | return getVisibilityFromAttr(A); |
229 | } |
230 | } |
231 | |
232 | // If this declaration has an explicit visibility attribute, use it. |
233 | if (const auto *A = D->getAttr<VisibilityAttr>()) { |
234 | return getVisibilityFromAttr(A); |
235 | } |
236 | |
237 | return std::nullopt; |
238 | } |
239 | |
240 | LinkageInfo LinkageComputer::getLVForType(const Type &T, |
241 | LVComputationKind computation) { |
242 | if (computation.IgnoreAllVisibility) |
243 | return LinkageInfo(T.getLinkage(), DefaultVisibility, true); |
244 | return getTypeLinkageAndVisibility(T: &T); |
245 | } |
246 | |
247 | /// Get the most restrictive linkage for the types in the given |
248 | /// template parameter list. For visibility purposes, template |
249 | /// parameters are part of the signature of a template. |
250 | LinkageInfo LinkageComputer::getLVForTemplateParameterList( |
251 | const TemplateParameterList *Params, LVComputationKind computation) { |
252 | LinkageInfo LV; |
253 | for (const NamedDecl *P : *Params) { |
254 | // Template type parameters are the most common and never |
255 | // contribute to visibility, pack or not. |
256 | if (isa<TemplateTypeParmDecl>(Val: P)) |
257 | continue; |
258 | |
259 | // Non-type template parameters can be restricted by the value type, e.g. |
260 | // template <enum X> class A { ... }; |
261 | // We have to be careful here, though, because we can be dealing with |
262 | // dependent types. |
263 | if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) { |
264 | // Handle the non-pack case first. |
265 | if (!NTTP->isExpandedParameterPack()) { |
266 | if (!NTTP->getType()->isDependentType()) { |
267 | LV.merge(other: getLVForType(T: *NTTP->getType(), computation)); |
268 | } |
269 | continue; |
270 | } |
271 | |
272 | // Look at all the types in an expanded pack. |
273 | for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) { |
274 | QualType type = NTTP->getExpansionType(I: i); |
275 | if (!type->isDependentType()) |
276 | LV.merge(other: getTypeLinkageAndVisibility(T: type)); |
277 | } |
278 | continue; |
279 | } |
280 | |
281 | // Template template parameters can be restricted by their |
282 | // template parameters, recursively. |
283 | const auto *TTP = cast<TemplateTemplateParmDecl>(Val: P); |
284 | |
285 | // Handle the non-pack case first. |
286 | if (!TTP->isExpandedParameterPack()) { |
287 | LV.merge(other: getLVForTemplateParameterList(Params: TTP->getTemplateParameters(), |
288 | computation)); |
289 | continue; |
290 | } |
291 | |
292 | // Look at all expansions in an expanded pack. |
293 | for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); |
294 | i != n; ++i) { |
295 | LV.merge(other: getLVForTemplateParameterList( |
296 | Params: TTP->getExpansionTemplateParameters(I: i), computation)); |
297 | } |
298 | } |
299 | |
300 | return LV; |
301 | } |
302 | |
303 | static const Decl *getOutermostFuncOrBlockContext(const Decl *D) { |
304 | const Decl *Ret = nullptr; |
305 | const DeclContext *DC = D->getDeclContext(); |
306 | while (DC->getDeclKind() != Decl::TranslationUnit) { |
307 | if (isa<FunctionDecl>(Val: DC) || isa<BlockDecl>(Val: DC)) |
308 | Ret = cast<Decl>(Val: DC); |
309 | DC = DC->getParent(); |
310 | } |
311 | return Ret; |
312 | } |
313 | |
314 | /// Get the most restrictive linkage for the types and |
315 | /// declarations in the given template argument list. |
316 | /// |
317 | /// Note that we don't take an LVComputationKind because we always |
318 | /// want to honor the visibility of template arguments in the same way. |
319 | LinkageInfo |
320 | LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args, |
321 | LVComputationKind computation) { |
322 | LinkageInfo LV; |
323 | |
324 | for (const TemplateArgument &Arg : Args) { |
325 | switch (Arg.getKind()) { |
326 | case TemplateArgument::Null: |
327 | case TemplateArgument::Integral: |
328 | case TemplateArgument::Expression: |
329 | continue; |
330 | |
331 | case TemplateArgument::Type: |
332 | LV.merge(other: getLVForType(T: *Arg.getAsType(), computation)); |
333 | continue; |
334 | |
335 | case TemplateArgument::Declaration: { |
336 | const NamedDecl *ND = Arg.getAsDecl(); |
337 | assert(!usesTypeVisibility(ND)); |
338 | LV.merge(other: getLVForDecl(D: ND, computation)); |
339 | continue; |
340 | } |
341 | |
342 | case TemplateArgument::NullPtr: |
343 | LV.merge(other: getTypeLinkageAndVisibility(T: Arg.getNullPtrType())); |
344 | continue; |
345 | |
346 | case TemplateArgument::StructuralValue: |
347 | LV.merge(other: getLVForValue(V: Arg.getAsStructuralValue(), computation)); |
348 | continue; |
349 | |
350 | case TemplateArgument::Template: |
351 | case TemplateArgument::TemplateExpansion: |
352 | if (TemplateDecl *Template = |
353 | Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl( |
354 | /*IgnoreDeduced=*/true)) |
355 | LV.merge(other: getLVForDecl(Template, computation)); |
356 | continue; |
357 | |
358 | case TemplateArgument::Pack: |
359 | LV.merge(other: getLVForTemplateArgumentList(Args: Arg.getPackAsArray(), computation)); |
360 | continue; |
361 | } |
362 | llvm_unreachable("bad template argument kind"); |
363 | } |
364 | |
365 | return LV; |
366 | } |
367 | |
368 | LinkageInfo |
369 | LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, |
370 | LVComputationKind computation) { |
371 | return getLVForTemplateArgumentList(Args: TArgs.asArray(), computation); |
372 | } |
373 | |
374 | static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, |
375 | const FunctionTemplateSpecializationInfo *specInfo) { |
376 | // Include visibility from the template parameters and arguments |
377 | // only if this is not an explicit instantiation or specialization |
378 | // with direct explicit visibility. (Implicit instantiations won't |
379 | // have a direct attribute.) |
380 | if (!specInfo->isExplicitInstantiationOrSpecialization()) |
381 | return true; |
382 | |
383 | return !fn->hasAttr<VisibilityAttr>(); |
384 | } |
385 | |
386 | /// Merge in template-related linkage and visibility for the given |
387 | /// function template specialization. |
388 | /// |
389 | /// We don't need a computation kind here because we can assume |
390 | /// LVForValue. |
391 | /// |
392 | /// \param[out] LV the computation to use for the parent |
393 | void LinkageComputer::mergeTemplateLV( |
394 | LinkageInfo &LV, const FunctionDecl *fn, |
395 | const FunctionTemplateSpecializationInfo *specInfo, |
396 | LVComputationKind computation) { |
397 | bool considerVisibility = |
398 | shouldConsiderTemplateVisibility(fn, specInfo); |
399 | |
400 | FunctionTemplateDecl *temp = specInfo->getTemplate(); |
401 | // Merge information from the template declaration. |
402 | LinkageInfo tempLV = getLVForDecl(temp, computation); |
403 | // The linkage and visibility of the specialization should be |
404 | // consistent with the template declaration. |
405 | LV.mergeMaybeWithVisibility(other: tempLV, withVis: considerVisibility); |
406 | |
407 | // Merge information from the template parameters. |
408 | LinkageInfo paramsLV = |
409 | getLVForTemplateParameterList(Params: temp->getTemplateParameters(), computation); |
410 | LV.mergeMaybeWithVisibility(other: paramsLV, withVis: considerVisibility); |
411 | |
412 | // Merge information from the template arguments. |
413 | const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; |
414 | LinkageInfo argsLV = getLVForTemplateArgumentList(TArgs: templateArgs, computation); |
415 | LV.mergeMaybeWithVisibility(other: argsLV, withVis: considerVisibility); |
416 | } |
417 | |
418 | /// Does the given declaration have a direct visibility attribute |
419 | /// that would match the given rules? |
420 | static bool hasDirectVisibilityAttribute(const NamedDecl *D, |
421 | LVComputationKind computation) { |
422 | if (computation.IgnoreAllVisibility) |
423 | return false; |
424 | |
425 | return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) || |
426 | D->hasAttr<VisibilityAttr>(); |
427 | } |
428 | |
429 | /// Should we consider visibility associated with the template |
430 | /// arguments and parameters of the given class template specialization? |
431 | static bool shouldConsiderTemplateVisibility( |
432 | const ClassTemplateSpecializationDecl *spec, |
433 | LVComputationKind computation) { |
434 | // Include visibility from the template parameters and arguments |
435 | // only if this is not an explicit instantiation or specialization |
436 | // with direct explicit visibility (and note that implicit |
437 | // instantiations won't have a direct attribute). |
438 | // |
439 | // Furthermore, we want to ignore template parameters and arguments |
440 | // for an explicit specialization when computing the visibility of a |
441 | // member thereof with explicit visibility. |
442 | // |
443 | // This is a bit complex; let's unpack it. |
444 | // |
445 | // An explicit class specialization is an independent, top-level |
446 | // declaration. As such, if it or any of its members has an |
447 | // explicit visibility attribute, that must directly express the |
448 | // user's intent, and we should honor it. The same logic applies to |
449 | // an explicit instantiation of a member of such a thing. |
450 | |
451 | // Fast path: if this is not an explicit instantiation or |
452 | // specialization, we always want to consider template-related |
453 | // visibility restrictions. |
454 | if (!spec->isExplicitInstantiationOrSpecialization()) |
455 | return true; |
456 | |
457 | // This is the 'member thereof' check. |
458 | if (spec->isExplicitSpecialization() && |
459 | hasExplicitVisibilityAlready(computation)) |
460 | return false; |
461 | |
462 | return !hasDirectVisibilityAttribute(spec, computation); |
463 | } |
464 | |
465 | /// Merge in template-related linkage and visibility for the given |
466 | /// class template specialization. |
467 | void LinkageComputer::mergeTemplateLV( |
468 | LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec, |
469 | LVComputationKind computation) { |
470 | bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); |
471 | |
472 | // Merge information from the template parameters, but ignore |
473 | // visibility if we're only considering template arguments. |
474 | ClassTemplateDecl *temp = spec->getSpecializedTemplate(); |
475 | // Merge information from the template declaration. |
476 | LinkageInfo tempLV = getLVForDecl(temp, computation); |
477 | // The linkage of the specialization should be consistent with the |
478 | // template declaration. |
479 | LV.setLinkage(tempLV.getLinkage()); |
480 | |
481 | LinkageInfo paramsLV = |
482 | getLVForTemplateParameterList(Params: temp->getTemplateParameters(), computation); |
483 | LV.mergeMaybeWithVisibility(other: paramsLV, |
484 | withVis: considerVisibility && !hasExplicitVisibilityAlready(computation)); |
485 | |
486 | // Merge information from the template arguments. We ignore |
487 | // template-argument visibility if we've got an explicit |
488 | // instantiation with a visibility attribute. |
489 | const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); |
490 | LinkageInfo argsLV = getLVForTemplateArgumentList(TArgs: templateArgs, computation); |
491 | if (considerVisibility) |
492 | LV.mergeVisibility(other: argsLV); |
493 | LV.mergeExternalVisibility(Other: argsLV); |
494 | } |
495 | |
496 | /// Should we consider visibility associated with the template |
497 | /// arguments and parameters of the given variable template |
498 | /// specialization? As usual, follow class template specialization |
499 | /// logic up to initialization. |
500 | static bool shouldConsiderTemplateVisibility( |
501 | const VarTemplateSpecializationDecl *spec, |
502 | LVComputationKind computation) { |
503 | // Include visibility from the template parameters and arguments |
504 | // only if this is not an explicit instantiation or specialization |
505 | // with direct explicit visibility (and note that implicit |
506 | // instantiations won't have a direct attribute). |
507 | if (!spec->isExplicitInstantiationOrSpecialization()) |
508 | return true; |
509 | |
510 | // An explicit variable specialization is an independent, top-level |
511 | // declaration. As such, if it has an explicit visibility attribute, |
512 | // that must directly express the user's intent, and we should honor |
513 | // it. |
514 | if (spec->isExplicitSpecialization() && |
515 | hasExplicitVisibilityAlready(computation)) |
516 | return false; |
517 | |
518 | return !hasDirectVisibilityAttribute(spec, computation); |
519 | } |
520 | |
521 | /// Merge in template-related linkage and visibility for the given |
522 | /// variable template specialization. As usual, follow class template |
523 | /// specialization logic up to initialization. |
524 | void LinkageComputer::mergeTemplateLV(LinkageInfo &LV, |
525 | const VarTemplateSpecializationDecl *spec, |
526 | LVComputationKind computation) { |
527 | bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); |
528 | |
529 | // Merge information from the template parameters, but ignore |
530 | // visibility if we're only considering template arguments. |
531 | VarTemplateDecl *temp = spec->getSpecializedTemplate(); |
532 | LinkageInfo tempLV = |
533 | getLVForTemplateParameterList(Params: temp->getTemplateParameters(), computation); |
534 | LV.mergeMaybeWithVisibility(other: tempLV, |
535 | withVis: considerVisibility && !hasExplicitVisibilityAlready(computation)); |
536 | |
537 | // Merge information from the template arguments. We ignore |
538 | // template-argument visibility if we've got an explicit |
539 | // instantiation with a visibility attribute. |
540 | const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); |
541 | LinkageInfo argsLV = getLVForTemplateArgumentList(TArgs: templateArgs, computation); |
542 | if (considerVisibility) |
543 | LV.mergeVisibility(other: argsLV); |
544 | LV.mergeExternalVisibility(Other: argsLV); |
545 | } |
546 | |
547 | static bool useInlineVisibilityHidden(const NamedDecl *D) { |
548 | // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. |
549 | const LangOptions &Opts = D->getASTContext().getLangOpts(); |
550 | if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) |
551 | return false; |
552 | |
553 | const auto *FD = dyn_cast<FunctionDecl>(Val: D); |
554 | if (!FD) |
555 | return false; |
556 | |
557 | TemplateSpecializationKind TSK = TSK_Undeclared; |
558 | if (FunctionTemplateSpecializationInfo *spec |
559 | = FD->getTemplateSpecializationInfo()) { |
560 | TSK = spec->getTemplateSpecializationKind(); |
561 | } else if (MemberSpecializationInfo *MSI = |
562 | FD->getMemberSpecializationInfo()) { |
563 | TSK = MSI->getTemplateSpecializationKind(); |
564 | } |
565 | |
566 | const FunctionDecl *Def = nullptr; |
567 | // InlineVisibilityHidden only applies to definitions, and |
568 | // isInlined() only gives meaningful answers on definitions |
569 | // anyway. |
570 | return TSK != TSK_ExplicitInstantiationDeclaration && |
571 | TSK != TSK_ExplicitInstantiationDefinition && |
572 | FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>(); |
573 | } |
574 | |
575 | template <typename T> static bool isFirstInExternCContext(T *D) { |
576 | const T *First = D->getFirstDecl(); |
577 | return First->isInExternCContext(); |
578 | } |
579 | |
580 | static bool isSingleLineLanguageLinkage(const Decl &D) { |
581 | if (const auto *SD = dyn_cast<LinkageSpecDecl>(Val: D.getDeclContext())) |
582 | if (!SD->hasBraces()) |
583 | return true; |
584 | return false; |
585 | } |
586 | |
587 | static LinkageInfo getExternalLinkageFor(const NamedDecl *D) { |
588 | return LinkageInfo::external(); |
589 | } |
590 | |
591 | static StorageClass getStorageClass(const Decl *D) { |
592 | if (auto *TD = dyn_cast<TemplateDecl>(Val: D)) |
593 | D = TD->getTemplatedDecl(); |
594 | if (D) { |
595 | if (auto *VD = dyn_cast<VarDecl>(Val: D)) |
596 | return VD->getStorageClass(); |
597 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
598 | return FD->getStorageClass(); |
599 | } |
600 | return SC_None; |
601 | } |
602 | |
603 | LinkageInfo |
604 | LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, |
605 | LVComputationKind computation, |
606 | bool IgnoreVarTypeLinkage) { |
607 | assert(D->getDeclContext()->getRedeclContext()->isFileContext() && |
608 | "Not a name having namespace scope"); |
609 | ASTContext &Context = D->getASTContext(); |
610 | const auto *Var = dyn_cast<VarDecl>(Val: D); |
611 | |
612 | // C++ [basic.link]p3: |
613 | // A name having namespace scope (3.3.6) has internal linkage if it |
614 | // is the name of |
615 | |
616 | if ((getStorageClass(D->getCanonicalDecl()) == SC_Static) || |
617 | (Context.getLangOpts().C23 && Var && Var->isConstexpr())) { |
618 | // - a variable, variable template, function, or function template |
619 | // that is explicitly declared static; or |
620 | // (This bullet corresponds to C99 6.2.2p3.) |
621 | |
622 | // C23 6.2.2p3 |
623 | // If the declaration of a file scope identifier for |
624 | // an object contains any of the storage-class specifiers static or |
625 | // constexpr then the identifier has internal linkage. |
626 | return LinkageInfo::internal(); |
627 | } |
628 | |
629 | if (Var) { |
630 | // - a non-template variable of non-volatile const-qualified type, unless |
631 | // - it is explicitly declared extern, or |
632 | // - it is declared in the purview of a module interface unit |
633 | // (outside the private-module-fragment, if any) or module partition, or |
634 | // - it is inline, or |
635 | // - it was previously declared and the prior declaration did not have |
636 | // internal linkage |
637 | // (There is no equivalent in C99.) |
638 | if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() && |
639 | !Var->getType().isVolatileQualified() && !Var->isInline() && |
640 | ![Var]() { |
641 | // Check if it is module purview except private module fragment |
642 | // and implementation unit. |
643 | if (auto *M = Var->getOwningModule()) |
644 | return M->isInterfaceOrPartition() || M->isImplicitGlobalModule(); |
645 | return false; |
646 | }() && |
647 | !isa<VarTemplateSpecializationDecl>(Val: Var) && |
648 | !Var->getDescribedVarTemplate()) { |
649 | const VarDecl *PrevVar = Var->getPreviousDecl(); |
650 | if (PrevVar) |
651 | return getLVForDecl(PrevVar, computation); |
652 | |
653 | if (Var->getStorageClass() != SC_Extern && |
654 | Var->getStorageClass() != SC_PrivateExtern && |
655 | !isSingleLineLanguageLinkage(*Var)) |
656 | return LinkageInfo::internal(); |
657 | } |
658 | |
659 | for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar; |
660 | PrevVar = PrevVar->getPreviousDecl()) { |
661 | if (PrevVar->getStorageClass() == SC_PrivateExtern && |
662 | Var->getStorageClass() == SC_None) |
663 | return getDeclLinkageAndVisibility(PrevVar); |
664 | // Explicitly declared static. |
665 | if (PrevVar->getStorageClass() == SC_Static) |
666 | return LinkageInfo::internal(); |
667 | } |
668 | } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D)) { |
669 | // - a data member of an anonymous union. |
670 | const VarDecl *VD = IFD->getVarDecl(); |
671 | assert(VD && "Expected a VarDecl in this IndirectFieldDecl!"); |
672 | return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage); |
673 | } |
674 | assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!"); |
675 | |
676 | // FIXME: This gives internal linkage to names that should have no linkage |
677 | // (those not covered by [basic.link]p6). |
678 | if (D->isInAnonymousNamespace()) { |
679 | const auto *Var = dyn_cast<VarDecl>(Val: D); |
680 | const auto *Func = dyn_cast<FunctionDecl>(Val: D); |
681 | // FIXME: The check for extern "C" here is not justified by the standard |
682 | // wording, but we retain it from the pre-DR1113 model to avoid breaking |
683 | // code. |
684 | // |
685 | // C++11 [basic.link]p4: |
686 | // An unnamed namespace or a namespace declared directly or indirectly |
687 | // within an unnamed namespace has internal linkage. |
688 | if ((!Var || !isFirstInExternCContext(D: Var)) && |
689 | (!Func || !isFirstInExternCContext(D: Func))) |
690 | return LinkageInfo::internal(); |
691 | } |
692 | |
693 | // Set up the defaults. |
694 | |
695 | // C99 6.2.2p5: |
696 | // If the declaration of an identifier for an object has file |
697 | // scope and no storage-class specifier, its linkage is |
698 | // external. |
699 | LinkageInfo LV = getExternalLinkageFor(D); |
700 | |
701 | if (!hasExplicitVisibilityAlready(computation)) { |
702 | if (std::optional<Visibility> Vis = getExplicitVisibility(D, kind: computation)) { |
703 | LV.mergeVisibility(newVis: *Vis, newExplicit: true); |
704 | } else { |
705 | // If we're declared in a namespace with a visibility attribute, |
706 | // use that namespace's visibility, and it still counts as explicit. |
707 | for (const DeclContext *DC = D->getDeclContext(); |
708 | !isa<TranslationUnitDecl>(Val: DC); |
709 | DC = DC->getParent()) { |
710 | const auto *ND = dyn_cast<NamespaceDecl>(Val: DC); |
711 | if (!ND) continue; |
712 | if (std::optional<Visibility> Vis = |
713 | getExplicitVisibility(ND, computation)) { |
714 | LV.mergeVisibility(newVis: *Vis, newExplicit: true); |
715 | break; |
716 | } |
717 | } |
718 | } |
719 | |
720 | // Add in global settings if the above didn't give us direct visibility. |
721 | if (!LV.isVisibilityExplicit()) { |
722 | // Use global type/value visibility as appropriate. |
723 | Visibility globalVisibility = |
724 | computation.isValueVisibility() |
725 | ? Context.getLangOpts().getValueVisibilityMode() |
726 | : Context.getLangOpts().getTypeVisibilityMode(); |
727 | LV.mergeVisibility(newVis: globalVisibility, /*explicit*/ newExplicit: false); |
728 | |
729 | // If we're paying attention to global visibility, apply |
730 | // -finline-visibility-hidden if this is an inline method. |
731 | if (useInlineVisibilityHidden(D)) |
732 | LV.mergeVisibility(newVis: HiddenVisibility, /*visibilityExplicit=*/newExplicit: false); |
733 | } |
734 | } |
735 | |
736 | // C++ [basic.link]p4: |
737 | |
738 | // A name having namespace scope that has not been given internal linkage |
739 | // above and that is the name of |
740 | // [...bullets...] |
741 | // has its linkage determined as follows: |
742 | // - if the enclosing namespace has internal linkage, the name has |
743 | // internal linkage; [handled above] |
744 | // - otherwise, if the declaration of the name is attached to a named |
745 | // module and is not exported, the name has module linkage; |
746 | // - otherwise, the name has external linkage. |
747 | // LV is currently set up to handle the last two bullets. |
748 | // |
749 | // The bullets are: |
750 | |
751 | // - a variable; or |
752 | if (const auto *Var = dyn_cast<VarDecl>(Val: D)) { |
753 | // GCC applies the following optimization to variables and static |
754 | // data members, but not to functions: |
755 | // |
756 | // Modify the variable's LV by the LV of its type unless this is |
757 | // C or extern "C". This follows from [basic.link]p9: |
758 | // A type without linkage shall not be used as the type of a |
759 | // variable or function with external linkage unless |
760 | // - the entity has C language linkage, or |
761 | // - the entity is declared within an unnamed namespace, or |
762 | // - the entity is not used or is defined in the same |
763 | // translation unit. |
764 | // and [basic.link]p10: |
765 | // ...the types specified by all declarations referring to a |
766 | // given variable or function shall be identical... |
767 | // C does not have an equivalent rule. |
768 | // |
769 | // Ignore this if we've got an explicit attribute; the user |
770 | // probably knows what they're doing. |
771 | // |
772 | // Note that we don't want to make the variable non-external |
773 | // because of this, but unique-external linkage suits us. |
774 | |
775 | if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(D: Var) && |
776 | !IgnoreVarTypeLinkage) { |
777 | LinkageInfo TypeLV = getLVForType(T: *Var->getType(), computation); |
778 | if (!isExternallyVisible(L: TypeLV.getLinkage())) |
779 | return LinkageInfo::uniqueExternal(); |
780 | if (!LV.isVisibilityExplicit()) |
781 | LV.mergeVisibility(other: TypeLV); |
782 | } |
783 | |
784 | if (Var->getStorageClass() == SC_PrivateExtern) |
785 | LV.mergeVisibility(newVis: HiddenVisibility, newExplicit: true); |
786 | |
787 | // Note that Sema::MergeVarDecl already takes care of implementing |
788 | // C99 6.2.2p4 and propagating the visibility attribute, so we don't have |
789 | // to do it here. |
790 | |
791 | // As per function and class template specializations (below), |
792 | // consider LV for the template and template arguments. We're at file |
793 | // scope, so we do not need to worry about nested specializations. |
794 | if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Val: Var)) { |
795 | mergeTemplateLV(LV, spec, computation); |
796 | } |
797 | |
798 | // - a function; or |
799 | } else if (const auto *Function = dyn_cast<FunctionDecl>(Val: D)) { |
800 | // In theory, we can modify the function's LV by the LV of its |
801 | // type unless it has C linkage (see comment above about variables |
802 | // for justification). In practice, GCC doesn't do this, so it's |
803 | // just too painful to make work. |
804 | |
805 | if (Function->getStorageClass() == SC_PrivateExtern) |
806 | LV.mergeVisibility(newVis: HiddenVisibility, newExplicit: true); |
807 | |
808 | // OpenMP target declare device functions are not callable from the host so |
809 | // they should not be exported from the device image. This applies to all |
810 | // functions as the host-callable kernel functions are emitted at codegen. |
811 | if (Context.getLangOpts().OpenMP && |
812 | Context.getLangOpts().OpenMPIsTargetDevice && |
813 | (Context.getTargetInfo().getTriple().isGPU() || |
814 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function))) |
815 | LV.mergeVisibility(newVis: HiddenVisibility, /*newExplicit=*/false); |
816 | |
817 | // Note that Sema::MergeCompatibleFunctionDecls already takes care of |
818 | // merging storage classes and visibility attributes, so we don't have to |
819 | // look at previous decls in here. |
820 | |
821 | // In C++, then if the type of the function uses a type with |
822 | // unique-external linkage, it's not legally usable from outside |
823 | // this translation unit. However, we should use the C linkage |
824 | // rules instead for extern "C" declarations. |
825 | if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(D: Function)) { |
826 | // Only look at the type-as-written. Otherwise, deducing the return type |
827 | // of a function could change its linkage. |
828 | QualType TypeAsWritten = Function->getType(); |
829 | if (TypeSourceInfo *TSI = Function->getTypeSourceInfo()) |
830 | TypeAsWritten = TSI->getType(); |
831 | if (!isExternallyVisible(L: TypeAsWritten->getLinkage())) |
832 | return LinkageInfo::uniqueExternal(); |
833 | } |
834 | |
835 | // Consider LV from the template and the template arguments. |
836 | // We're at file scope, so we do not need to worry about nested |
837 | // specializations. |
838 | if (FunctionTemplateSpecializationInfo *specInfo |
839 | = Function->getTemplateSpecializationInfo()) { |
840 | mergeTemplateLV(LV, fn: Function, specInfo, computation); |
841 | } |
842 | |
843 | // - a named class (Clause 9), or an unnamed class defined in a |
844 | // typedef declaration in which the class has the typedef name |
845 | // for linkage purposes (7.1.3); or |
846 | // - a named enumeration (7.2), or an unnamed enumeration |
847 | // defined in a typedef declaration in which the enumeration |
848 | // has the typedef name for linkage purposes (7.1.3); or |
849 | } else if (const auto *Tag = dyn_cast<TagDecl>(Val: D)) { |
850 | // Unnamed tags have no linkage. |
851 | if (!Tag->hasNameForLinkage()) |
852 | return LinkageInfo::none(); |
853 | |
854 | // If this is a class template specialization, consider the |
855 | // linkage of the template and template arguments. We're at file |
856 | // scope, so we do not need to worry about nested specializations. |
857 | if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Tag)) { |
858 | mergeTemplateLV(LV, spec, computation); |
859 | } |
860 | |
861 | // FIXME: This is not part of the C++ standard any more. |
862 | // - an enumerator belonging to an enumeration with external linkage; or |
863 | } else if (isa<EnumConstantDecl>(Val: D)) { |
864 | LinkageInfo EnumLV = getLVForDecl(D: cast<NamedDecl>(D->getDeclContext()), |
865 | computation); |
866 | if (!isExternalFormalLinkage(L: EnumLV.getLinkage())) |
867 | return LinkageInfo::none(); |
868 | LV.merge(other: EnumLV); |
869 | |
870 | // - a template |
871 | } else if (const auto *temp = dyn_cast<TemplateDecl>(Val: D)) { |
872 | bool considerVisibility = !hasExplicitVisibilityAlready(computation); |
873 | LinkageInfo tempLV = |
874 | getLVForTemplateParameterList(Params: temp->getTemplateParameters(), computation); |
875 | LV.mergeMaybeWithVisibility(other: tempLV, withVis: considerVisibility); |
876 | |
877 | // An unnamed namespace or a namespace declared directly or indirectly |
878 | // within an unnamed namespace has internal linkage. All other namespaces |
879 | // have external linkage. |
880 | // |
881 | // We handled names in anonymous namespaces above. |
882 | } else if (isa<NamespaceDecl>(Val: D)) { |
883 | return LV; |
884 | |
885 | // By extension, we assign external linkage to Objective-C |
886 | // interfaces. |
887 | } else if (isa<ObjCInterfaceDecl>(Val: D)) { |
888 | // fallout |
889 | |
890 | } else if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) { |
891 | // A typedef declaration has linkage if it gives a type a name for |
892 | // linkage purposes. |
893 | if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) |
894 | return LinkageInfo::none(); |
895 | |
896 | } else if (isa<MSGuidDecl>(Val: D)) { |
897 | // A GUID behaves like an inline variable with external linkage. Fall |
898 | // through. |
899 | |
900 | // Everything not covered here has no linkage. |
901 | } else { |
902 | return LinkageInfo::none(); |
903 | } |
904 | |
905 | // If we ended up with non-externally-visible linkage, visibility should |
906 | // always be default. |
907 | if (!isExternallyVisible(L: LV.getLinkage())) |
908 | return LinkageInfo(LV.getLinkage(), DefaultVisibility, false); |
909 | |
910 | return LV; |
911 | } |
912 | |
913 | LinkageInfo |
914 | LinkageComputer::getLVForClassMember(const NamedDecl *D, |
915 | LVComputationKind computation, |
916 | bool IgnoreVarTypeLinkage) { |
917 | // Only certain class members have linkage. Note that fields don't |
918 | // really have linkage, but it's convenient to say they do for the |
919 | // purposes of calculating linkage of pointer-to-data-member |
920 | // template arguments. |
921 | // |
922 | // Templates also don't officially have linkage, but since we ignore |
923 | // the C++ standard and look at template arguments when determining |
924 | // linkage and visibility of a template specialization, we might hit |
925 | // a template template argument that way. If we do, we need to |
926 | // consider its linkage. |
927 | if (!(isa<CXXMethodDecl>(Val: D) || |
928 | isa<VarDecl>(Val: D) || |
929 | isa<FieldDecl>(Val: D) || |
930 | isa<IndirectFieldDecl>(Val: D) || |
931 | isa<TagDecl>(Val: D) || |
932 | isa<TemplateDecl>(Val: D))) |
933 | return LinkageInfo::none(); |
934 | |
935 | LinkageInfo LV; |
936 | |
937 | // If we have an explicit visibility attribute, merge that in. |
938 | if (!hasExplicitVisibilityAlready(computation)) { |
939 | if (std::optional<Visibility> Vis = getExplicitVisibility(D, kind: computation)) |
940 | LV.mergeVisibility(newVis: *Vis, newExplicit: true); |
941 | // If we're paying attention to global visibility, apply |
942 | // -finline-visibility-hidden if this is an inline method. |
943 | // |
944 | // Note that we do this before merging information about |
945 | // the class visibility. |
946 | if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D)) |
947 | LV.mergeVisibility(newVis: HiddenVisibility, /*visibilityExplicit=*/newExplicit: false); |
948 | } |
949 | |
950 | // If this class member has an explicit visibility attribute, the only |
951 | // thing that can change its visibility is the template arguments, so |
952 | // only look for them when processing the class. |
953 | LVComputationKind classComputation = computation; |
954 | if (LV.isVisibilityExplicit()) |
955 | classComputation = withExplicitVisibilityAlready(Kind: computation); |
956 | |
957 | LinkageInfo classLV = |
958 | getLVForDecl(D: cast<RecordDecl>(D->getDeclContext()), computation: classComputation); |
959 | // The member has the same linkage as the class. If that's not externally |
960 | // visible, we don't need to compute anything about the linkage. |
961 | // FIXME: If we're only computing linkage, can we bail out here? |
962 | if (!isExternallyVisible(L: classLV.getLinkage())) |
963 | return classLV; |
964 | |
965 | |
966 | // Otherwise, don't merge in classLV yet, because in certain cases |
967 | // we need to completely ignore the visibility from it. |
968 | |
969 | // Specifically, if this decl exists and has an explicit attribute. |
970 | const NamedDecl *explicitSpecSuppressor = nullptr; |
971 | |
972 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) { |
973 | // Only look at the type-as-written. Otherwise, deducing the return type |
974 | // of a function could change its linkage. |
975 | QualType TypeAsWritten = MD->getType(); |
976 | if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) |
977 | TypeAsWritten = TSI->getType(); |
978 | if (!isExternallyVisible(L: TypeAsWritten->getLinkage())) |
979 | return LinkageInfo::uniqueExternal(); |
980 | |
981 | // If this is a method template specialization, use the linkage for |
982 | // the template parameters and arguments. |
983 | if (FunctionTemplateSpecializationInfo *spec |
984 | = MD->getTemplateSpecializationInfo()) { |
985 | mergeTemplateLV(LV, MD, spec, computation); |
986 | if (spec->isExplicitSpecialization()) { |
987 | explicitSpecSuppressor = MD; |
988 | } else if (isExplicitMemberSpecialization(spec->getTemplate())) { |
989 | explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl(); |
990 | } |
991 | } else if (isExplicitMemberSpecialization(D: MD)) { |
992 | explicitSpecSuppressor = MD; |
993 | } |
994 | |
995 | // OpenMP target declare device functions are not callable from the host so |
996 | // they should not be exported from the device image. This applies to all |
997 | // functions as the host-callable kernel functions are emitted at codegen. |
998 | ASTContext &Context = D->getASTContext(); |
999 | if (Context.getLangOpts().OpenMP && |
1000 | Context.getLangOpts().OpenMPIsTargetDevice && |
1001 | ((Context.getTargetInfo().getTriple().isAMDGPU() || |
1002 | Context.getTargetInfo().getTriple().isNVPTX()) || |
1003 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD))) |
1004 | LV.mergeVisibility(newVis: HiddenVisibility, /*newExplicit=*/false); |
1005 | |
1006 | } else if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) { |
1007 | if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) { |
1008 | mergeTemplateLV(LV, spec, computation); |
1009 | if (spec->isExplicitSpecialization()) { |
1010 | explicitSpecSuppressor = spec; |
1011 | } else { |
1012 | const ClassTemplateDecl *temp = spec->getSpecializedTemplate(); |
1013 | if (isExplicitMemberSpecialization(temp)) { |
1014 | explicitSpecSuppressor = temp->getTemplatedDecl(); |
1015 | } |
1016 | } |
1017 | } else if (isExplicitMemberSpecialization(D: RD)) { |
1018 | explicitSpecSuppressor = RD; |
1019 | } |
1020 | |
1021 | // Static data members. |
1022 | } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) { |
1023 | if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) |
1024 | mergeTemplateLV(LV, spec, computation); |
1025 | |
1026 | // Modify the variable's linkage by its type, but ignore the |
1027 | // type's visibility unless it's a definition. |
1028 | if (!IgnoreVarTypeLinkage) { |
1029 | LinkageInfo typeLV = getLVForType(T: *VD->getType(), computation); |
1030 | // FIXME: If the type's linkage is not externally visible, we can |
1031 | // give this static data member UniqueExternalLinkage. |
1032 | if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit()) |
1033 | LV.mergeVisibility(other: typeLV); |
1034 | LV.mergeExternalVisibility(Other: typeLV); |
1035 | } |
1036 | |
1037 | if (isExplicitMemberSpecialization(D: VD)) { |
1038 | explicitSpecSuppressor = VD; |
1039 | } |
1040 | |
1041 | // Template members. |
1042 | } else if (const auto *temp = dyn_cast<TemplateDecl>(Val: D)) { |
1043 | bool considerVisibility = |
1044 | (!LV.isVisibilityExplicit() && |
1045 | !classLV.isVisibilityExplicit() && |
1046 | !hasExplicitVisibilityAlready(computation)); |
1047 | LinkageInfo tempLV = |
1048 | getLVForTemplateParameterList(Params: temp->getTemplateParameters(), computation); |
1049 | LV.mergeMaybeWithVisibility(other: tempLV, withVis: considerVisibility); |
1050 | |
1051 | if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(Val: temp)) { |
1052 | if (isExplicitMemberSpecialization(D: redeclTemp)) { |
1053 | explicitSpecSuppressor = temp->getTemplatedDecl(); |
1054 | } else if (const RedeclarableTemplateDecl *from = |
1055 | redeclTemp->getInstantiatedFromMemberTemplate()) { |
1056 | // If no explicit visibility is specified yet, and this is an |
1057 | // instantiated member of a template, look up visibility there |
1058 | // as well. |
1059 | LinkageInfo fromLV = from->getLinkageAndVisibility(); |
1060 | LV.mergeMaybeWithVisibility(other: fromLV, withVis: considerVisibility); |
1061 | } |
1062 | } |
1063 | } |
1064 | |
1065 | // We should never be looking for an attribute directly on a template. |
1066 | assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor)); |
1067 | |
1068 | // If this member is an explicit member specialization, and it has |
1069 | // an explicit attribute, ignore visibility from the parent. |
1070 | bool considerClassVisibility = true; |
1071 | if (explicitSpecSuppressor && |
1072 | // optimization: hasDVA() is true only with explicit visibility. |
1073 | LV.isVisibilityExplicit() && |
1074 | classLV.getVisibility() != DefaultVisibility && |
1075 | hasDirectVisibilityAttribute(D: explicitSpecSuppressor, computation)) { |
1076 | considerClassVisibility = false; |
1077 | } |
1078 | |
1079 | // Finally, merge in information from the class. |
1080 | LV.mergeMaybeWithVisibility(other: classLV, withVis: considerClassVisibility); |
1081 | return LV; |
1082 | } |
1083 | |
1084 | void NamedDecl::anchor() {} |
1085 | |
1086 | bool NamedDecl::isLinkageValid() const { |
1087 | if (!hasCachedLinkage()) |
1088 | return true; |
1089 | |
1090 | Linkage L = LinkageComputer{} |
1091 | .computeLVForDecl(D: this, computation: LVComputationKind::forLinkageOnly()) |
1092 | .getLinkage(); |
1093 | return L == getCachedLinkage(); |
1094 | } |
1095 | |
1096 | bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const { |
1097 | // [C++2c] [basic.scope.scope]/p5 |
1098 | // A declaration is name-independent if its name is _ and it declares |
1099 | // - a variable with automatic storage duration, |
1100 | // - a structured binding not inhabiting a namespace scope, |
1101 | // - the variable introduced by an init-capture |
1102 | // - or a non-static data member. |
1103 | |
1104 | if (!LangOpts.CPlusPlus || !getIdentifier() || |
1105 | !getIdentifier()->isPlaceholder()) |
1106 | return false; |
1107 | if (isa<FieldDecl>(Val: this)) |
1108 | return true; |
1109 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: this)) { |
1110 | if (!getDeclContext()->isFunctionOrMethod() && |
1111 | !getDeclContext()->isRecord()) |
1112 | return false; |
1113 | const VarDecl *VD = IFD->getVarDecl(); |
1114 | return !VD || VD->getStorageDuration() == SD_Automatic; |
1115 | } |
1116 | // and it declares a variable with automatic storage duration |
1117 | if (const auto *VD = dyn_cast<VarDecl>(Val: this)) { |
1118 | if (isa<ParmVarDecl>(Val: VD)) |
1119 | return false; |
1120 | if (VD->isInitCapture()) |
1121 | return true; |
1122 | return VD->getStorageDuration() == StorageDuration::SD_Automatic; |
1123 | } |
1124 | if (const auto *BD = dyn_cast<BindingDecl>(Val: this); |
1125 | BD && getDeclContext()->isFunctionOrMethod()) { |
1126 | const VarDecl *VD = BD->getHoldingVar(); |
1127 | return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic; |
1128 | } |
1129 | return false; |
1130 | } |
1131 | |
1132 | ReservedIdentifierStatus |
1133 | NamedDecl::isReserved(const LangOptions &LangOpts) const { |
1134 | const IdentifierInfo *II = getIdentifier(); |
1135 | |
1136 | // This triggers at least for CXXLiteralIdentifiers, which we already checked |
1137 | // at lexing time. |
1138 | if (!II) |
1139 | return ReservedIdentifierStatus::NotReserved; |
1140 | |
1141 | ReservedIdentifierStatus Status = II->isReserved(LangOpts); |
1142 | if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) { |
1143 | // This name is only reserved at global scope. Check if this declaration |
1144 | // conflicts with a global scope declaration. |
1145 | if (isa<ParmVarDecl>(Val: this) || isTemplateParameter()) |
1146 | return ReservedIdentifierStatus::NotReserved; |
1147 | |
1148 | // C++ [dcl.link]/7: |
1149 | // Two declarations [conflict] if [...] one declares a function or |
1150 | // variable with C language linkage, and the other declares [...] a |
1151 | // variable that belongs to the global scope. |
1152 | // |
1153 | // Therefore names that are reserved at global scope are also reserved as |
1154 | // names of variables and functions with C language linkage. |
1155 | const DeclContext *DC = getDeclContext()->getRedeclContext(); |
1156 | if (DC->isTranslationUnit()) |
1157 | return Status; |
1158 | if (auto *VD = dyn_cast<VarDecl>(Val: this)) |
1159 | if (VD->isExternC()) |
1160 | return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC; |
1161 | if (auto *FD = dyn_cast<FunctionDecl>(Val: this)) |
1162 | if (FD->isExternC()) |
1163 | return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC; |
1164 | return ReservedIdentifierStatus::NotReserved; |
1165 | } |
1166 | |
1167 | return Status; |
1168 | } |
1169 | |
1170 | ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { |
1171 | StringRef name = getName(); |
1172 | if (name.empty()) return SFF_None; |
1173 | |
1174 | if (name.front() == 'C') |
1175 | if (name == "CFStringCreateWithFormat"|| |
1176 | name == "CFStringCreateWithFormatAndArguments"|| |
1177 | name == "CFStringAppendFormat"|| |
1178 | name == "CFStringAppendFormatAndArguments") |
1179 | return SFF_CFString; |
1180 | return SFF_None; |
1181 | } |
1182 | |
1183 | Linkage NamedDecl::getLinkageInternal() const { |
1184 | // We don't care about visibility here, so ask for the cheapest |
1185 | // possible visibility analysis. |
1186 | return LinkageComputer{} |
1187 | .getLVForDecl(D: this, computation: LVComputationKind::forLinkageOnly()) |
1188 | .getLinkage(); |
1189 | } |
1190 | |
1191 | static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) { |
1192 | // FIXME: Handle isModulePrivate. |
1193 | switch (D->getModuleOwnershipKind()) { |
1194 | case Decl::ModuleOwnershipKind::Unowned: |
1195 | case Decl::ModuleOwnershipKind::ReachableWhenImported: |
1196 | case Decl::ModuleOwnershipKind::ModulePrivate: |
1197 | return false; |
1198 | case Decl::ModuleOwnershipKind::Visible: |
1199 | case Decl::ModuleOwnershipKind::VisibleWhenImported: |
1200 | return D->isInNamedModule(); |
1201 | } |
1202 | llvm_unreachable("unexpected module ownership kind"); |
1203 | } |
1204 | |
1205 | /// Get the linkage from a semantic point of view. Entities in |
1206 | /// anonymous namespaces are external (in c++98). |
1207 | Linkage NamedDecl::getFormalLinkage() const { |
1208 | Linkage InternalLinkage = getLinkageInternal(); |
1209 | |
1210 | // C++ [basic.link]p4.8: |
1211 | // - if the declaration of the name is attached to a named module and is not |
1212 | // exported |
1213 | // the name has module linkage; |
1214 | // |
1215 | // [basic.namespace.general]/p2 |
1216 | // A namespace is never attached to a named module and never has a name with |
1217 | // module linkage. |
1218 | if (isInNamedModule() && InternalLinkage == Linkage::External && |
1219 | !isExportedFromModuleInterfaceUnit( |
1220 | cast<NamedDecl>(this->getCanonicalDecl())) && |
1221 | !isa<NamespaceDecl>(Val: this)) |
1222 | InternalLinkage = Linkage::Module; |
1223 | |
1224 | return clang::getFormalLinkage(L: InternalLinkage); |
1225 | } |
1226 | |
1227 | LinkageInfo NamedDecl::getLinkageAndVisibility() const { |
1228 | return LinkageComputer{}.getDeclLinkageAndVisibility(D: this); |
1229 | } |
1230 | |
1231 | static std::optional<Visibility> |
1232 | getExplicitVisibilityAux(const NamedDecl *ND, |
1233 | NamedDecl::ExplicitVisibilityKind kind, |
1234 | bool IsMostRecent) { |
1235 | assert(!IsMostRecent || ND == ND->getMostRecentDecl()); |
1236 | |
1237 | // Check the declaration itself first. |
1238 | if (std::optional<Visibility> V = getVisibilityOf(D: ND, kind)) |
1239 | return V; |
1240 | |
1241 | // If this is a member class of a specialization of a class template |
1242 | // and the corresponding decl has explicit visibility, use that. |
1243 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND)) { |
1244 | CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); |
1245 | if (InstantiatedFrom) |
1246 | return getVisibilityOf(InstantiatedFrom, kind); |
1247 | } |
1248 | |
1249 | // If there wasn't explicit visibility there, and this is a |
1250 | // specialization of a class template, check for visibility |
1251 | // on the pattern. |
1252 | if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: ND)) { |
1253 | // Walk all the template decl till this point to see if there are |
1254 | // explicit visibility attributes. |
1255 | const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl(); |
1256 | while (TD != nullptr) { |
1257 | auto Vis = getVisibilityOf(TD, kind); |
1258 | if (Vis != std::nullopt) |
1259 | return Vis; |
1260 | TD = TD->getPreviousDecl(); |
1261 | } |
1262 | return std::nullopt; |
1263 | } |
1264 | |
1265 | // Use the most recent declaration. |
1266 | if (!IsMostRecent && !isa<NamespaceDecl>(Val: ND)) { |
1267 | const NamedDecl *MostRecent = ND->getMostRecentDecl(); |
1268 | if (MostRecent != ND) |
1269 | return getExplicitVisibilityAux(ND: MostRecent, kind, IsMostRecent: true); |
1270 | } |
1271 | |
1272 | if (const auto *Var = dyn_cast<VarDecl>(Val: ND)) { |
1273 | if (Var->isStaticDataMember()) { |
1274 | VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); |
1275 | if (InstantiatedFrom) |
1276 | return getVisibilityOf(InstantiatedFrom, kind); |
1277 | } |
1278 | |
1279 | if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Var)) |
1280 | return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(), |
1281 | kind); |
1282 | |
1283 | return std::nullopt; |
1284 | } |
1285 | // Also handle function template specializations. |
1286 | if (const auto *fn = dyn_cast<FunctionDecl>(Val: ND)) { |
1287 | // If the function is a specialization of a template with an |
1288 | // explicit visibility attribute, use that. |
1289 | if (FunctionTemplateSpecializationInfo *templateInfo |
1290 | = fn->getTemplateSpecializationInfo()) |
1291 | return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(), |
1292 | kind); |
1293 | |
1294 | // If the function is a member of a specialization of a class template |
1295 | // and the corresponding decl has explicit visibility, use that. |
1296 | FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction(); |
1297 | if (InstantiatedFrom) |
1298 | return getVisibilityOf(InstantiatedFrom, kind); |
1299 | |
1300 | return std::nullopt; |
1301 | } |
1302 | |
1303 | // The visibility of a template is stored in the templated decl. |
1304 | if (const auto *TD = dyn_cast<TemplateDecl>(Val: ND)) |
1305 | return getVisibilityOf(D: TD->getTemplatedDecl(), kind); |
1306 | |
1307 | return std::nullopt; |
1308 | } |
1309 | |
1310 | std::optional<Visibility> |
1311 | NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const { |
1312 | return getExplicitVisibilityAux(ND: this, kind, IsMostRecent: false); |
1313 | } |
1314 | |
1315 | LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC, |
1316 | Decl *ContextDecl, |
1317 | LVComputationKind computation) { |
1318 | // This lambda has its linkage/visibility determined by its owner. |
1319 | const NamedDecl *Owner; |
1320 | if (!ContextDecl) |
1321 | Owner = dyn_cast<NamedDecl>(Val: DC); |
1322 | else if (isa<ParmVarDecl>(Val: ContextDecl)) |
1323 | Owner = |
1324 | dyn_cast<NamedDecl>(Val: ContextDecl->getDeclContext()->getRedeclContext()); |
1325 | else if (isa<ImplicitConceptSpecializationDecl>(Val: ContextDecl)) { |
1326 | // Replace with the concept's owning decl, which is either a namespace or a |
1327 | // TU, so this needs a dyn_cast. |
1328 | Owner = dyn_cast<NamedDecl>(Val: ContextDecl->getDeclContext()); |
1329 | } else { |
1330 | Owner = cast<NamedDecl>(Val: ContextDecl); |
1331 | } |
1332 | |
1333 | if (!Owner) |
1334 | return LinkageInfo::none(); |
1335 | |
1336 | // If the owner has a deduced type, we need to skip querying the linkage and |
1337 | // visibility of that type, because it might involve this closure type. The |
1338 | // only effect of this is that we might give a lambda VisibleNoLinkage rather |
1339 | // than NoLinkage when we don't strictly need to, which is benign. |
1340 | auto *VD = dyn_cast<VarDecl>(Val: Owner); |
1341 | LinkageInfo OwnerLV = |
1342 | VD && VD->getType()->getContainedDeducedType() |
1343 | ? computeLVForDecl(D: Owner, computation, /*IgnoreVarTypeLinkage*/true) |
1344 | : getLVForDecl(D: Owner, computation); |
1345 | |
1346 | // A lambda never formally has linkage. But if the owner is externally |
1347 | // visible, then the lambda is too. We apply the same rules to blocks. |
1348 | if (!isExternallyVisible(L: OwnerLV.getLinkage())) |
1349 | return LinkageInfo::none(); |
1350 | return LinkageInfo(Linkage::VisibleNone, OwnerLV.getVisibility(), |
1351 | OwnerLV.isVisibilityExplicit()); |
1352 | } |
1353 | |
1354 | LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D, |
1355 | LVComputationKind computation) { |
1356 | if (const auto *Function = dyn_cast<FunctionDecl>(Val: D)) { |
1357 | if (Function->isInAnonymousNamespace() && |
1358 | !isFirstInExternCContext(D: Function)) |
1359 | return LinkageInfo::internal(); |
1360 | |
1361 | // This is a "void f();" which got merged with a file static. |
1362 | if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) |
1363 | return LinkageInfo::internal(); |
1364 | |
1365 | LinkageInfo LV; |
1366 | if (!hasExplicitVisibilityAlready(computation)) { |
1367 | if (std::optional<Visibility> Vis = |
1368 | getExplicitVisibility(Function, computation)) |
1369 | LV.mergeVisibility(newVis: *Vis, newExplicit: true); |
1370 | } |
1371 | |
1372 | // Note that Sema::MergeCompatibleFunctionDecls already takes care of |
1373 | // merging storage classes and visibility attributes, so we don't have to |
1374 | // look at previous decls in here. |
1375 | |
1376 | return LV; |
1377 | } |
1378 | |
1379 | if (const auto *Var = dyn_cast<VarDecl>(Val: D)) { |
1380 | if (Var->hasExternalStorage()) { |
1381 | if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(D: Var)) |
1382 | return LinkageInfo::internal(); |
1383 | |
1384 | LinkageInfo LV; |
1385 | if (Var->getStorageClass() == SC_PrivateExtern) |
1386 | LV.mergeVisibility(newVis: HiddenVisibility, newExplicit: true); |
1387 | else if (!hasExplicitVisibilityAlready(computation)) { |
1388 | if (std::optional<Visibility> Vis = |
1389 | getExplicitVisibility(Var, computation)) |
1390 | LV.mergeVisibility(newVis: *Vis, newExplicit: true); |
1391 | } |
1392 | |
1393 | if (const VarDecl *Prev = Var->getPreviousDecl()) { |
1394 | LinkageInfo PrevLV = getLVForDecl(Prev, computation); |
1395 | if (PrevLV.getLinkage() != Linkage::Invalid) |
1396 | LV.setLinkage(PrevLV.getLinkage()); |
1397 | LV.mergeVisibility(other: PrevLV); |
1398 | } |
1399 | |
1400 | return LV; |
1401 | } |
1402 | |
1403 | if (!Var->isStaticLocal()) |
1404 | return LinkageInfo::none(); |
1405 | } |
1406 | |
1407 | ASTContext &Context = D->getASTContext(); |
1408 | if (!Context.getLangOpts().CPlusPlus) |
1409 | return LinkageInfo::none(); |
1410 | |
1411 | const Decl *OuterD = getOutermostFuncOrBlockContext(D); |
1412 | if (!OuterD || OuterD->isInvalidDecl()) |
1413 | return LinkageInfo::none(); |
1414 | |
1415 | LinkageInfo LV; |
1416 | if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) { |
1417 | if (!BD->getBlockManglingNumber()) |
1418 | return LinkageInfo::none(); |
1419 | |
1420 | LV = getLVForClosure(DC: BD->getDeclContext()->getRedeclContext(), |
1421 | ContextDecl: BD->getBlockManglingContextDecl(), computation); |
1422 | } else { |
1423 | const auto *FD = cast<FunctionDecl>(Val: OuterD); |
1424 | if (!FD->isInlined() && |
1425 | !isTemplateInstantiation(FD->getTemplateSpecializationKind())) |
1426 | return LinkageInfo::none(); |
1427 | |
1428 | // If a function is hidden by -fvisibility-inlines-hidden option and |
1429 | // is not explicitly attributed as a hidden function, |
1430 | // we should not make static local variables in the function hidden. |
1431 | LV = getLVForDecl(D: FD, computation); |
1432 | if (isa<VarDecl>(Val: D) && useInlineVisibilityHidden(FD) && |
1433 | !LV.isVisibilityExplicit() && |
1434 | !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) { |
1435 | assert(cast<VarDecl>(D)->isStaticLocal()); |
1436 | // If this was an implicitly hidden inline method, check again for |
1437 | // explicit visibility on the parent class, and use that for static locals |
1438 | // if present. |
1439 | if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) |
1440 | LV = getLVForDecl(D: MD->getParent(), computation); |
1441 | if (!LV.isVisibilityExplicit()) { |
1442 | Visibility globalVisibility = |
1443 | computation.isValueVisibility() |
1444 | ? Context.getLangOpts().getValueVisibilityMode() |
1445 | : Context.getLangOpts().getTypeVisibilityMode(); |
1446 | return LinkageInfo(Linkage::VisibleNone, globalVisibility, |
1447 | /*visibilityExplicit=*/false); |
1448 | } |
1449 | } |
1450 | } |
1451 | if (!isExternallyVisible(L: LV.getLinkage())) |
1452 | return LinkageInfo::none(); |
1453 | return LinkageInfo(Linkage::VisibleNone, LV.getVisibility(), |
1454 | LV.isVisibilityExplicit()); |
1455 | } |
1456 | |
1457 | LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, |
1458 | LVComputationKind computation, |
1459 | bool IgnoreVarTypeLinkage) { |
1460 | // Internal_linkage attribute overrides other considerations. |
1461 | if (D->hasAttr<InternalLinkageAttr>()) |
1462 | return LinkageInfo::internal(); |
1463 | |
1464 | // Objective-C: treat all Objective-C declarations as having external |
1465 | // linkage. |
1466 | switch (D->getKind()) { |
1467 | default: |
1468 | break; |
1469 | |
1470 | // Per C++ [basic.link]p2, only the names of objects, references, |
1471 | // functions, types, templates, namespaces, and values ever have linkage. |
1472 | // |
1473 | // Note that the name of a typedef, namespace alias, using declaration, |
1474 | // and so on are not the name of the corresponding type, namespace, or |
1475 | // declaration, so they do *not* have linkage. |
1476 | case Decl::ImplicitParam: |
1477 | case Decl::Label: |
1478 | case Decl::NamespaceAlias: |
1479 | case Decl::ParmVar: |
1480 | case Decl::Using: |
1481 | case Decl::UsingEnum: |
1482 | case Decl::UsingShadow: |
1483 | case Decl::UsingDirective: |
1484 | return LinkageInfo::none(); |
1485 | |
1486 | case Decl::EnumConstant: |
1487 | // C++ [basic.link]p4: an enumerator has the linkage of its enumeration. |
1488 | if (D->getASTContext().getLangOpts().CPlusPlus) |
1489 | return getLVForDecl(D: cast<EnumDecl>(D->getDeclContext()), computation); |
1490 | return LinkageInfo::visible_none(); |
1491 | |
1492 | case Decl::Typedef: |
1493 | case Decl::TypeAlias: |
1494 | // A typedef declaration has linkage if it gives a type a name for |
1495 | // linkage purposes. |
1496 | if (!cast<TypedefNameDecl>(Val: D) |
1497 | ->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) |
1498 | return LinkageInfo::none(); |
1499 | break; |
1500 | |
1501 | case Decl::TemplateTemplateParm: // count these as external |
1502 | case Decl::NonTypeTemplateParm: |
1503 | case Decl::ObjCAtDefsField: |
1504 | case Decl::ObjCCategory: |
1505 | case Decl::ObjCCategoryImpl: |
1506 | case Decl::ObjCCompatibleAlias: |
1507 | case Decl::ObjCImplementation: |
1508 | case Decl::ObjCMethod: |
1509 | case Decl::ObjCProperty: |
1510 | case Decl::ObjCPropertyImpl: |
1511 | case Decl::ObjCProtocol: |
1512 | return getExternalLinkageFor(D); |
1513 | |
1514 | case Decl::CXXRecord: { |
1515 | const auto *Record = cast<CXXRecordDecl>(Val: D); |
1516 | if (Record->isLambda()) { |
1517 | if (Record->hasKnownLambdaInternalLinkage() || |
1518 | !Record->getLambdaManglingNumber()) { |
1519 | // This lambda has no mangling number, so it's internal. |
1520 | return LinkageInfo::internal(); |
1521 | } |
1522 | |
1523 | return getLVForClosure( |
1524 | DC: Record->getDeclContext()->getRedeclContext(), |
1525 | ContextDecl: Record->getLambdaContextDecl(), computation); |
1526 | } |
1527 | |
1528 | break; |
1529 | } |
1530 | |
1531 | case Decl::TemplateParamObject: { |
1532 | // The template parameter object can be referenced from anywhere its type |
1533 | // and value can be referenced. |
1534 | auto *TPO = cast<TemplateParamObjectDecl>(Val: D); |
1535 | LinkageInfo LV = getLVForType(T: *TPO->getType(), computation); |
1536 | LV.merge(other: getLVForValue(V: TPO->getValue(), computation)); |
1537 | return LV; |
1538 | } |
1539 | } |
1540 | |
1541 | // Handle linkage for namespace-scope names. |
1542 | if (D->getDeclContext()->getRedeclContext()->isFileContext()) |
1543 | return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage); |
1544 | |
1545 | // C++ [basic.link]p5: |
1546 | // In addition, a member function, static data member, a named |
1547 | // class or enumeration of class scope, or an unnamed class or |
1548 | // enumeration defined in a class-scope typedef declaration such |
1549 | // that the class or enumeration has the typedef name for linkage |
1550 | // purposes (7.1.3), has external linkage if the name of the class |
1551 | // has external linkage. |
1552 | if (D->getDeclContext()->isRecord()) |
1553 | return getLVForClassMember(D, computation, IgnoreVarTypeLinkage); |
1554 | |
1555 | // C++ [basic.link]p6: |
1556 | // The name of a function declared in block scope and the name of |
1557 | // an object declared by a block scope extern declaration have |
1558 | // linkage. If there is a visible declaration of an entity with |
1559 | // linkage having the same name and type, ignoring entities |
1560 | // declared outside the innermost enclosing namespace scope, the |
1561 | // block scope declaration declares that same entity and receives |
1562 | // the linkage of the previous declaration. If there is more than |
1563 | // one such matching entity, the program is ill-formed. Otherwise, |
1564 | // if no matching entity is found, the block scope entity receives |
1565 | // external linkage. |
1566 | if (D->getDeclContext()->isFunctionOrMethod()) |
1567 | return getLVForLocalDecl(D, computation); |
1568 | |
1569 | // C++ [basic.link]p6: |
1570 | // Names not covered by these rules have no linkage. |
1571 | return LinkageInfo::none(); |
1572 | } |
1573 | |
1574 | /// getLVForDecl - Get the linkage and visibility for the given declaration. |
1575 | LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D, |
1576 | LVComputationKind computation) { |
1577 | // Internal_linkage attribute overrides other considerations. |
1578 | if (D->hasAttr<InternalLinkageAttr>()) |
1579 | return LinkageInfo::internal(); |
1580 | |
1581 | if (computation.IgnoreAllVisibility && D->hasCachedLinkage()) |
1582 | return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false); |
1583 | |
1584 | if (std::optional<LinkageInfo> LI = lookup(ND: D, Kind: computation)) |
1585 | return *LI; |
1586 | |
1587 | LinkageInfo LV = computeLVForDecl(D, computation); |
1588 | if (D->hasCachedLinkage()) |
1589 | assert(D->getCachedLinkage() == LV.getLinkage()); |
1590 | |
1591 | D->setCachedLinkage(LV.getLinkage()); |
1592 | cache(ND: D, Kind: computation, Info: LV); |
1593 | |
1594 | #ifndef NDEBUG |
1595 | // In C (because of gnu inline) and in c++ with microsoft extensions an |
1596 | // static can follow an extern, so we can have two decls with different |
1597 | // linkages. |
1598 | const LangOptions &Opts = D->getASTContext().getLangOpts(); |
1599 | if (!Opts.CPlusPlus || Opts.MicrosoftExt) |
1600 | return LV; |
1601 | |
1602 | // We have just computed the linkage for this decl. By induction we know |
1603 | // that all other computed linkages match, check that the one we just |
1604 | // computed also does. |
1605 | NamedDecl *Old = nullptr; |
1606 | for (auto *I : D->redecls()) { |
1607 | auto *T = cast<NamedDecl>(I); |
1608 | if (T == D) |
1609 | continue; |
1610 | if (!T->isInvalidDecl() && T->hasCachedLinkage()) { |
1611 | Old = T; |
1612 | break; |
1613 | } |
1614 | } |
1615 | assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage()); |
1616 | #endif |
1617 | |
1618 | return LV; |
1619 | } |
1620 | |
1621 | LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) { |
1622 | NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D) |
1623 | ? NamedDecl::VisibilityForType |
1624 | : NamedDecl::VisibilityForValue; |
1625 | LVComputationKind CK(EK); |
1626 | return getLVForDecl(D, computation: D->getASTContext().getLangOpts().IgnoreXCOFFVisibility |
1627 | ? CK.forLinkageOnly() |
1628 | : CK); |
1629 | } |
1630 | |
1631 | Module *Decl::getOwningModuleForLinkage() const { |
1632 | if (isa<NamespaceDecl>(Val: this)) |
1633 | // Namespaces never have module linkage. It is the entities within them |
1634 | // that [may] do. |
1635 | return nullptr; |
1636 | |
1637 | Module *M = getOwningModule(); |
1638 | if (!M) |
1639 | return nullptr; |
1640 | |
1641 | switch (M->Kind) { |
1642 | case Module::ModuleMapModule: |
1643 | // Module map modules have no special linkage semantics. |
1644 | return nullptr; |
1645 | |
1646 | case Module::ModuleInterfaceUnit: |
1647 | case Module::ModuleImplementationUnit: |
1648 | case Module::ModulePartitionInterface: |
1649 | case Module::ModulePartitionImplementation: |
1650 | return M; |
1651 | |
1652 | case Module::ModuleHeaderUnit: |
1653 | case Module::ExplicitGlobalModuleFragment: |
1654 | case Module::ImplicitGlobalModuleFragment: |
1655 | // The global module shouldn't change the linkage. |
1656 | return nullptr; |
1657 | |
1658 | case Module::PrivateModuleFragment: |
1659 | // The private module fragment is part of its containing module for linkage |
1660 | // purposes. |
1661 | return M->Parent; |
1662 | } |
1663 | |
1664 | llvm_unreachable("unknown module kind"); |
1665 | } |
1666 | |
1667 | void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { |
1668 | Name.print(OS, Policy); |
1669 | } |
1670 | |
1671 | void NamedDecl::printName(raw_ostream &OS) const { |
1672 | printName(OS, getASTContext().getPrintingPolicy()); |
1673 | } |
1674 | |
1675 | std::string NamedDecl::getQualifiedNameAsString() const { |
1676 | std::string QualName; |
1677 | llvm::raw_string_ostream OS(QualName); |
1678 | printQualifiedName(OS, getASTContext().getPrintingPolicy()); |
1679 | return QualName; |
1680 | } |
1681 | |
1682 | void NamedDecl::printQualifiedName(raw_ostream &OS) const { |
1683 | printQualifiedName(OS, getASTContext().getPrintingPolicy()); |
1684 | } |
1685 | |
1686 | void NamedDecl::printQualifiedName(raw_ostream &OS, |
1687 | const PrintingPolicy &P) const { |
1688 | if (getDeclContext()->isFunctionOrMethod()) { |
1689 | // We do not print '(anonymous)' for function parameters without name. |
1690 | printName(OS, Policy: P); |
1691 | return; |
1692 | } |
1693 | printNestedNameSpecifier(OS, Policy: P); |
1694 | if (getDeclName()) |
1695 | OS << *this; |
1696 | else { |
1697 | // Give the printName override a chance to pick a different name before we |
1698 | // fall back to "(anonymous)". |
1699 | SmallString<64> NameBuffer; |
1700 | llvm::raw_svector_ostream NameOS(NameBuffer); |
1701 | printName(OS&: NameOS, Policy: P); |
1702 | if (NameBuffer.empty()) |
1703 | OS << "(anonymous)"; |
1704 | else |
1705 | OS << NameBuffer; |
1706 | } |
1707 | } |
1708 | |
1709 | void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const { |
1710 | printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy()); |
1711 | } |
1712 | |
1713 | void NamedDecl::printNestedNameSpecifier(raw_ostream &OS, |
1714 | const PrintingPolicy &P) const { |
1715 | const DeclContext *Ctx = getDeclContext(); |
1716 | |
1717 | // For ObjC methods and properties, look through categories and use the |
1718 | // interface as context. |
1719 | if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: this)) { |
1720 | if (auto *ID = MD->getClassInterface()) |
1721 | Ctx = ID; |
1722 | } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(Val: this)) { |
1723 | if (auto *MD = PD->getGetterMethodDecl()) |
1724 | if (auto *ID = MD->getClassInterface()) |
1725 | Ctx = ID; |
1726 | } else if (auto *ID = dyn_cast<ObjCIvarDecl>(Val: this)) { |
1727 | if (auto *CI = ID->getContainingInterface()) |
1728 | Ctx = CI; |
1729 | } |
1730 | |
1731 | if (Ctx->isFunctionOrMethod()) |
1732 | return; |
1733 | |
1734 | using ContextsTy = SmallVector<const DeclContext *, 8>; |
1735 | ContextsTy Contexts; |
1736 | |
1737 | // Collect named contexts. |
1738 | DeclarationName NameInScope = getDeclName(); |
1739 | for (; Ctx; Ctx = Ctx->getParent()) { |
1740 | // Suppress anonymous namespace if requested. |
1741 | if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Val: Ctx) && |
1742 | cast<NamespaceDecl>(Val: Ctx)->isAnonymousNamespace()) |
1743 | continue; |
1744 | |
1745 | // Suppress inline namespace if it doesn't make the result ambiguous. |
1746 | if (Ctx->isInlineNamespace() && NameInScope) { |
1747 | if (P.SuppressInlineNamespace == |
1748 | PrintingPolicy::SuppressInlineNamespaceMode::All || |
1749 | (P.SuppressInlineNamespace == |
1750 | PrintingPolicy::SuppressInlineNamespaceMode::Redundant && |
1751 | cast<NamespaceDecl>(Val: Ctx)->isRedundantInlineQualifierFor( |
1752 | Name: NameInScope))) { |
1753 | continue; |
1754 | } |
1755 | } |
1756 | |
1757 | // Suppress transparent contexts like export or HLSLBufferDecl context |
1758 | if (Ctx->isTransparentContext()) |
1759 | continue; |
1760 | |
1761 | // Skip non-named contexts such as linkage specifications and ExportDecls. |
1762 | const NamedDecl *ND = dyn_cast<NamedDecl>(Val: Ctx); |
1763 | if (!ND) |
1764 | continue; |
1765 | |
1766 | Contexts.push_back(Elt: Ctx); |
1767 | NameInScope = ND->getDeclName(); |
1768 | } |
1769 | |
1770 | for (const DeclContext *DC : llvm::reverse(C&: Contexts)) { |
1771 | if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) { |
1772 | OS << Spec->getName(); |
1773 | const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); |
1774 | printTemplateArgumentList( |
1775 | OS, TemplateArgs.asArray(), P, |
1776 | Spec->getSpecializedTemplate()->getTemplateParameters()); |
1777 | } else if (const auto *ND = dyn_cast<NamespaceDecl>(Val: DC)) { |
1778 | if (ND->isAnonymousNamespace()) { |
1779 | OS << (P.MSVCFormatting ? "`anonymous namespace\'" |
1780 | : "(anonymous namespace)"); |
1781 | } |
1782 | else |
1783 | OS << *ND; |
1784 | } else if (const auto *RD = dyn_cast<RecordDecl>(Val: DC)) { |
1785 | if (!RD->getIdentifier()) |
1786 | OS << "(anonymous "<< RD->getKindName() << ')'; |
1787 | else |
1788 | OS << *RD; |
1789 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: DC)) { |
1790 | const FunctionProtoType *FT = nullptr; |
1791 | if (FD->hasWrittenPrototype()) |
1792 | FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); |
1793 | |
1794 | OS << *FD << '('; |
1795 | if (FT) { |
1796 | unsigned NumParams = FD->getNumParams(); |
1797 | for (unsigned i = 0; i < NumParams; ++i) { |
1798 | if (i) |
1799 | OS << ", "; |
1800 | OS << FD->getParamDecl(i)->getType().stream(P); |
1801 | } |
1802 | |
1803 | if (FT->isVariadic()) { |
1804 | if (NumParams > 0) |
1805 | OS << ", "; |
1806 | OS << "..."; |
1807 | } |
1808 | } |
1809 | OS << ')'; |
1810 | } else if (const auto *ED = dyn_cast<EnumDecl>(Val: DC)) { |
1811 | // C++ [dcl.enum]p10: Each enum-name and each unscoped |
1812 | // enumerator is declared in the scope that immediately contains |
1813 | // the enum-specifier. Each scoped enumerator is declared in the |
1814 | // scope of the enumeration. |
1815 | // For the case of unscoped enumerator, do not include in the qualified |
1816 | // name any information about its enum enclosing scope, as its visibility |
1817 | // is global. |
1818 | if (ED->isScoped()) |
1819 | OS << *ED; |
1820 | else |
1821 | continue; |
1822 | } else { |
1823 | OS << *cast<NamedDecl>(Val: DC); |
1824 | } |
1825 | OS << "::"; |
1826 | } |
1827 | } |
1828 | |
1829 | void NamedDecl::getNameForDiagnostic(raw_ostream &OS, |
1830 | const PrintingPolicy &Policy, |
1831 | bool Qualified) const { |
1832 | if (Qualified) |
1833 | printQualifiedName(OS, P: Policy); |
1834 | else |
1835 | printName(OS, Policy); |
1836 | } |
1837 | |
1838 | template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) { |
1839 | return true; |
1840 | } |
1841 | static bool isRedeclarableImpl(...) { return false; } |
1842 | static bool isRedeclarable(Decl::Kind K) { |
1843 | switch (K) { |
1844 | #define DECL(Type, Base) \ |
1845 | case Decl::Type: \ |
1846 | return isRedeclarableImpl((Type##Decl *)nullptr); |
1847 | #define ABSTRACT_DECL(DECL) |
1848 | #include "clang/AST/DeclNodes.inc" |
1849 | } |
1850 | llvm_unreachable("unknown decl kind"); |
1851 | } |
1852 | |
1853 | bool NamedDecl::declarationReplaces(const NamedDecl *OldD, |
1854 | bool IsKnownNewer) const { |
1855 | assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); |
1856 | |
1857 | // Never replace one imported declaration with another; we need both results |
1858 | // when re-exporting. |
1859 | if (OldD->isFromASTFile() && isFromASTFile()) |
1860 | return false; |
1861 | |
1862 | // A kind mismatch implies that the declaration is not replaced. |
1863 | if (OldD->getKind() != getKind()) |
1864 | return false; |
1865 | |
1866 | // For method declarations, we never replace. (Why?) |
1867 | if (isa<ObjCMethodDecl>(this)) |
1868 | return false; |
1869 | |
1870 | // For parameters, pick the newer one. This is either an error or (in |
1871 | // Objective-C) permitted as an extension. |
1872 | if (isa<ParmVarDecl>(this)) |
1873 | return true; |
1874 | |
1875 | // Inline namespaces can give us two declarations with the same |
1876 | // name and kind in the same scope but different contexts; we should |
1877 | // keep both declarations in this case. |
1878 | if (!this->getDeclContext()->getRedeclContext()->Equals( |
1879 | OldD->getDeclContext()->getRedeclContext())) |
1880 | return false; |
1881 | |
1882 | // Using declarations can be replaced if they import the same name from the |
1883 | // same context. |
1884 | if (const auto *UD = dyn_cast<UsingDecl>(this)) { |
1885 | ASTContext &Context = getASTContext(); |
1886 | return Context.getCanonicalNestedNameSpecifier(NNS: UD->getQualifier()) == |
1887 | Context.getCanonicalNestedNameSpecifier( |
1888 | NNS: cast<UsingDecl>(OldD)->getQualifier()); |
1889 | } |
1890 | if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) { |
1891 | ASTContext &Context = getASTContext(); |
1892 | return Context.getCanonicalNestedNameSpecifier(NNS: UUVD->getQualifier()) == |
1893 | Context.getCanonicalNestedNameSpecifier( |
1894 | NNS: cast<UnresolvedUsingValueDecl>(OldD)->getQualifier()); |
1895 | } |
1896 | |
1897 | if (isRedeclarable(getKind())) { |
1898 | if (getCanonicalDecl() != OldD->getCanonicalDecl()) |
1899 | return false; |
1900 | |
1901 | if (IsKnownNewer) |
1902 | return true; |
1903 | |
1904 | // Check whether this is actually newer than OldD. We want to keep the |
1905 | // newer declaration. This loop will usually only iterate once, because |
1906 | // OldD is usually the previous declaration. |
1907 | for (const auto *D : redecls()) { |
1908 | if (D == OldD) |
1909 | break; |
1910 | |
1911 | // If we reach the canonical declaration, then OldD is not actually older |
1912 | // than this one. |
1913 | // |
1914 | // FIXME: In this case, we should not add this decl to the lookup table. |
1915 | if (D->isCanonicalDecl()) |
1916 | return false; |
1917 | } |
1918 | |
1919 | // It's a newer declaration of the same kind of declaration in the same |
1920 | // scope: we want this decl instead of the existing one. |
1921 | return true; |
1922 | } |
1923 | |
1924 | // In all other cases, we need to keep both declarations in case they have |
1925 | // different visibility. Any attempt to use the name will result in an |
1926 | // ambiguity if more than one is visible. |
1927 | return false; |
1928 | } |
1929 | |
1930 | bool NamedDecl::hasLinkage() const { |
1931 | switch (getFormalLinkage()) { |
1932 | case Linkage::Invalid: |
1933 | llvm_unreachable("Linkage hasn't been computed!"); |
1934 | case Linkage::None: |
1935 | return false; |
1936 | case Linkage::Internal: |
1937 | return true; |
1938 | case Linkage::UniqueExternal: |
1939 | case Linkage::VisibleNone: |
1940 | llvm_unreachable("Non-formal linkage is not allowed here!"); |
1941 | case Linkage::Module: |
1942 | case Linkage::External: |
1943 | return true; |
1944 | } |
1945 | llvm_unreachable("Unhandled Linkage enum"); |
1946 | } |
1947 | |
1948 | NamedDecl *NamedDecl::getUnderlyingDeclImpl() { |
1949 | NamedDecl *ND = this; |
1950 | if (auto *UD = dyn_cast<UsingShadowDecl>(Val: ND)) |
1951 | ND = UD->getTargetDecl(); |
1952 | |
1953 | if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(Val: ND)) |
1954 | return AD->getClassInterface(); |
1955 | |
1956 | if (auto *AD = dyn_cast<NamespaceAliasDecl>(Val: ND)) |
1957 | return AD->getNamespace(); |
1958 | |
1959 | return ND; |
1960 | } |
1961 | |
1962 | bool NamedDecl::isCXXInstanceMember() const { |
1963 | if (!isCXXClassMember()) |
1964 | return false; |
1965 | |
1966 | const NamedDecl *D = this; |
1967 | if (isa<UsingShadowDecl>(Val: D)) |
1968 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
1969 | |
1970 | if (isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) || isa<MSPropertyDecl>(Val: D)) |
1971 | return true; |
1972 | if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction())) |
1973 | return MD->isInstance(); |
1974 | return false; |
1975 | } |
1976 | |
1977 | //===----------------------------------------------------------------------===// |
1978 | // DeclaratorDecl Implementation |
1979 | //===----------------------------------------------------------------------===// |
1980 | |
1981 | template <typename DeclT> |
1982 | static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { |
1983 | if (decl->getNumTemplateParameterLists() > 0) |
1984 | return decl->getTemplateParameterList(0)->getTemplateLoc(); |
1985 | return decl->getInnerLocStart(); |
1986 | } |
1987 | |
1988 | SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { |
1989 | TypeSourceInfo *TSI = getTypeSourceInfo(); |
1990 | if (TSI) return TSI->getTypeLoc().getBeginLoc(); |
1991 | return SourceLocation(); |
1992 | } |
1993 | |
1994 | SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const { |
1995 | TypeSourceInfo *TSI = getTypeSourceInfo(); |
1996 | if (TSI) return TSI->getTypeLoc().getEndLoc(); |
1997 | return SourceLocation(); |
1998 | } |
1999 | |
2000 | void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { |
2001 | if (QualifierLoc) { |
2002 | // Make sure the extended decl info is allocated. |
2003 | if (!hasExtInfo()) { |
2004 | // Save (non-extended) type source info pointer. |
2005 | auto *savedTInfo = cast<TypeSourceInfo *>(Val&: DeclInfo); |
2006 | // Allocate external info struct. |
2007 | DeclInfo = new (getASTContext()) ExtInfo; |
2008 | // Restore savedTInfo into (extended) decl info. |
2009 | getExtInfo()->TInfo = savedTInfo; |
2010 | } |
2011 | // Set qualifier info. |
2012 | getExtInfo()->QualifierLoc = QualifierLoc; |
2013 | } else if (hasExtInfo()) { |
2014 | // Here Qualifier == 0, i.e., we are removing the qualifier (if any). |
2015 | getExtInfo()->QualifierLoc = QualifierLoc; |
2016 | } |
2017 | } |
2018 | |
2019 | void DeclaratorDecl::setTrailingRequiresClause(const AssociatedConstraint &AC) { |
2020 | assert(AC); |
2021 | // Make sure the extended decl info is allocated. |
2022 | if (!hasExtInfo()) { |
2023 | // Save (non-extended) type source info pointer. |
2024 | auto *savedTInfo = cast<TypeSourceInfo *>(Val&: DeclInfo); |
2025 | // Allocate external info struct. |
2026 | DeclInfo = new (getASTContext()) ExtInfo; |
2027 | // Restore savedTInfo into (extended) decl info. |
2028 | getExtInfo()->TInfo = savedTInfo; |
2029 | } |
2030 | // Set requires clause info. |
2031 | getExtInfo()->TrailingRequiresClause = AC; |
2032 | } |
2033 | |
2034 | void DeclaratorDecl::setTemplateParameterListsInfo( |
2035 | ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { |
2036 | assert(!TPLists.empty()); |
2037 | // Make sure the extended decl info is allocated. |
2038 | if (!hasExtInfo()) { |
2039 | // Save (non-extended) type source info pointer. |
2040 | auto *savedTInfo = cast<TypeSourceInfo *>(Val&: DeclInfo); |
2041 | // Allocate external info struct. |
2042 | DeclInfo = new (getASTContext()) ExtInfo; |
2043 | // Restore savedTInfo into (extended) decl info. |
2044 | getExtInfo()->TInfo = savedTInfo; |
2045 | } |
2046 | // Set the template parameter lists info. |
2047 | getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); |
2048 | } |
2049 | |
2050 | SourceLocation DeclaratorDecl::getOuterLocStart() const { |
2051 | return getTemplateOrInnerLocStart(decl: this); |
2052 | } |
2053 | |
2054 | // Helper function: returns true if QT is or contains a type |
2055 | // having a postfix component. |
2056 | static bool typeIsPostfix(QualType QT) { |
2057 | while (true) { |
2058 | const Type* T = QT.getTypePtr(); |
2059 | switch (T->getTypeClass()) { |
2060 | default: |
2061 | return false; |
2062 | case Type::Pointer: |
2063 | QT = cast<PointerType>(Val: T)->getPointeeType(); |
2064 | break; |
2065 | case Type::BlockPointer: |
2066 | QT = cast<BlockPointerType>(Val: T)->getPointeeType(); |
2067 | break; |
2068 | case Type::MemberPointer: |
2069 | QT = cast<MemberPointerType>(Val: T)->getPointeeType(); |
2070 | break; |
2071 | case Type::LValueReference: |
2072 | case Type::RValueReference: |
2073 | QT = cast<ReferenceType>(Val: T)->getPointeeType(); |
2074 | break; |
2075 | case Type::PackExpansion: |
2076 | QT = cast<PackExpansionType>(Val: T)->getPattern(); |
2077 | break; |
2078 | case Type::Paren: |
2079 | case Type::ConstantArray: |
2080 | case Type::DependentSizedArray: |
2081 | case Type::IncompleteArray: |
2082 | case Type::VariableArray: |
2083 | case Type::FunctionProto: |
2084 | case Type::FunctionNoProto: |
2085 | return true; |
2086 | } |
2087 | } |
2088 | } |
2089 | |
2090 | SourceRange DeclaratorDecl::getSourceRange() const { |
2091 | SourceLocation RangeEnd = getLocation(); |
2092 | if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { |
2093 | // If the declaration has no name or the type extends past the name take the |
2094 | // end location of the type. |
2095 | if (!getDeclName() || typeIsPostfix(QT: TInfo->getType())) |
2096 | RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); |
2097 | } |
2098 | return SourceRange(getOuterLocStart(), RangeEnd); |
2099 | } |
2100 | |
2101 | void QualifierInfo::setTemplateParameterListsInfo( |
2102 | ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { |
2103 | // Free previous template parameters (if any). |
2104 | if (NumTemplParamLists > 0) { |
2105 | Context.Deallocate(Ptr: TemplParamLists); |
2106 | TemplParamLists = nullptr; |
2107 | NumTemplParamLists = 0; |
2108 | } |
2109 | // Set info on matched template parameter lists (if any). |
2110 | if (!TPLists.empty()) { |
2111 | TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()]; |
2112 | NumTemplParamLists = TPLists.size(); |
2113 | std::copy(first: TPLists.begin(), last: TPLists.end(), result: TemplParamLists); |
2114 | } |
2115 | } |
2116 | |
2117 | //===----------------------------------------------------------------------===// |
2118 | // VarDecl Implementation |
2119 | //===----------------------------------------------------------------------===// |
2120 | |
2121 | const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { |
2122 | switch (SC) { |
2123 | case SC_None: break; |
2124 | case SC_Auto: return "auto"; |
2125 | case SC_Extern: return "extern"; |
2126 | case SC_PrivateExtern: return "__private_extern__"; |
2127 | case SC_Register: return "register"; |
2128 | case SC_Static: return "static"; |
2129 | } |
2130 | |
2131 | llvm_unreachable("Invalid storage class"); |
2132 | } |
2133 | |
2134 | VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC, |
2135 | SourceLocation StartLoc, SourceLocation IdLoc, |
2136 | const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, |
2137 | StorageClass SC) |
2138 | : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), |
2139 | redeclarable_base(C) { |
2140 | static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned), |
2141 | "VarDeclBitfields too large!"); |
2142 | static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned), |
2143 | "ParmVarDeclBitfields too large!"); |
2144 | static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned), |
2145 | "NonParmVarDeclBitfields too large!"); |
2146 | AllBits = 0; |
2147 | VarDeclBits.SClass = SC; |
2148 | // Everything else is implicitly initialized to false. |
2149 | } |
2150 | |
2151 | VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL, |
2152 | SourceLocation IdL, const IdentifierInfo *Id, |
2153 | QualType T, TypeSourceInfo *TInfo, StorageClass S) { |
2154 | return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); |
2155 | } |
2156 | |
2157 | VarDecl *VarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
2158 | return new (C, ID) |
2159 | VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr, |
2160 | QualType(), nullptr, SC_None); |
2161 | } |
2162 | |
2163 | void VarDecl::setStorageClass(StorageClass SC) { |
2164 | assert(isLegalForVariable(SC)); |
2165 | VarDeclBits.SClass = SC; |
2166 | } |
2167 | |
2168 | VarDecl::TLSKind VarDecl::getTLSKind() const { |
2169 | switch (VarDeclBits.TSCSpec) { |
2170 | case TSCS_unspecified: |
2171 | if (!hasAttr<ThreadAttr>() && |
2172 | !(getASTContext().getLangOpts().OpenMPUseTLS && |
2173 | getASTContext().getTargetInfo().isTLSSupported() && |
2174 | hasAttr<OMPThreadPrivateDeclAttr>())) |
2175 | return TLS_None; |
2176 | return ((getASTContext().getLangOpts().isCompatibleWithMSVC( |
2177 | LangOptions::MSVC2015)) || |
2178 | hasAttr<OMPThreadPrivateDeclAttr>()) |
2179 | ? TLS_Dynamic |
2180 | : TLS_Static; |
2181 | case TSCS___thread: // Fall through. |
2182 | case TSCS__Thread_local: |
2183 | return TLS_Static; |
2184 | case TSCS_thread_local: |
2185 | return TLS_Dynamic; |
2186 | } |
2187 | llvm_unreachable("Unknown thread storage class specifier!"); |
2188 | } |
2189 | |
2190 | SourceRange VarDecl::getSourceRange() const { |
2191 | if (const Expr *Init = getInit()) { |
2192 | SourceLocation InitEnd = Init->getEndLoc(); |
2193 | // If Init is implicit, ignore its source range and fallback on |
2194 | // DeclaratorDecl::getSourceRange() to handle postfix elements. |
2195 | if (InitEnd.isValid() && InitEnd != getLocation()) |
2196 | return SourceRange(getOuterLocStart(), InitEnd); |
2197 | } |
2198 | return DeclaratorDecl::getSourceRange(); |
2199 | } |
2200 | |
2201 | template<typename T> |
2202 | static LanguageLinkage getDeclLanguageLinkage(const T &D) { |
2203 | // C++ [dcl.link]p1: All function types, function names with external linkage, |
2204 | // and variable names with external linkage have a language linkage. |
2205 | if (!D.hasExternalFormalLinkage()) |
2206 | return NoLanguageLinkage; |
2207 | |
2208 | // Language linkage is a C++ concept, but saying that everything else in C has |
2209 | // C language linkage fits the implementation nicely. |
2210 | if (!D.getASTContext().getLangOpts().CPlusPlus) |
2211 | return CLanguageLinkage; |
2212 | |
2213 | // C++ [dcl.link]p4: A C language linkage is ignored in determining the |
2214 | // language linkage of the names of class members and the function type of |
2215 | // class member functions. |
2216 | const DeclContext *DC = D.getDeclContext(); |
2217 | if (DC->isRecord()) |
2218 | return CXXLanguageLinkage; |
2219 | |
2220 | // If the first decl is in an extern "C" context, any other redeclaration |
2221 | // will have C language linkage. If the first one is not in an extern "C" |
2222 | // context, we would have reported an error for any other decl being in one. |
2223 | if (isFirstInExternCContext(&D)) |
2224 | return CLanguageLinkage; |
2225 | return CXXLanguageLinkage; |
2226 | } |
2227 | |
2228 | template<typename T> |
2229 | static bool isDeclExternC(const T &D) { |
2230 | // Since the context is ignored for class members, they can only have C++ |
2231 | // language linkage or no language linkage. |
2232 | const DeclContext *DC = D.getDeclContext(); |
2233 | if (DC->isRecord()) { |
2234 | assert(D.getASTContext().getLangOpts().CPlusPlus); |
2235 | return false; |
2236 | } |
2237 | |
2238 | return D.getLanguageLinkage() == CLanguageLinkage; |
2239 | } |
2240 | |
2241 | LanguageLinkage VarDecl::getLanguageLinkage() const { |
2242 | return getDeclLanguageLinkage(D: *this); |
2243 | } |
2244 | |
2245 | bool VarDecl::isExternC() const { |
2246 | return isDeclExternC(D: *this); |
2247 | } |
2248 | |
2249 | bool VarDecl::isInExternCContext() const { |
2250 | return getLexicalDeclContext()->isExternCContext(); |
2251 | } |
2252 | |
2253 | bool VarDecl::isInExternCXXContext() const { |
2254 | return getLexicalDeclContext()->isExternCXXContext(); |
2255 | } |
2256 | |
2257 | VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); } |
2258 | |
2259 | VarDecl::DefinitionKind |
2260 | VarDecl::isThisDeclarationADefinition(ASTContext &C) const { |
2261 | if (isThisDeclarationADemotedDefinition()) |
2262 | return DeclarationOnly; |
2263 | |
2264 | // C++ [basic.def]p2: |
2265 | // A declaration is a definition unless [...] it contains the 'extern' |
2266 | // specifier or a linkage-specification and neither an initializer [...], |
2267 | // it declares a non-inline static data member in a class declaration [...], |
2268 | // it declares a static data member outside a class definition and the variable |
2269 | // was defined within the class with the constexpr specifier [...], |
2270 | // C++1y [temp.expl.spec]p15: |
2271 | // An explicit specialization of a static data member or an explicit |
2272 | // specialization of a static data member template is a definition if the |
2273 | // declaration includes an initializer; otherwise, it is a declaration. |
2274 | // |
2275 | // FIXME: How do you declare (but not define) a partial specialization of |
2276 | // a static data member template outside the containing class? |
2277 | if (isStaticDataMember()) { |
2278 | if (isOutOfLine() && |
2279 | !(getCanonicalDecl()->isInline() && |
2280 | getCanonicalDecl()->isConstexpr()) && |
2281 | (hasInit() || |
2282 | // If the first declaration is out-of-line, this may be an |
2283 | // instantiation of an out-of-line partial specialization of a variable |
2284 | // template for which we have not yet instantiated the initializer. |
2285 | (getFirstDecl()->isOutOfLine() |
2286 | ? getTemplateSpecializationKind() == TSK_Undeclared |
2287 | : getTemplateSpecializationKind() != |
2288 | TSK_ExplicitSpecialization) || |
2289 | isa<VarTemplatePartialSpecializationDecl>(Val: this))) |
2290 | return Definition; |
2291 | if (!isOutOfLine() && isInline()) |
2292 | return Definition; |
2293 | return DeclarationOnly; |
2294 | } |
2295 | // C99 6.7p5: |
2296 | // A definition of an identifier is a declaration for that identifier that |
2297 | // [...] causes storage to be reserved for that object. |
2298 | // Note: that applies for all non-file-scope objects. |
2299 | // C99 6.9.2p1: |
2300 | // If the declaration of an identifier for an object has file scope and an |
2301 | // initializer, the declaration is an external definition for the identifier |
2302 | if (hasInit()) |
2303 | return Definition; |
2304 | |
2305 | if (hasDefiningAttr()) |
2306 | return Definition; |
2307 | |
2308 | if (const auto *SAA = getAttr<SelectAnyAttr>()) |
2309 | if (!SAA->isInherited()) |
2310 | return Definition; |
2311 | |
2312 | // A variable template specialization (other than a static data member |
2313 | // template or an explicit specialization) is a declaration until we |
2314 | // instantiate its initializer. |
2315 | if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: this)) { |
2316 | if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && |
2317 | !isa<VarTemplatePartialSpecializationDecl>(Val: VTSD) && |
2318 | !VTSD->IsCompleteDefinition) |
2319 | return DeclarationOnly; |
2320 | } |
2321 | |
2322 | if (hasExternalStorage()) |
2323 | return DeclarationOnly; |
2324 | |
2325 | // [dcl.link] p7: |
2326 | // A declaration directly contained in a linkage-specification is treated |
2327 | // as if it contains the extern specifier for the purpose of determining |
2328 | // the linkage of the declared name and whether it is a definition. |
2329 | if (isSingleLineLanguageLinkage(*this)) |
2330 | return DeclarationOnly; |
2331 | |
2332 | // C99 6.9.2p2: |
2333 | // A declaration of an object that has file scope without an initializer, |
2334 | // and without a storage class specifier or the scs 'static', constitutes |
2335 | // a tentative definition. |
2336 | // No such thing in C++. |
2337 | if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) |
2338 | return TentativeDefinition; |
2339 | |
2340 | // What's left is (in C, block-scope) declarations without initializers or |
2341 | // external storage. These are definitions. |
2342 | return Definition; |
2343 | } |
2344 | |
2345 | VarDecl *VarDecl::getActingDefinition() { |
2346 | DefinitionKind Kind = isThisDeclarationADefinition(); |
2347 | if (Kind != TentativeDefinition) |
2348 | return nullptr; |
2349 | |
2350 | VarDecl *LastTentative = nullptr; |
2351 | |
2352 | // Loop through the declaration chain, starting with the most recent. |
2353 | for (VarDecl *Decl = getMostRecentDecl(); Decl; |
2354 | Decl = Decl->getPreviousDecl()) { |
2355 | Kind = Decl->isThisDeclarationADefinition(); |
2356 | if (Kind == Definition) |
2357 | return nullptr; |
2358 | // Record the first (most recent) TentativeDefinition that is encountered. |
2359 | if (Kind == TentativeDefinition && !LastTentative) |
2360 | LastTentative = Decl; |
2361 | } |
2362 | |
2363 | return LastTentative; |
2364 | } |
2365 | |
2366 | VarDecl *VarDecl::getDefinition(ASTContext &C) { |
2367 | VarDecl *First = getFirstDecl(); |
2368 | for (auto *I : First->redecls()) { |
2369 | if (I->isThisDeclarationADefinition(C) == Definition) |
2370 | return I; |
2371 | } |
2372 | return nullptr; |
2373 | } |
2374 | |
2375 | VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { |
2376 | DefinitionKind Kind = DeclarationOnly; |
2377 | |
2378 | const VarDecl *First = getFirstDecl(); |
2379 | for (auto *I : First->redecls()) { |
2380 | Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); |
2381 | if (Kind == Definition) |
2382 | break; |
2383 | } |
2384 | |
2385 | return Kind; |
2386 | } |
2387 | |
2388 | const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { |
2389 | for (auto *I : redecls()) { |
2390 | if (auto Expr = I->getInit()) { |
2391 | D = I; |
2392 | return Expr; |
2393 | } |
2394 | } |
2395 | return nullptr; |
2396 | } |
2397 | |
2398 | bool VarDecl::hasInit() const { |
2399 | if (auto *P = dyn_cast<ParmVarDecl>(Val: this)) |
2400 | if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg()) |
2401 | return false; |
2402 | |
2403 | if (auto *Eval = getEvaluatedStmt()) |
2404 | return Eval->Value.isValid(); |
2405 | |
2406 | return !Init.isNull(); |
2407 | } |
2408 | |
2409 | Expr *VarDecl::getInit() { |
2410 | if (!hasInit()) |
2411 | return nullptr; |
2412 | |
2413 | if (auto *S = dyn_cast<Stmt *>(Val&: Init)) |
2414 | return cast<Expr>(Val: S); |
2415 | |
2416 | auto *Eval = getEvaluatedStmt(); |
2417 | |
2418 | return cast<Expr>(Eval->Value.get( |
2419 | Source: Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr)); |
2420 | } |
2421 | |
2422 | Stmt **VarDecl::getInitAddress() { |
2423 | if (auto *ES = Init.dyn_cast<EvaluatedStmt *>()) |
2424 | return ES->Value.getAddressOfPointer(Source: getASTContext().getExternalSource()); |
2425 | |
2426 | return Init.getAddrOfPtr1(); |
2427 | } |
2428 | |
2429 | VarDecl *VarDecl::getInitializingDeclaration() { |
2430 | VarDecl *Def = nullptr; |
2431 | for (auto *I : redecls()) { |
2432 | if (I->hasInit()) |
2433 | return I; |
2434 | |
2435 | if (I->isThisDeclarationADefinition()) { |
2436 | if (isStaticDataMember()) |
2437 | return I; |
2438 | Def = I; |
2439 | } |
2440 | } |
2441 | return Def; |
2442 | } |
2443 | |
2444 | bool VarDecl::isOutOfLine() const { |
2445 | if (Decl::isOutOfLine()) |
2446 | return true; |
2447 | |
2448 | if (!isStaticDataMember()) |
2449 | return false; |
2450 | |
2451 | // If this static data member was instantiated from a static data member of |
2452 | // a class template, check whether that static data member was defined |
2453 | // out-of-line. |
2454 | if (VarDecl *VD = getInstantiatedFromStaticDataMember()) |
2455 | return VD->isOutOfLine(); |
2456 | |
2457 | return false; |
2458 | } |
2459 | |
2460 | void VarDecl::setInit(Expr *I) { |
2461 | if (auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Val&: Init)) { |
2462 | Eval->~EvaluatedStmt(); |
2463 | getASTContext().Deallocate(Eval); |
2464 | } |
2465 | |
2466 | Init = I; |
2467 | } |
2468 | |
2469 | bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const { |
2470 | const LangOptions &Lang = C.getLangOpts(); |
2471 | |
2472 | // OpenCL permits const integral variables to be used in constant |
2473 | // expressions, like in C++98. |
2474 | if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23) |
2475 | return false; |
2476 | |
2477 | // Function parameters are never usable in constant expressions. |
2478 | if (isa<ParmVarDecl>(Val: this)) |
2479 | return false; |
2480 | |
2481 | // The values of weak variables are never usable in constant expressions. |
2482 | if (isWeak()) |
2483 | return false; |
2484 | |
2485 | // In C++11, any variable of reference type can be used in a constant |
2486 | // expression if it is initialized by a constant expression. |
2487 | if (Lang.CPlusPlus11 && getType()->isReferenceType()) |
2488 | return true; |
2489 | |
2490 | // Only const objects can be used in constant expressions in C++. C++98 does |
2491 | // not require the variable to be non-volatile, but we consider this to be a |
2492 | // defect. |
2493 | if (!getType().isConstant(C) || getType().isVolatileQualified()) |
2494 | return false; |
2495 | |
2496 | // In C++, but not in C, const, non-volatile variables of integral or |
2497 | // enumeration types can be used in constant expressions. |
2498 | if (getType()->isIntegralOrEnumerationType() && !Lang.C23) |
2499 | return true; |
2500 | |
2501 | // C23 6.6p7: An identifier that is: |
2502 | // ... |
2503 | // - declared with storage-class specifier constexpr and has an object type, |
2504 | // is a named constant, ... such a named constant is a constant expression |
2505 | // with the type and value of the declared object. |
2506 | // Additionally, in C++11, non-volatile constexpr variables can be used in |
2507 | // constant expressions. |
2508 | return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr(); |
2509 | } |
2510 | |
2511 | bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const { |
2512 | // C++2a [expr.const]p3: |
2513 | // A variable is usable in constant expressions after its initializing |
2514 | // declaration is encountered... |
2515 | const VarDecl *DefVD = nullptr; |
2516 | const Expr *Init = getAnyInitializer(D&: DefVD); |
2517 | if (!Init || Init->isValueDependent() || getType()->isDependentType()) |
2518 | return false; |
2519 | // ... if it is a constexpr variable, or it is of reference type or of |
2520 | // const-qualified integral or enumeration type, ... |
2521 | if (!DefVD->mightBeUsableInConstantExpressions(C: Context)) |
2522 | return false; |
2523 | // ... and its initializer is a constant initializer. |
2524 | if ((Context.getLangOpts().CPlusPlus || getLangOpts().C23) && |
2525 | !DefVD->hasConstantInitialization()) |
2526 | return false; |
2527 | // C++98 [expr.const]p1: |
2528 | // An integral constant-expression can involve only [...] const variables |
2529 | // or static data members of integral or enumeration types initialized with |
2530 | // [integer] constant expressions (dcl.init) |
2531 | if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) && |
2532 | !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context)) |
2533 | return false; |
2534 | return true; |
2535 | } |
2536 | |
2537 | /// Convert the initializer for this declaration to the elaborated EvaluatedStmt |
2538 | /// form, which contains extra information on the evaluated value of the |
2539 | /// initializer. |
2540 | EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { |
2541 | auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Val&: Init); |
2542 | if (!Eval) { |
2543 | // Note: EvaluatedStmt contains an APValue, which usually holds |
2544 | // resources not allocated from the ASTContext. We need to do some |
2545 | // work to avoid leaking those, but we do so in VarDecl::evaluateValue |
2546 | // where we can detect whether there's anything to clean up or not. |
2547 | Eval = new (getASTContext()) EvaluatedStmt; |
2548 | Eval->Value = cast<Stmt *>(Val&: Init); |
2549 | Init = Eval; |
2550 | } |
2551 | return Eval; |
2552 | } |
2553 | |
2554 | EvaluatedStmt *VarDecl::getEvaluatedStmt() const { |
2555 | return dyn_cast_if_present<EvaluatedStmt *>(Val&: Init); |
2556 | } |
2557 | |
2558 | APValue *VarDecl::evaluateValue() const { |
2559 | SmallVector<PartialDiagnosticAt, 8> Notes; |
2560 | return evaluateValueImpl(Notes, IsConstantInitialization: hasConstantInitialization()); |
2561 | } |
2562 | |
2563 | APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes, |
2564 | bool IsConstantInitialization) const { |
2565 | EvaluatedStmt *Eval = ensureEvaluatedStmt(); |
2566 | |
2567 | const auto *Init = getInit(); |
2568 | assert(!Init->isValueDependent()); |
2569 | |
2570 | // We only produce notes indicating why an initializer is non-constant the |
2571 | // first time it is evaluated. FIXME: The notes won't always be emitted the |
2572 | // first time we try evaluation, so might not be produced at all. |
2573 | if (Eval->WasEvaluated) |
2574 | return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated; |
2575 | |
2576 | if (Eval->IsEvaluating) { |
2577 | // FIXME: Produce a diagnostic for self-initialization. |
2578 | return nullptr; |
2579 | } |
2580 | |
2581 | Eval->IsEvaluating = true; |
2582 | |
2583 | ASTContext &Ctx = getASTContext(); |
2584 | bool Result = Init->EvaluateAsInitializer(Result&: Eval->Evaluated, Ctx, VD: this, Notes, |
2585 | IsConstantInitializer: IsConstantInitialization); |
2586 | |
2587 | // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't |
2588 | // a constant initializer if we produced notes. In that case, we can't keep |
2589 | // the result, because it may only be correct under the assumption that the |
2590 | // initializer is a constant context. |
2591 | if (IsConstantInitialization && |
2592 | (Ctx.getLangOpts().CPlusPlus || |
2593 | (isConstexpr() && Ctx.getLangOpts().C23)) && |
2594 | !Notes.empty()) |
2595 | Result = false; |
2596 | |
2597 | // Ensure the computed APValue is cleaned up later if evaluation succeeded, |
2598 | // or that it's empty (so that there's nothing to clean up) if evaluation |
2599 | // failed. |
2600 | if (!Result) |
2601 | Eval->Evaluated = APValue(); |
2602 | else if (Eval->Evaluated.needsCleanup()) |
2603 | Ctx.addDestruction(Ptr: &Eval->Evaluated); |
2604 | |
2605 | Eval->IsEvaluating = false; |
2606 | Eval->WasEvaluated = true; |
2607 | |
2608 | return Result ? &Eval->Evaluated : nullptr; |
2609 | } |
2610 | |
2611 | APValue *VarDecl::getEvaluatedValue() const { |
2612 | if (EvaluatedStmt *Eval = getEvaluatedStmt()) |
2613 | if (Eval->WasEvaluated) |
2614 | return &Eval->Evaluated; |
2615 | |
2616 | return nullptr; |
2617 | } |
2618 | |
2619 | bool VarDecl::hasICEInitializer(const ASTContext &Context) const { |
2620 | const Expr *Init = getInit(); |
2621 | assert(Init && "no initializer"); |
2622 | |
2623 | EvaluatedStmt *Eval = ensureEvaluatedStmt(); |
2624 | if (!Eval->CheckedForICEInit) { |
2625 | Eval->CheckedForICEInit = true; |
2626 | Eval->HasICEInit = Init->isIntegerConstantExpr(Ctx: Context); |
2627 | } |
2628 | return Eval->HasICEInit; |
2629 | } |
2630 | |
2631 | bool VarDecl::hasConstantInitialization() const { |
2632 | // In C, all globals and constexpr variables should have constant |
2633 | // initialization. For constexpr variables in C check that initializer is a |
2634 | // constant initializer because they can be used in constant expressions. |
2635 | if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus && |
2636 | !isConstexpr()) |
2637 | return true; |
2638 | |
2639 | // In C++, it depends on whether the evaluation at the point of definition |
2640 | // was evaluatable as a constant initializer. |
2641 | if (EvaluatedStmt *Eval = getEvaluatedStmt()) |
2642 | return Eval->HasConstantInitialization; |
2643 | |
2644 | return false; |
2645 | } |
2646 | |
2647 | bool VarDecl::checkForConstantInitialization( |
2648 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { |
2649 | EvaluatedStmt *Eval = ensureEvaluatedStmt(); |
2650 | // If we ask for the value before we know whether we have a constant |
2651 | // initializer, we can compute the wrong value (for example, due to |
2652 | // std::is_constant_evaluated()). |
2653 | assert(!Eval->WasEvaluated && |
2654 | "already evaluated var value before checking for constant init"); |
2655 | assert((getASTContext().getLangOpts().CPlusPlus || |
2656 | getASTContext().getLangOpts().C23) && |
2657 | "only meaningful in C++/C23"); |
2658 | |
2659 | assert(!getInit()->isValueDependent()); |
2660 | |
2661 | // Evaluate the initializer to check whether it's a constant expression. |
2662 | Eval->HasConstantInitialization = |
2663 | evaluateValueImpl(Notes, IsConstantInitialization: true) && Notes.empty(); |
2664 | |
2665 | // If evaluation as a constant initializer failed, allow re-evaluation as a |
2666 | // non-constant initializer if we later find we want the value. |
2667 | if (!Eval->HasConstantInitialization) |
2668 | Eval->WasEvaluated = false; |
2669 | |
2670 | return Eval->HasConstantInitialization; |
2671 | } |
2672 | |
2673 | template<typename DeclT> |
2674 | static DeclT *getDefinitionOrSelf(DeclT *D) { |
2675 | assert(D); |
2676 | if (auto *Def = D->getDefinition()) |
2677 | return Def; |
2678 | return D; |
2679 | } |
2680 | |
2681 | bool VarDecl::isEscapingByref() const { |
2682 | return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref; |
2683 | } |
2684 | |
2685 | bool VarDecl::isNonEscapingByref() const { |
2686 | return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref; |
2687 | } |
2688 | |
2689 | bool VarDecl::hasDependentAlignment() const { |
2690 | QualType T = getType(); |
2691 | return T->isDependentType() || T->isUndeducedType() || |
2692 | llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) { |
2693 | return AA->isAlignmentDependent(); |
2694 | }); |
2695 | } |
2696 | |
2697 | VarDecl *VarDecl::getTemplateInstantiationPattern() const { |
2698 | const VarDecl *VD = this; |
2699 | |
2700 | // If this is an instantiated member, walk back to the template from which |
2701 | // it was instantiated. |
2702 | if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) { |
2703 | if (isTemplateInstantiation(Kind: MSInfo->getTemplateSpecializationKind())) { |
2704 | VD = VD->getInstantiatedFromStaticDataMember(); |
2705 | while (auto *NewVD = VD->getInstantiatedFromStaticDataMember()) |
2706 | VD = NewVD; |
2707 | } |
2708 | } |
2709 | |
2710 | // If it's an instantiated variable template specialization, find the |
2711 | // template or partial specialization from which it was instantiated. |
2712 | if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) { |
2713 | if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) { |
2714 | auto From = VDTemplSpec->getInstantiatedFrom(); |
2715 | if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) { |
2716 | while (!VTD->isMemberSpecialization()) { |
2717 | auto *NewVTD = VTD->getInstantiatedFromMemberTemplate(); |
2718 | if (!NewVTD) |
2719 | break; |
2720 | VTD = NewVTD; |
2721 | } |
2722 | return getDefinitionOrSelf(D: VTD->getTemplatedDecl()); |
2723 | } |
2724 | if (auto *VTPSD = |
2725 | From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { |
2726 | while (!VTPSD->isMemberSpecialization()) { |
2727 | auto *NewVTPSD = VTPSD->getInstantiatedFromMember(); |
2728 | if (!NewVTPSD) |
2729 | break; |
2730 | VTPSD = NewVTPSD; |
2731 | } |
2732 | return getDefinitionOrSelf<VarDecl>(VTPSD); |
2733 | } |
2734 | } |
2735 | } |
2736 | |
2737 | // If this is the pattern of a variable template, find where it was |
2738 | // instantiated from. FIXME: Is this necessary? |
2739 | if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) { |
2740 | while (!VarTemplate->isMemberSpecialization()) { |
2741 | auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate(); |
2742 | if (!NewVT) |
2743 | break; |
2744 | VarTemplate = NewVT; |
2745 | } |
2746 | |
2747 | return getDefinitionOrSelf(D: VarTemplate->getTemplatedDecl()); |
2748 | } |
2749 | |
2750 | if (VD == this) |
2751 | return nullptr; |
2752 | return getDefinitionOrSelf(D: const_cast<VarDecl*>(VD)); |
2753 | } |
2754 | |
2755 | VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { |
2756 | if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) |
2757 | return cast<VarDecl>(Val: MSI->getInstantiatedFrom()); |
2758 | |
2759 | return nullptr; |
2760 | } |
2761 | |
2762 | TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { |
2763 | if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(Val: this)) |
2764 | return Spec->getSpecializationKind(); |
2765 | |
2766 | if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) |
2767 | return MSI->getTemplateSpecializationKind(); |
2768 | |
2769 | return TSK_Undeclared; |
2770 | } |
2771 | |
2772 | TemplateSpecializationKind |
2773 | VarDecl::getTemplateSpecializationKindForInstantiation() const { |
2774 | if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) |
2775 | return MSI->getTemplateSpecializationKind(); |
2776 | |
2777 | if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(Val: this)) |
2778 | return Spec->getSpecializationKind(); |
2779 | |
2780 | return TSK_Undeclared; |
2781 | } |
2782 | |
2783 | SourceLocation VarDecl::getPointOfInstantiation() const { |
2784 | if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(Val: this)) |
2785 | return Spec->getPointOfInstantiation(); |
2786 | |
2787 | if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) |
2788 | return MSI->getPointOfInstantiation(); |
2789 | |
2790 | return SourceLocation(); |
2791 | } |
2792 | |
2793 | VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { |
2794 | return dyn_cast_if_present<VarTemplateDecl *>( |
2795 | getASTContext().getTemplateOrSpecializationInfo(this)); |
2796 | } |
2797 | |
2798 | void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { |
2799 | getASTContext().setTemplateOrSpecializationInfo(this, Template); |
2800 | } |
2801 | |
2802 | bool VarDecl::isKnownToBeDefined() const { |
2803 | const auto &LangOpts = getASTContext().getLangOpts(); |
2804 | // In CUDA mode without relocatable device code, variables of form 'extern |
2805 | // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared |
2806 | // memory pool. These are never undefined variables, even if they appear |
2807 | // inside of an anon namespace or static function. |
2808 | // |
2809 | // With CUDA relocatable device code enabled, these variables don't get |
2810 | // special handling; they're treated like regular extern variables. |
2811 | if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode && |
2812 | hasExternalStorage() && hasAttr<CUDASharedAttr>() && |
2813 | isa<IncompleteArrayType>(getType())) |
2814 | return true; |
2815 | |
2816 | return hasDefinition(); |
2817 | } |
2818 | |
2819 | bool VarDecl::isNoDestroy(const ASTContext &Ctx) const { |
2820 | if (!hasGlobalStorage()) |
2821 | return false; |
2822 | if (hasAttr<NoDestroyAttr>()) |
2823 | return true; |
2824 | if (hasAttr<AlwaysDestroyAttr>()) |
2825 | return false; |
2826 | |
2827 | using RSDKind = LangOptions::RegisterStaticDestructorsKind; |
2828 | RSDKind K = Ctx.getLangOpts().getRegisterStaticDestructors(); |
2829 | return K == RSDKind::None || |
2830 | (K == RSDKind::ThreadLocal && getTLSKind() == TLS_None); |
2831 | } |
2832 | |
2833 | QualType::DestructionKind |
2834 | VarDecl::needsDestruction(const ASTContext &Ctx) const { |
2835 | if (EvaluatedStmt *Eval = getEvaluatedStmt()) |
2836 | if (Eval->HasConstantDestruction) |
2837 | return QualType::DK_none; |
2838 | |
2839 | if (isNoDestroy(Ctx)) |
2840 | return QualType::DK_none; |
2841 | |
2842 | return getType().isDestructedType(); |
2843 | } |
2844 | |
2845 | bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const { |
2846 | assert(hasInit() && "Expect initializer to check for flexible array init"); |
2847 | auto *Ty = getType()->getAs<RecordType>(); |
2848 | if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember()) |
2849 | return false; |
2850 | auto *List = dyn_cast<InitListExpr>(Val: getInit()->IgnoreParens()); |
2851 | if (!List) |
2852 | return false; |
2853 | const Expr *FlexibleInit = List->getInit(Init: List->getNumInits() - 1); |
2854 | auto InitTy = Ctx.getAsConstantArrayType(T: FlexibleInit->getType()); |
2855 | if (!InitTy) |
2856 | return false; |
2857 | return !InitTy->isZeroSize(); |
2858 | } |
2859 | |
2860 | CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const { |
2861 | assert(hasInit() && "Expect initializer to check for flexible array init"); |
2862 | auto *Ty = getType()->getAs<RecordType>(); |
2863 | if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember()) |
2864 | return CharUnits::Zero(); |
2865 | auto *List = dyn_cast<InitListExpr>(Val: getInit()->IgnoreParens()); |
2866 | if (!List || List->getNumInits() == 0) |
2867 | return CharUnits::Zero(); |
2868 | const Expr *FlexibleInit = List->getInit(Init: List->getNumInits() - 1); |
2869 | auto InitTy = Ctx.getAsConstantArrayType(T: FlexibleInit->getType()); |
2870 | if (!InitTy) |
2871 | return CharUnits::Zero(); |
2872 | CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy); |
2873 | const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Ty->getDecl()); |
2874 | CharUnits FlexibleArrayOffset = |
2875 | Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: RL.getFieldCount() - 1)); |
2876 | if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize()) |
2877 | return CharUnits::Zero(); |
2878 | return FlexibleArrayOffset + FlexibleArraySize - RL.getSize(); |
2879 | } |
2880 | |
2881 | MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { |
2882 | if (isStaticDataMember()) |
2883 | // FIXME: Remove ? |
2884 | // return getASTContext().getInstantiatedFromStaticDataMember(this); |
2885 | return dyn_cast_if_present<MemberSpecializationInfo *>( |
2886 | getASTContext().getTemplateOrSpecializationInfo(this)); |
2887 | return nullptr; |
2888 | } |
2889 | |
2890 | void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
2891 | SourceLocation PointOfInstantiation) { |
2892 | assert((isa<VarTemplateSpecializationDecl>(this) || |
2893 | getMemberSpecializationInfo()) && |
2894 | "not a variable or static data member template specialization"); |
2895 | |
2896 | if (VarTemplateSpecializationDecl *Spec = |
2897 | dyn_cast<VarTemplateSpecializationDecl>(Val: this)) { |
2898 | Spec->setSpecializationKind(TSK); |
2899 | if (TSK != TSK_ExplicitSpecialization && |
2900 | PointOfInstantiation.isValid() && |
2901 | Spec->getPointOfInstantiation().isInvalid()) { |
2902 | Spec->setPointOfInstantiation(PointOfInstantiation); |
2903 | if (ASTMutationListener *L = getASTContext().getASTMutationListener()) |
2904 | L->InstantiationRequested(this); |
2905 | } |
2906 | } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { |
2907 | MSI->setTemplateSpecializationKind(TSK); |
2908 | if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && |
2909 | MSI->getPointOfInstantiation().isInvalid()) { |
2910 | MSI->setPointOfInstantiation(PointOfInstantiation); |
2911 | if (ASTMutationListener *L = getASTContext().getASTMutationListener()) |
2912 | L->InstantiationRequested(this); |
2913 | } |
2914 | } |
2915 | } |
2916 | |
2917 | void |
2918 | VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, |
2919 | TemplateSpecializationKind TSK) { |
2920 | assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && |
2921 | "Previous template or instantiation?"); |
2922 | getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); |
2923 | } |
2924 | |
2925 | //===----------------------------------------------------------------------===// |
2926 | // ParmVarDecl Implementation |
2927 | //===----------------------------------------------------------------------===// |
2928 | |
2929 | ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, |
2930 | SourceLocation StartLoc, SourceLocation IdLoc, |
2931 | const IdentifierInfo *Id, QualType T, |
2932 | TypeSourceInfo *TInfo, StorageClass S, |
2933 | Expr *DefArg) { |
2934 | return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, |
2935 | S, DefArg); |
2936 | } |
2937 | |
2938 | QualType ParmVarDecl::getOriginalType() const { |
2939 | TypeSourceInfo *TSI = getTypeSourceInfo(); |
2940 | QualType T = TSI ? TSI->getType() : getType(); |
2941 | if (const auto *DT = dyn_cast<DecayedType>(T)) |
2942 | return DT->getOriginalType(); |
2943 | return T; |
2944 | } |
2945 | |
2946 | ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
2947 | return new (C, ID) |
2948 | ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), |
2949 | nullptr, QualType(), nullptr, SC_None, nullptr); |
2950 | } |
2951 | |
2952 | SourceRange ParmVarDecl::getSourceRange() const { |
2953 | if (!hasInheritedDefaultArg()) { |
2954 | SourceRange ArgRange = getDefaultArgRange(); |
2955 | if (ArgRange.isValid()) |
2956 | return SourceRange(getOuterLocStart(), ArgRange.getEnd()); |
2957 | } |
2958 | |
2959 | // DeclaratorDecl considers the range of postfix types as overlapping with the |
2960 | // declaration name, but this is not the case with parameters in ObjC methods. |
2961 | if (isa<ObjCMethodDecl>(getDeclContext())) |
2962 | return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation()); |
2963 | |
2964 | return DeclaratorDecl::getSourceRange(); |
2965 | } |
2966 | |
2967 | bool ParmVarDecl::isDestroyedInCallee() const { |
2968 | // ns_consumed only affects code generation in ARC |
2969 | if (hasAttr<NSConsumedAttr>()) |
2970 | return getASTContext().getLangOpts().ObjCAutoRefCount; |
2971 | |
2972 | // FIXME: isParamDestroyedInCallee() should probably imply |
2973 | // isDestructedType() |
2974 | const auto *RT = getType()->getAs<RecordType>(); |
2975 | if (RT && RT->getDecl()->isParamDestroyedInCallee() && |
2976 | getType().isDestructedType()) |
2977 | return true; |
2978 | |
2979 | return false; |
2980 | } |
2981 | |
2982 | Expr *ParmVarDecl::getDefaultArg() { |
2983 | assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); |
2984 | assert(!hasUninstantiatedDefaultArg() && |
2985 | "Default argument is not yet instantiated!"); |
2986 | |
2987 | Expr *Arg = getInit(); |
2988 | if (auto *E = dyn_cast_if_present<FullExpr>(Arg)) |
2989 | return E->getSubExpr(); |
2990 | |
2991 | return Arg; |
2992 | } |
2993 | |
2994 | void ParmVarDecl::setDefaultArg(Expr *defarg) { |
2995 | ParmVarDeclBits.DefaultArgKind = DAK_Normal; |
2996 | Init = defarg; |
2997 | } |
2998 | |
2999 | SourceRange ParmVarDecl::getDefaultArgRange() const { |
3000 | switch (ParmVarDeclBits.DefaultArgKind) { |
3001 | case DAK_None: |
3002 | case DAK_Unparsed: |
3003 | // Nothing we can do here. |
3004 | return SourceRange(); |
3005 | |
3006 | case DAK_Uninstantiated: |
3007 | return getUninstantiatedDefaultArg()->getSourceRange(); |
3008 | |
3009 | case DAK_Normal: |
3010 | if (const Expr *E = getInit()) |
3011 | return E->getSourceRange(); |
3012 | |
3013 | // Missing an actual expression, may be invalid. |
3014 | return SourceRange(); |
3015 | } |
3016 | llvm_unreachable("Invalid default argument kind."); |
3017 | } |
3018 | |
3019 | void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) { |
3020 | ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated; |
3021 | Init = arg; |
3022 | } |
3023 | |
3024 | Expr *ParmVarDecl::getUninstantiatedDefaultArg() { |
3025 | assert(hasUninstantiatedDefaultArg() && |
3026 | "Wrong kind of initialization expression!"); |
3027 | return cast_if_present<Expr>(Val: cast<Stmt *>(Val&: Init)); |
3028 | } |
3029 | |
3030 | bool ParmVarDecl::hasDefaultArg() const { |
3031 | // FIXME: We should just return false for DAK_None here once callers are |
3032 | // prepared for the case that we encountered an invalid default argument and |
3033 | // were unable to even build an invalid expression. |
3034 | return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() || |
3035 | !Init.isNull(); |
3036 | } |
3037 | |
3038 | void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { |
3039 | getASTContext().setParameterIndex(this, parameterIndex); |
3040 | ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; |
3041 | } |
3042 | |
3043 | unsigned ParmVarDecl::getParameterIndexLarge() const { |
3044 | return getASTContext().getParameterIndex(this); |
3045 | } |
3046 | |
3047 | //===----------------------------------------------------------------------===// |
3048 | // FunctionDecl Implementation |
3049 | //===----------------------------------------------------------------------===// |
3050 | |
3051 | FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, |
3052 | SourceLocation StartLoc, |
3053 | const DeclarationNameInfo &NameInfo, QualType T, |
3054 | TypeSourceInfo *TInfo, StorageClass S, |
3055 | bool UsesFPIntrin, bool isInlineSpecified, |
3056 | ConstexprSpecKind ConstexprKind, |
3057 | const AssociatedConstraint &TrailingRequiresClause) |
3058 | : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, |
3059 | StartLoc), |
3060 | DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0), |
3061 | EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) { |
3062 | assert(T.isNull() || T->isFunctionType()); |
3063 | FunctionDeclBits.SClass = S; |
3064 | FunctionDeclBits.IsInline = isInlineSpecified; |
3065 | FunctionDeclBits.IsInlineSpecified = isInlineSpecified; |
3066 | FunctionDeclBits.IsVirtualAsWritten = false; |
3067 | FunctionDeclBits.IsPureVirtual = false; |
3068 | FunctionDeclBits.HasInheritedPrototype = false; |
3069 | FunctionDeclBits.HasWrittenPrototype = true; |
3070 | FunctionDeclBits.IsDeleted = false; |
3071 | FunctionDeclBits.IsTrivial = false; |
3072 | FunctionDeclBits.IsTrivialForCall = false; |
3073 | FunctionDeclBits.IsDefaulted = false; |
3074 | FunctionDeclBits.IsExplicitlyDefaulted = false; |
3075 | FunctionDeclBits.HasDefaultedOrDeletedInfo = false; |
3076 | FunctionDeclBits.IsIneligibleOrNotSelected = false; |
3077 | FunctionDeclBits.HasImplicitReturnZero = false; |
3078 | FunctionDeclBits.IsLateTemplateParsed = false; |
3079 | FunctionDeclBits.IsInstantiatedFromMemberTemplate = false; |
3080 | FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind); |
3081 | FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false; |
3082 | FunctionDeclBits.InstantiationIsPending = false; |
3083 | FunctionDeclBits.UsesSEHTry = false; |
3084 | FunctionDeclBits.UsesFPIntrin = UsesFPIntrin; |
3085 | FunctionDeclBits.HasSkippedBody = false; |
3086 | FunctionDeclBits.WillHaveBody = false; |
3087 | FunctionDeclBits.IsMultiVersion = false; |
3088 | FunctionDeclBits.DeductionCandidateKind = |
3089 | static_cast<unsigned char>(DeductionCandidate::Normal); |
3090 | FunctionDeclBits.HasODRHash = false; |
3091 | FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false; |
3092 | |
3093 | if (TrailingRequiresClause) |
3094 | setTrailingRequiresClause(TrailingRequiresClause); |
3095 | } |
3096 | |
3097 | void FunctionDecl::getNameForDiagnostic( |
3098 | raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { |
3099 | NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); |
3100 | const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); |
3101 | if (TemplateArgs) |
3102 | printTemplateArgumentList(OS, Args: TemplateArgs->asArray(), Policy); |
3103 | } |
3104 | |
3105 | bool FunctionDecl::isVariadic() const { |
3106 | if (const auto *FT = getType()->getAs<FunctionProtoType>()) |
3107 | return FT->isVariadic(); |
3108 | return false; |
3109 | } |
3110 | |
3111 | FunctionDecl::DefaultedOrDeletedFunctionInfo * |
3112 | FunctionDecl::DefaultedOrDeletedFunctionInfo::Create( |
3113 | ASTContext &Context, ArrayRef<DeclAccessPair> Lookups, |
3114 | StringLiteral *DeletedMessage) { |
3115 | static constexpr size_t Alignment = |
3116 | std::max(l: {alignof(DefaultedOrDeletedFunctionInfo), |
3117 | alignof(DeclAccessPair), alignof(StringLiteral *)}); |
3118 | size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>( |
3119 | Counts: Lookups.size(), Counts: DeletedMessage != nullptr); |
3120 | |
3121 | DefaultedOrDeletedFunctionInfo *Info = |
3122 | new (Context.Allocate(Size, Align: Alignment)) DefaultedOrDeletedFunctionInfo; |
3123 | Info->NumLookups = Lookups.size(); |
3124 | Info->HasDeletedMessage = DeletedMessage != nullptr; |
3125 | |
3126 | llvm::uninitialized_copy(Src&: Lookups, Dst: Info->getTrailingObjects<DeclAccessPair>()); |
3127 | if (DeletedMessage) |
3128 | *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage; |
3129 | return Info; |
3130 | } |
3131 | |
3132 | void FunctionDecl::setDefaultedOrDeletedInfo( |
3133 | DefaultedOrDeletedFunctionInfo *Info) { |
3134 | assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this"); |
3135 | assert(!Body && "can't replace function body with defaulted function info"); |
3136 | |
3137 | FunctionDeclBits.HasDefaultedOrDeletedInfo = true; |
3138 | DefaultedOrDeletedInfo = Info; |
3139 | } |
3140 | |
3141 | void FunctionDecl::setDeletedAsWritten(bool D, StringLiteral *Message) { |
3142 | FunctionDeclBits.IsDeleted = D; |
3143 | |
3144 | if (Message) { |
3145 | assert(isDeletedAsWritten() && "Function must be deleted"); |
3146 | if (FunctionDeclBits.HasDefaultedOrDeletedInfo) |
3147 | DefaultedOrDeletedInfo->setDeletedMessage(Message); |
3148 | else |
3149 | setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo::Create( |
3150 | Context&: getASTContext(), /*Lookups=*/{}, DeletedMessage: Message)); |
3151 | } |
3152 | } |
3153 | |
3154 | void FunctionDecl::DefaultedOrDeletedFunctionInfo::setDeletedMessage( |
3155 | StringLiteral *Message) { |
3156 | // We should never get here with the DefaultedOrDeletedInfo populated, but |
3157 | // no space allocated for the deleted message, since that would require |
3158 | // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting |
3159 | // an already existing DefaultedOrDeletedFunctionInfo. |
3160 | assert(HasDeletedMessage && |
3161 | "No space to store a delete message in this DefaultedOrDeletedInfo"); |
3162 | *getTrailingObjects<StringLiteral *>() = Message; |
3163 | } |
3164 | |
3165 | FunctionDecl::DefaultedOrDeletedFunctionInfo * |
3166 | FunctionDecl::getDefalutedOrDeletedInfo() const { |
3167 | return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo |
3168 | : nullptr; |
3169 | } |
3170 | |
3171 | bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { |
3172 | for (const auto *I : redecls()) { |
3173 | if (I->doesThisDeclarationHaveABody()) { |
3174 | Definition = I; |
3175 | return true; |
3176 | } |
3177 | } |
3178 | |
3179 | return false; |
3180 | } |
3181 | |
3182 | bool FunctionDecl::hasTrivialBody() const { |
3183 | const Stmt *S = getBody(); |
3184 | if (!S) { |
3185 | // Since we don't have a body for this function, we don't know if it's |
3186 | // trivial or not. |
3187 | return false; |
3188 | } |
3189 | |
3190 | if (isa<CompoundStmt>(Val: S) && cast<CompoundStmt>(Val: S)->body_empty()) |
3191 | return true; |
3192 | return false; |
3193 | } |
3194 | |
3195 | bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const { |
3196 | if (!getFriendObjectKind()) |
3197 | return false; |
3198 | |
3199 | // Check for a friend function instantiated from a friend function |
3200 | // definition in a templated class. |
3201 | if (const FunctionDecl *InstantiatedFrom = |
3202 | getInstantiatedFromMemberFunction()) |
3203 | return InstantiatedFrom->getFriendObjectKind() && |
3204 | InstantiatedFrom->isThisDeclarationADefinition(); |
3205 | |
3206 | // Check for a friend function template instantiated from a friend |
3207 | // function template definition in a templated class. |
3208 | if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) { |
3209 | if (const FunctionTemplateDecl *InstantiatedFrom = |
3210 | Template->getInstantiatedFromMemberTemplate()) |
3211 | return InstantiatedFrom->getFriendObjectKind() && |
3212 | InstantiatedFrom->isThisDeclarationADefinition(); |
3213 | } |
3214 | |
3215 | return false; |
3216 | } |
3217 | |
3218 | bool FunctionDecl::isDefined(const FunctionDecl *&Definition, |
3219 | bool CheckForPendingFriendDefinition) const { |
3220 | for (const FunctionDecl *FD : redecls()) { |
3221 | if (FD->isThisDeclarationADefinition()) { |
3222 | Definition = FD; |
3223 | return true; |
3224 | } |
3225 | |
3226 | // If this is a friend function defined in a class template, it does not |
3227 | // have a body until it is used, nevertheless it is a definition, see |
3228 | // [temp.inst]p2: |
3229 | // |
3230 | // ... for the purpose of determining whether an instantiated redeclaration |
3231 | // is valid according to [basic.def.odr] and [class.mem], a declaration that |
3232 | // corresponds to a definition in the template is considered to be a |
3233 | // definition. |
3234 | // |
3235 | // The following code must produce redefinition error: |
3236 | // |
3237 | // template<typename T> struct C20 { friend void func_20() {} }; |
3238 | // C20<int> c20i; |
3239 | // void func_20() {} |
3240 | // |
3241 | if (CheckForPendingFriendDefinition && |
3242 | FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { |
3243 | Definition = FD; |
3244 | return true; |
3245 | } |
3246 | } |
3247 | |
3248 | return false; |
3249 | } |
3250 | |
3251 | Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { |
3252 | if (!hasBody(Definition)) |
3253 | return nullptr; |
3254 | |
3255 | assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo && |
3256 | "definition should not have a body"); |
3257 | if (Definition->Body) |
3258 | return Definition->Body.get(Source: getASTContext().getExternalSource()); |
3259 | |
3260 | return nullptr; |
3261 | } |
3262 | |
3263 | void FunctionDecl::setBody(Stmt *B) { |
3264 | FunctionDeclBits.HasDefaultedOrDeletedInfo = false; |
3265 | Body = LazyDeclStmtPtr(B); |
3266 | if (B) |
3267 | EndRangeLoc = B->getEndLoc(); |
3268 | } |
3269 | |
3270 | void FunctionDecl::setIsPureVirtual(bool P) { |
3271 | FunctionDeclBits.IsPureVirtual = P; |
3272 | if (P) |
3273 | if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) |
3274 | Parent->markedVirtualFunctionPure(); |
3275 | } |
3276 | |
3277 | template<std::size_t Len> |
3278 | static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { |
3279 | const IdentifierInfo *II = ND->getIdentifier(); |
3280 | return II && II->isStr(Str); |
3281 | } |
3282 | |
3283 | bool FunctionDecl::isImmediateEscalating() const { |
3284 | // C++23 [expr.const]/p17 |
3285 | // An immediate-escalating function is |
3286 | // - the call operator of a lambda that is not declared with the consteval |
3287 | // specifier, |
3288 | if (isLambdaCallOperator(this) && !isConsteval()) |
3289 | return true; |
3290 | // - a defaulted special member function that is not declared with the |
3291 | // consteval specifier, |
3292 | if (isDefaulted() && !isConsteval()) |
3293 | return true; |
3294 | |
3295 | if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: this); |
3296 | CD && CD->isInheritingConstructor()) |
3297 | return CD->getInheritedConstructor().getConstructor(); |
3298 | |
3299 | // - a function that results from the instantiation of a templated entity |
3300 | // defined with the constexpr specifier. |
3301 | TemplatedKind TK = getTemplatedKind(); |
3302 | if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate && |
3303 | isConstexprSpecified()) |
3304 | return true; |
3305 | return false; |
3306 | } |
3307 | |
3308 | bool FunctionDecl::isImmediateFunction() const { |
3309 | // C++23 [expr.const]/p18 |
3310 | // An immediate function is a function or constructor that is |
3311 | // - declared with the consteval specifier |
3312 | if (isConsteval()) |
3313 | return true; |
3314 | // - an immediate-escalating function F whose function body contains an |
3315 | // immediate-escalating expression |
3316 | if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions()) |
3317 | return true; |
3318 | |
3319 | if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: this); |
3320 | CD && CD->isInheritingConstructor()) |
3321 | return CD->getInheritedConstructor() |
3322 | .getConstructor() |
3323 | ->isImmediateFunction(); |
3324 | |
3325 | if (FunctionDecl *P = getTemplateInstantiationPattern(); |
3326 | P && P->isImmediateFunction()) |
3327 | return true; |
3328 | |
3329 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: this); |
3330 | MD && MD->isLambdaStaticInvoker()) |
3331 | return MD->getParent()->getLambdaCallOperator()->isImmediateFunction(); |
3332 | |
3333 | return false; |
3334 | } |
3335 | |
3336 | bool FunctionDecl::isMain() const { |
3337 | return isNamed(this, "main") && !getLangOpts().Freestanding && |
3338 | !getLangOpts().HLSL && |
3339 | (getDeclContext()->getRedeclContext()->isTranslationUnit() || |
3340 | isExternC()); |
3341 | } |
3342 | |
3343 | bool FunctionDecl::isMSVCRTEntryPoint() const { |
3344 | const TranslationUnitDecl *TUnit = |
3345 | dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); |
3346 | if (!TUnit) |
3347 | return false; |
3348 | |
3349 | // Even though we aren't really targeting MSVCRT if we are freestanding, |
3350 | // semantic analysis for these functions remains the same. |
3351 | |
3352 | // MSVCRT entry points only exist on MSVCRT targets. |
3353 | if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT() && |
3354 | !TUnit->getASTContext().getTargetInfo().getTriple().isUEFI()) |
3355 | return false; |
3356 | |
3357 | // Nameless functions like constructors cannot be entry points. |
3358 | if (!getIdentifier()) |
3359 | return false; |
3360 | |
3361 | return llvm::StringSwitch<bool>(getName()) |
3362 | .Cases(S0: "main", // an ANSI console app |
3363 | S1: "wmain", // a Unicode console App |
3364 | S2: "WinMain", // an ANSI GUI app |
3365 | S3: "wWinMain", // a Unicode GUI app |
3366 | S4: "DllMain", // a DLL |
3367 | Value: true) |
3368 | .Default(Value: false); |
3369 | } |
3370 | |
3371 | bool FunctionDecl::isReservedGlobalPlacementOperator() const { |
3372 | if (!getDeclName().isAnyOperatorNewOrDelete()) |
3373 | return false; |
3374 | |
3375 | if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) |
3376 | return false; |
3377 | |
3378 | if (isTypeAwareOperatorNewOrDelete()) |
3379 | return false; |
3380 | |
3381 | const auto *proto = getType()->castAs<FunctionProtoType>(); |
3382 | if (proto->getNumParams() != 2 || proto->isVariadic()) |
3383 | return false; |
3384 | |
3385 | const ASTContext &Context = |
3386 | cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) |
3387 | ->getASTContext(); |
3388 | |
3389 | // The result type and first argument type are constant across all |
3390 | // these operators. The second argument must be exactly void*. |
3391 | return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); |
3392 | } |
3393 | |
3394 | bool FunctionDecl::isUsableAsGlobalAllocationFunctionInConstantEvaluation( |
3395 | UnsignedOrNone *AlignmentParam, bool *IsNothrow) const { |
3396 | if (!getDeclName().isAnyOperatorNewOrDelete()) |
3397 | return false; |
3398 | |
3399 | if (isa<CXXRecordDecl>(getDeclContext())) |
3400 | return false; |
3401 | |
3402 | // This can only fail for an invalid 'operator new' declaration. |
3403 | if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) |
3404 | return false; |
3405 | |
3406 | if (isVariadic()) |
3407 | return false; |
3408 | |
3409 | if (isTypeAwareOperatorNewOrDelete()) { |
3410 | bool IsDelete = getDeclName().isAnyOperatorDelete(); |
3411 | unsigned RequiredParameterCount = |
3412 | IsDelete ? FunctionDecl::RequiredTypeAwareDeleteParameterCount |
3413 | : FunctionDecl::RequiredTypeAwareNewParameterCount; |
3414 | if (AlignmentParam) |
3415 | *AlignmentParam = |
3416 | /* type identity */ 1U + /* address */ IsDelete + /* size */ 1U; |
3417 | if (RequiredParameterCount == getNumParams()) |
3418 | return true; |
3419 | if (getNumParams() > RequiredParameterCount + 1) |
3420 | return false; |
3421 | if (!getParamDecl(i: RequiredParameterCount)->getType()->isNothrowT()) |
3422 | return false; |
3423 | |
3424 | if (IsNothrow) |
3425 | *IsNothrow = true; |
3426 | return true; |
3427 | } |
3428 | |
3429 | const auto *FPT = getType()->castAs<FunctionProtoType>(); |
3430 | if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4) |
3431 | return false; |
3432 | |
3433 | // If this is a single-parameter function, it must be a replaceable global |
3434 | // allocation or deallocation function. |
3435 | if (FPT->getNumParams() == 1) |
3436 | return true; |
3437 | |
3438 | unsigned Params = 1; |
3439 | QualType Ty = FPT->getParamType(Params); |
3440 | const ASTContext &Ctx = getASTContext(); |
3441 | |
3442 | auto Consume = [&] { |
3443 | ++Params; |
3444 | Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType(); |
3445 | }; |
3446 | |
3447 | // In C++14, the next parameter can be a 'std::size_t' for sized delete. |
3448 | bool IsSizedDelete = false; |
3449 | if (Ctx.getLangOpts().SizedDeallocation && |
3450 | getDeclName().isAnyOperatorDelete() && |
3451 | Ctx.hasSameType(T1: Ty, T2: Ctx.getSizeType())) { |
3452 | IsSizedDelete = true; |
3453 | Consume(); |
3454 | } |
3455 | |
3456 | // In C++17, the next parameter can be a 'std::align_val_t' for aligned |
3457 | // new/delete. |
3458 | if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { |
3459 | Consume(); |
3460 | if (AlignmentParam) |
3461 | *AlignmentParam = Params; |
3462 | } |
3463 | |
3464 | // If this is not a sized delete, the next parameter can be a |
3465 | // 'const std::nothrow_t&'. |
3466 | if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) { |
3467 | Ty = Ty->getPointeeType(); |
3468 | if (Ty.getCVRQualifiers() != Qualifiers::Const) |
3469 | return false; |
3470 | if (Ty->isNothrowT()) { |
3471 | if (IsNothrow) |
3472 | *IsNothrow = true; |
3473 | Consume(); |
3474 | } |
3475 | } |
3476 | |
3477 | // Finally, recognize the not yet standard versions of new that take a |
3478 | // hot/cold allocation hint (__hot_cold_t). These are currently supported by |
3479 | // tcmalloc (see |
3480 | // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53). |
3481 | if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) { |
3482 | QualType T = Ty; |
3483 | while (const auto *TD = T->getAs<TypedefType>()) |
3484 | T = TD->getDecl()->getUnderlyingType(); |
3485 | const IdentifierInfo *II = |
3486 | T->castAs<EnumType>()->getDecl()->getIdentifier(); |
3487 | if (II && II->isStr(Str: "__hot_cold_t")) |
3488 | Consume(); |
3489 | } |
3490 | |
3491 | return Params == FPT->getNumParams(); |
3492 | } |
3493 | |
3494 | bool FunctionDecl::isInlineBuiltinDeclaration() const { |
3495 | if (!getBuiltinID()) |
3496 | return false; |
3497 | |
3498 | const FunctionDecl *Definition; |
3499 | if (!hasBody(Definition)) |
3500 | return false; |
3501 | |
3502 | if (!Definition->isInlineSpecified() || |
3503 | !Definition->hasAttr<AlwaysInlineAttr>()) |
3504 | return false; |
3505 | |
3506 | ASTContext &Context = getASTContext(); |
3507 | switch (Context.GetGVALinkageForFunction(FD: Definition)) { |
3508 | case GVA_Internal: |
3509 | case GVA_DiscardableODR: |
3510 | case GVA_StrongODR: |
3511 | return false; |
3512 | case GVA_AvailableExternally: |
3513 | case GVA_StrongExternal: |
3514 | return true; |
3515 | } |
3516 | llvm_unreachable("Unknown GVALinkage"); |
3517 | } |
3518 | |
3519 | bool FunctionDecl::isDestroyingOperatorDelete() const { |
3520 | return getASTContext().isDestroyingOperatorDelete(this); |
3521 | } |
3522 | |
3523 | void FunctionDecl::setIsDestroyingOperatorDelete(bool IsDestroyingDelete) { |
3524 | getASTContext().setIsDestroyingOperatorDelete(this, IsDestroyingDelete); |
3525 | } |
3526 | |
3527 | bool FunctionDecl::isTypeAwareOperatorNewOrDelete() const { |
3528 | return getASTContext().isTypeAwareOperatorNewOrDelete(this); |
3529 | } |
3530 | |
3531 | void FunctionDecl::setIsTypeAwareOperatorNewOrDelete(bool IsTypeAware) { |
3532 | getASTContext().setIsTypeAwareOperatorNewOrDelete(this, IsTypeAware); |
3533 | } |
3534 | |
3535 | LanguageLinkage FunctionDecl::getLanguageLinkage() const { |
3536 | return getDeclLanguageLinkage(D: *this); |
3537 | } |
3538 | |
3539 | bool FunctionDecl::isExternC() const { |
3540 | return isDeclExternC(D: *this); |
3541 | } |
3542 | |
3543 | bool FunctionDecl::isInExternCContext() const { |
3544 | if (DeviceKernelAttr::isOpenCLSpelling(getAttr<DeviceKernelAttr>())) |
3545 | return true; |
3546 | return getLexicalDeclContext()->isExternCContext(); |
3547 | } |
3548 | |
3549 | bool FunctionDecl::isInExternCXXContext() const { |
3550 | return getLexicalDeclContext()->isExternCXXContext(); |
3551 | } |
3552 | |
3553 | bool FunctionDecl::isGlobal() const { |
3554 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: this)) |
3555 | return Method->isStatic(); |
3556 | |
3557 | if (getCanonicalDecl()->getStorageClass() == SC_Static) |
3558 | return false; |
3559 | |
3560 | for (const DeclContext *DC = getDeclContext(); |
3561 | DC->isNamespace(); |
3562 | DC = DC->getParent()) { |
3563 | if (const auto *Namespace = cast<NamespaceDecl>(DC)) { |
3564 | if (!Namespace->getDeclName()) |
3565 | return false; |
3566 | } |
3567 | } |
3568 | |
3569 | return true; |
3570 | } |
3571 | |
3572 | bool FunctionDecl::isNoReturn() const { |
3573 | if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || |
3574 | hasAttr<C11NoReturnAttr>()) |
3575 | return true; |
3576 | |
3577 | if (auto *FnTy = getType()->getAs<FunctionType>()) |
3578 | return FnTy->getNoReturnAttr(); |
3579 | |
3580 | return false; |
3581 | } |
3582 | |
3583 | bool FunctionDecl::isMemberLikeConstrainedFriend() const { |
3584 | // C++20 [temp.friend]p9: |
3585 | // A non-template friend declaration with a requires-clause [or] |
3586 | // a friend function template with a constraint that depends on a template |
3587 | // parameter from an enclosing template [...] does not declare the same |
3588 | // function or function template as a declaration in any other scope. |
3589 | |
3590 | // If this isn't a friend then it's not a member-like constrained friend. |
3591 | if (!getFriendObjectKind()) { |
3592 | return false; |
3593 | } |
3594 | |
3595 | if (!getDescribedFunctionTemplate()) { |
3596 | // If these friends don't have constraints, they aren't constrained, and |
3597 | // thus don't fall under temp.friend p9. Else the simple presence of a |
3598 | // constraint makes them unique. |
3599 | return !getTrailingRequiresClause().isNull(); |
3600 | } |
3601 | |
3602 | return FriendConstraintRefersToEnclosingTemplate(); |
3603 | } |
3604 | |
3605 | MultiVersionKind FunctionDecl::getMultiVersionKind() const { |
3606 | if (hasAttr<TargetAttr>()) |
3607 | return MultiVersionKind::Target; |
3608 | if (hasAttr<TargetVersionAttr>()) |
3609 | return MultiVersionKind::TargetVersion; |
3610 | if (hasAttr<CPUDispatchAttr>()) |
3611 | return MultiVersionKind::CPUDispatch; |
3612 | if (hasAttr<CPUSpecificAttr>()) |
3613 | return MultiVersionKind::CPUSpecific; |
3614 | if (hasAttr<TargetClonesAttr>()) |
3615 | return MultiVersionKind::TargetClones; |
3616 | return MultiVersionKind::None; |
3617 | } |
3618 | |
3619 | bool FunctionDecl::isCPUDispatchMultiVersion() const { |
3620 | return isMultiVersion() && hasAttr<CPUDispatchAttr>(); |
3621 | } |
3622 | |
3623 | bool FunctionDecl::isCPUSpecificMultiVersion() const { |
3624 | return isMultiVersion() && hasAttr<CPUSpecificAttr>(); |
3625 | } |
3626 | |
3627 | bool FunctionDecl::isTargetMultiVersion() const { |
3628 | return isMultiVersion() && |
3629 | (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>()); |
3630 | } |
3631 | |
3632 | bool FunctionDecl::isTargetMultiVersionDefault() const { |
3633 | if (!isMultiVersion()) |
3634 | return false; |
3635 | if (hasAttr<TargetAttr>()) |
3636 | return getAttr<TargetAttr>()->isDefaultVersion(); |
3637 | return hasAttr<TargetVersionAttr>() && |
3638 | getAttr<TargetVersionAttr>()->isDefaultVersion(); |
3639 | } |
3640 | |
3641 | bool FunctionDecl::isTargetClonesMultiVersion() const { |
3642 | return isMultiVersion() && hasAttr<TargetClonesAttr>(); |
3643 | } |
3644 | |
3645 | bool FunctionDecl::isTargetVersionMultiVersion() const { |
3646 | return isMultiVersion() && hasAttr<TargetVersionAttr>(); |
3647 | } |
3648 | |
3649 | void |
3650 | FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { |
3651 | redeclarable_base::setPreviousDecl(PrevDecl); |
3652 | |
3653 | if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { |
3654 | FunctionTemplateDecl *PrevFunTmpl |
3655 | = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; |
3656 | assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); |
3657 | FunTmpl->setPreviousDecl(PrevFunTmpl); |
3658 | } |
3659 | |
3660 | if (PrevDecl && PrevDecl->isInlined()) |
3661 | setImplicitlyInline(true); |
3662 | } |
3663 | |
3664 | FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } |
3665 | |
3666 | /// Returns a value indicating whether this function corresponds to a builtin |
3667 | /// function. |
3668 | /// |
3669 | /// The function corresponds to a built-in function if it is declared at |
3670 | /// translation scope or within an extern "C" block and its name matches with |
3671 | /// the name of a builtin. The returned value will be 0 for functions that do |
3672 | /// not correspond to a builtin, a value of type \c Builtin::ID if in the |
3673 | /// target-independent range \c [1,Builtin::First), or a target-specific builtin |
3674 | /// value. |
3675 | /// |
3676 | /// \param ConsiderWrapperFunctions If true, we should consider wrapper |
3677 | /// functions as their wrapped builtins. This shouldn't be done in general, but |
3678 | /// it's useful in Sema to diagnose calls to wrappers based on their semantics. |
3679 | unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const { |
3680 | unsigned BuiltinID = 0; |
3681 | |
3682 | if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) { |
3683 | BuiltinID = ABAA->getBuiltinName()->getBuiltinID(); |
3684 | } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) { |
3685 | BuiltinID = BAA->getBuiltinName()->getBuiltinID(); |
3686 | } else if (const auto *A = getAttr<BuiltinAttr>()) { |
3687 | BuiltinID = A->getID(); |
3688 | } |
3689 | |
3690 | if (!BuiltinID) |
3691 | return 0; |
3692 | |
3693 | // If the function is marked "overloadable", it has a different mangled name |
3694 | // and is not the C library function. |
3695 | if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() && |
3696 | (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>())) |
3697 | return 0; |
3698 | |
3699 | if (getASTContext().getLangOpts().CPlusPlus && |
3700 | BuiltinID == Builtin::BI__builtin_counted_by_ref) |
3701 | return 0; |
3702 | |
3703 | const ASTContext &Context = getASTContext(); |
3704 | if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) |
3705 | return BuiltinID; |
3706 | |
3707 | // This function has the name of a known C library |
3708 | // function. Determine whether it actually refers to the C library |
3709 | // function or whether it just has the same name. |
3710 | |
3711 | // If this is a static function, it's not a builtin. |
3712 | if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static) |
3713 | return 0; |
3714 | |
3715 | // OpenCL v1.2 s6.9.f - The library functions defined in |
3716 | // the C99 standard headers are not available. |
3717 | if (Context.getLangOpts().OpenCL && |
3718 | Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) |
3719 | return 0; |
3720 | |
3721 | // CUDA does not have device-side standard library. printf and malloc are the |
3722 | // only special cases that are supported by device-side runtime. |
3723 | if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() && |
3724 | !hasAttr<CUDAHostAttr>() && |
3725 | !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) |
3726 | return 0; |
3727 | |
3728 | // As AMDGCN implementation of OpenMP does not have a device-side standard |
3729 | // library, none of the predefined library functions except printf and malloc |
3730 | // should be treated as a builtin i.e. 0 should be returned for them. |
3731 | if (Context.getTargetInfo().getTriple().isAMDGCN() && |
3732 | Context.getLangOpts().OpenMPIsTargetDevice && |
3733 | Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && |
3734 | !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) |
3735 | return 0; |
3736 | |
3737 | return BuiltinID; |
3738 | } |
3739 | |
3740 | /// getNumParams - Return the number of parameters this function must have |
3741 | /// based on its FunctionType. This is the length of the ParamInfo array |
3742 | /// after it has been created. |
3743 | unsigned FunctionDecl::getNumParams() const { |
3744 | const auto *FPT = getType()->getAs<FunctionProtoType>(); |
3745 | return FPT ? FPT->getNumParams() : 0; |
3746 | } |
3747 | |
3748 | void FunctionDecl::setParams(ASTContext &C, |
3749 | ArrayRef<ParmVarDecl *> NewParamInfo) { |
3750 | assert(!ParamInfo && "Already has param info!"); |
3751 | assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); |
3752 | |
3753 | // Zero params -> null pointer. |
3754 | if (!NewParamInfo.empty()) { |
3755 | ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; |
3756 | std::copy(first: NewParamInfo.begin(), last: NewParamInfo.end(), result: ParamInfo); |
3757 | } |
3758 | } |
3759 | |
3760 | /// getMinRequiredArguments - Returns the minimum number of arguments |
3761 | /// needed to call this function. This may be fewer than the number of |
3762 | /// function parameters, if some of the parameters have default |
3763 | /// arguments (in C++) or are parameter packs (C++11). |
3764 | unsigned FunctionDecl::getMinRequiredArguments() const { |
3765 | if (!getASTContext().getLangOpts().CPlusPlus) |
3766 | return getNumParams(); |
3767 | |
3768 | // Note that it is possible for a parameter with no default argument to |
3769 | // follow a parameter with a default argument. |
3770 | unsigned NumRequiredArgs = 0; |
3771 | unsigned MinParamsSoFar = 0; |
3772 | for (auto *Param : parameters()) { |
3773 | if (!Param->isParameterPack()) { |
3774 | ++MinParamsSoFar; |
3775 | if (!Param->hasDefaultArg()) |
3776 | NumRequiredArgs = MinParamsSoFar; |
3777 | } |
3778 | } |
3779 | return NumRequiredArgs; |
3780 | } |
3781 | |
3782 | bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const { |
3783 | return getNumParams() != 0 && getParamDecl(i: 0)->isExplicitObjectParameter(); |
3784 | } |
3785 | |
3786 | unsigned FunctionDecl::getNumNonObjectParams() const { |
3787 | return getNumParams() - |
3788 | static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter()); |
3789 | } |
3790 | |
3791 | unsigned FunctionDecl::getMinRequiredExplicitArguments() const { |
3792 | return getMinRequiredArguments() - |
3793 | static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter()); |
3794 | } |
3795 | |
3796 | bool FunctionDecl::hasOneParamOrDefaultArgs() const { |
3797 | return getNumParams() == 1 || |
3798 | (getNumParams() > 1 && |
3799 | llvm::all_of(Range: llvm::drop_begin(RangeOrContainer: parameters()), |
3800 | P: [](ParmVarDecl *P) { return P->hasDefaultArg(); })); |
3801 | } |
3802 | |
3803 | /// The combination of the extern and inline keywords under MSVC forces |
3804 | /// the function to be required. |
3805 | /// |
3806 | /// Note: This function assumes that we will only get called when isInlined() |
3807 | /// would return true for this FunctionDecl. |
3808 | bool FunctionDecl::isMSExternInline() const { |
3809 | assert(isInlined() && "expected to get called on an inlined function!"); |
3810 | |
3811 | const ASTContext &Context = getASTContext(); |
3812 | if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && |
3813 | !hasAttr<DLLExportAttr>()) |
3814 | return false; |
3815 | |
3816 | for (const FunctionDecl *FD = getMostRecentDecl(); FD; |
3817 | FD = FD->getPreviousDecl()) |
3818 | if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) |
3819 | return true; |
3820 | |
3821 | return false; |
3822 | } |
3823 | |
3824 | static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { |
3825 | if (Redecl->getStorageClass() != SC_Extern) |
3826 | return false; |
3827 | |
3828 | for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; |
3829 | FD = FD->getPreviousDecl()) |
3830 | if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) |
3831 | return false; |
3832 | |
3833 | return true; |
3834 | } |
3835 | |
3836 | static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { |
3837 | // Only consider file-scope declarations in this test. |
3838 | if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) |
3839 | return false; |
3840 | |
3841 | // Only consider explicit declarations; the presence of a builtin for a |
3842 | // libcall shouldn't affect whether a definition is externally visible. |
3843 | if (Redecl->isImplicit()) |
3844 | return false; |
3845 | |
3846 | if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) |
3847 | return true; // Not an inline definition |
3848 | |
3849 | return false; |
3850 | } |
3851 | |
3852 | /// For a function declaration in C or C++, determine whether this |
3853 | /// declaration causes the definition to be externally visible. |
3854 | /// |
3855 | /// For instance, this determines if adding the current declaration to the set |
3856 | /// of redeclarations of the given functions causes |
3857 | /// isInlineDefinitionExternallyVisible to change from false to true. |
3858 | bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { |
3859 | assert(!doesThisDeclarationHaveABody() && |
3860 | "Must have a declaration without a body."); |
3861 | |
3862 | const ASTContext &Context = getASTContext(); |
3863 | |
3864 | if (Context.getLangOpts().MSVCCompat) { |
3865 | const FunctionDecl *Definition; |
3866 | if (hasBody(Definition) && Definition->isInlined() && |
3867 | redeclForcesDefMSVC(Redecl: this)) |
3868 | return true; |
3869 | } |
3870 | |
3871 | if (Context.getLangOpts().CPlusPlus) |
3872 | return false; |
3873 | |
3874 | if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { |
3875 | // With GNU inlining, a declaration with 'inline' but not 'extern', forces |
3876 | // an externally visible definition. |
3877 | // |
3878 | // FIXME: What happens if gnu_inline gets added on after the first |
3879 | // declaration? |
3880 | if (!isInlineSpecified() || getStorageClass() == SC_Extern) |
3881 | return false; |
3882 | |
3883 | const FunctionDecl *Prev = this; |
3884 | bool FoundBody = false; |
3885 | while ((Prev = Prev->getPreviousDecl())) { |
3886 | FoundBody |= Prev->doesThisDeclarationHaveABody(); |
3887 | |
3888 | if (Prev->doesThisDeclarationHaveABody()) { |
3889 | // If it's not the case that both 'inline' and 'extern' are |
3890 | // specified on the definition, then it is always externally visible. |
3891 | if (!Prev->isInlineSpecified() || |
3892 | Prev->getStorageClass() != SC_Extern) |
3893 | return false; |
3894 | } else if (Prev->isInlineSpecified() && |
3895 | Prev->getStorageClass() != SC_Extern) { |
3896 | return false; |
3897 | } |
3898 | } |
3899 | return FoundBody; |
3900 | } |
3901 | |
3902 | // C99 6.7.4p6: |
3903 | // [...] If all of the file scope declarations for a function in a |
3904 | // translation unit include the inline function specifier without extern, |
3905 | // then the definition in that translation unit is an inline definition. |
3906 | if (isInlineSpecified() && getStorageClass() != SC_Extern) |
3907 | return false; |
3908 | const FunctionDecl *Prev = this; |
3909 | bool FoundBody = false; |
3910 | while ((Prev = Prev->getPreviousDecl())) { |
3911 | FoundBody |= Prev->doesThisDeclarationHaveABody(); |
3912 | if (RedeclForcesDefC99(Redecl: Prev)) |
3913 | return false; |
3914 | } |
3915 | return FoundBody; |
3916 | } |
3917 | |
3918 | FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const { |
3919 | const TypeSourceInfo *TSI = getTypeSourceInfo(); |
3920 | |
3921 | if (!TSI) |
3922 | return FunctionTypeLoc(); |
3923 | |
3924 | TypeLoc TL = TSI->getTypeLoc(); |
3925 | FunctionTypeLoc FTL; |
3926 | |
3927 | while (!(FTL = TL.getAs<FunctionTypeLoc>())) { |
3928 | if (const auto PTL = TL.getAs<ParenTypeLoc>()) |
3929 | TL = PTL.getInnerLoc(); |
3930 | else if (const auto ATL = TL.getAs<AttributedTypeLoc>()) |
3931 | TL = ATL.getEquivalentTypeLoc(); |
3932 | else if (const auto MQTL = TL.getAs<MacroQualifiedTypeLoc>()) |
3933 | TL = MQTL.getInnerLoc(); |
3934 | else |
3935 | break; |
3936 | } |
3937 | |
3938 | return FTL; |
3939 | } |
3940 | |
3941 | SourceRange FunctionDecl::getReturnTypeSourceRange() const { |
3942 | FunctionTypeLoc FTL = getFunctionTypeLoc(); |
3943 | if (!FTL) |
3944 | return SourceRange(); |
3945 | |
3946 | // Skip self-referential return types. |
3947 | const SourceManager &SM = getASTContext().getSourceManager(); |
3948 | SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); |
3949 | SourceLocation Boundary = getNameInfo().getBeginLoc(); |
3950 | if (RTRange.isInvalid() || Boundary.isInvalid() || |
3951 | !SM.isBeforeInTranslationUnit(LHS: RTRange.getEnd(), RHS: Boundary)) |
3952 | return SourceRange(); |
3953 | |
3954 | return RTRange; |
3955 | } |
3956 | |
3957 | SourceRange FunctionDecl::getParametersSourceRange() const { |
3958 | unsigned NP = getNumParams(); |
3959 | SourceLocation EllipsisLoc = getEllipsisLoc(); |
3960 | |
3961 | if (NP == 0 && EllipsisLoc.isInvalid()) |
3962 | return SourceRange(); |
3963 | |
3964 | SourceLocation Begin = |
3965 | NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc; |
3966 | SourceLocation End = EllipsisLoc.isValid() |
3967 | ? EllipsisLoc |
3968 | : ParamInfo[NP - 1]->getSourceRange().getEnd(); |
3969 | |
3970 | return SourceRange(Begin, End); |
3971 | } |
3972 | |
3973 | SourceRange FunctionDecl::getExceptionSpecSourceRange() const { |
3974 | FunctionTypeLoc FTL = getFunctionTypeLoc(); |
3975 | return FTL ? FTL.getExceptionSpecRange() : SourceRange(); |
3976 | } |
3977 | |
3978 | /// For an inline function definition in C, or for a gnu_inline function |
3979 | /// in C++, determine whether the definition will be externally visible. |
3980 | /// |
3981 | /// Inline function definitions are always available for inlining optimizations. |
3982 | /// However, depending on the language dialect, declaration specifiers, and |
3983 | /// attributes, the definition of an inline function may or may not be |
3984 | /// "externally" visible to other translation units in the program. |
3985 | /// |
3986 | /// In C99, inline definitions are not externally visible by default. However, |
3987 | /// if even one of the global-scope declarations is marked "extern inline", the |
3988 | /// inline definition becomes externally visible (C99 6.7.4p6). |
3989 | /// |
3990 | /// In GNU89 mode, or if the gnu_inline attribute is attached to the function |
3991 | /// definition, we use the GNU semantics for inline, which are nearly the |
3992 | /// opposite of C99 semantics. In particular, "inline" by itself will create |
3993 | /// an externally visible symbol, but "extern inline" will not create an |
3994 | /// externally visible symbol. |
3995 | bool FunctionDecl::isInlineDefinitionExternallyVisible() const { |
3996 | assert((doesThisDeclarationHaveABody() || willHaveBody() || |
3997 | hasAttr<AliasAttr>()) && |
3998 | "Must be a function definition"); |
3999 | assert(isInlined() && "Function must be inline"); |
4000 | ASTContext &Context = getASTContext(); |
4001 | |
4002 | if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { |
4003 | // Note: If you change the logic here, please change |
4004 | // doesDeclarationForceExternallyVisibleDefinition as well. |
4005 | // |
4006 | // If it's not the case that both 'inline' and 'extern' are |
4007 | // specified on the definition, then this inline definition is |
4008 | // externally visible. |
4009 | if (Context.getLangOpts().CPlusPlus) |
4010 | return false; |
4011 | if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) |
4012 | return true; |
4013 | |
4014 | // If any declaration is 'inline' but not 'extern', then this definition |
4015 | // is externally visible. |
4016 | for (auto *Redecl : redecls()) { |
4017 | if (Redecl->isInlineSpecified() && |
4018 | Redecl->getStorageClass() != SC_Extern) |
4019 | return true; |
4020 | } |
4021 | |
4022 | return false; |
4023 | } |
4024 | |
4025 | // The rest of this function is C-only. |
4026 | assert(!Context.getLangOpts().CPlusPlus && |
4027 | "should not use C inline rules in C++"); |
4028 | |
4029 | // C99 6.7.4p6: |
4030 | // [...] If all of the file scope declarations for a function in a |
4031 | // translation unit include the inline function specifier without extern, |
4032 | // then the definition in that translation unit is an inline definition. |
4033 | for (auto *Redecl : redecls()) { |
4034 | if (RedeclForcesDefC99(Redecl)) |
4035 | return true; |
4036 | } |
4037 | |
4038 | // C99 6.7.4p6: |
4039 | // An inline definition does not provide an external definition for the |
4040 | // function, and does not forbid an external definition in another |
4041 | // translation unit. |
4042 | return false; |
4043 | } |
4044 | |
4045 | /// getOverloadedOperator - Which C++ overloaded operator this |
4046 | /// function represents, if any. |
4047 | OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { |
4048 | if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) |
4049 | return getDeclName().getCXXOverloadedOperator(); |
4050 | return OO_None; |
4051 | } |
4052 | |
4053 | /// getLiteralIdentifier - The literal suffix identifier this function |
4054 | /// represents, if any. |
4055 | const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { |
4056 | if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) |
4057 | return getDeclName().getCXXLiteralIdentifier(); |
4058 | return nullptr; |
4059 | } |
4060 | |
4061 | FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { |
4062 | if (TemplateOrSpecialization.isNull()) |
4063 | return TK_NonTemplate; |
4064 | if (const auto *ND = dyn_cast<NamedDecl *>(Val: TemplateOrSpecialization)) { |
4065 | if (isa<FunctionDecl>(Val: ND)) |
4066 | return TK_DependentNonTemplate; |
4067 | assert(isa<FunctionTemplateDecl>(ND) && |
4068 | "No other valid types in NamedDecl"); |
4069 | return TK_FunctionTemplate; |
4070 | } |
4071 | if (isa<MemberSpecializationInfo *>(Val: TemplateOrSpecialization)) |
4072 | return TK_MemberSpecialization; |
4073 | if (isa<FunctionTemplateSpecializationInfo *>(Val: TemplateOrSpecialization)) |
4074 | return TK_FunctionTemplateSpecialization; |
4075 | if (isa<DependentFunctionTemplateSpecializationInfo *>( |
4076 | Val: TemplateOrSpecialization)) |
4077 | return TK_DependentFunctionTemplateSpecialization; |
4078 | |
4079 | llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); |
4080 | } |
4081 | |
4082 | FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { |
4083 | if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) |
4084 | return cast<FunctionDecl>(Val: Info->getInstantiatedFrom()); |
4085 | |
4086 | return nullptr; |
4087 | } |
4088 | |
4089 | MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { |
4090 | if (auto *MSI = dyn_cast_if_present<MemberSpecializationInfo *>( |
4091 | Val: TemplateOrSpecialization)) |
4092 | return MSI; |
4093 | if (auto *FTSI = dyn_cast_if_present<FunctionTemplateSpecializationInfo *>( |
4094 | Val: TemplateOrSpecialization)) |
4095 | return FTSI->getMemberSpecializationInfo(); |
4096 | return nullptr; |
4097 | } |
4098 | |
4099 | void |
4100 | FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, |
4101 | FunctionDecl *FD, |
4102 | TemplateSpecializationKind TSK) { |
4103 | assert(TemplateOrSpecialization.isNull() && |
4104 | "Member function is already a specialization"); |
4105 | MemberSpecializationInfo *Info |
4106 | = new (C) MemberSpecializationInfo(FD, TSK); |
4107 | TemplateOrSpecialization = Info; |
4108 | } |
4109 | |
4110 | FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const { |
4111 | return dyn_cast_if_present<FunctionTemplateDecl>( |
4112 | Val: dyn_cast_if_present<NamedDecl *>(Val: TemplateOrSpecialization)); |
4113 | } |
4114 | |
4115 | void FunctionDecl::setDescribedFunctionTemplate( |
4116 | FunctionTemplateDecl *Template) { |
4117 | assert(TemplateOrSpecialization.isNull() && |
4118 | "Member function is already a specialization"); |
4119 | TemplateOrSpecialization = Template; |
4120 | } |
4121 | |
4122 | bool FunctionDecl::isFunctionTemplateSpecialization() const { |
4123 | return isa<FunctionTemplateSpecializationInfo *>(Val: TemplateOrSpecialization) || |
4124 | isa<DependentFunctionTemplateSpecializationInfo *>( |
4125 | Val: TemplateOrSpecialization); |
4126 | } |
4127 | |
4128 | void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) { |
4129 | assert(TemplateOrSpecialization.isNull() && |
4130 | "Function is already a specialization"); |
4131 | TemplateOrSpecialization = FD; |
4132 | } |
4133 | |
4134 | FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const { |
4135 | return dyn_cast_if_present<FunctionDecl>( |
4136 | Val: TemplateOrSpecialization.dyn_cast<NamedDecl *>()); |
4137 | } |
4138 | |
4139 | bool FunctionDecl::isImplicitlyInstantiable() const { |
4140 | // If the function is invalid, it can't be implicitly instantiated. |
4141 | if (isInvalidDecl()) |
4142 | return false; |
4143 | |
4144 | switch (getTemplateSpecializationKindForInstantiation()) { |
4145 | case TSK_Undeclared: |
4146 | case TSK_ExplicitInstantiationDefinition: |
4147 | case TSK_ExplicitSpecialization: |
4148 | return false; |
4149 | |
4150 | case TSK_ImplicitInstantiation: |
4151 | return true; |
4152 | |
4153 | case TSK_ExplicitInstantiationDeclaration: |
4154 | // Handled below. |
4155 | break; |
4156 | } |
4157 | |
4158 | // Find the actual template from which we will instantiate. |
4159 | const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); |
4160 | bool HasPattern = false; |
4161 | if (PatternDecl) |
4162 | HasPattern = PatternDecl->hasBody(Definition&: PatternDecl); |
4163 | |
4164 | // C++0x [temp.explicit]p9: |
4165 | // Except for inline functions, other explicit instantiation declarations |
4166 | // have the effect of suppressing the implicit instantiation of the entity |
4167 | // to which they refer. |
4168 | if (!HasPattern || !PatternDecl) |
4169 | return true; |
4170 | |
4171 | return PatternDecl->isInlined(); |
4172 | } |
4173 | |
4174 | bool FunctionDecl::isTemplateInstantiation() const { |
4175 | // FIXME: Remove this, it's not clear what it means. (Which template |
4176 | // specialization kind?) |
4177 | return clang::isTemplateInstantiation(Kind: getTemplateSpecializationKind()); |
4178 | } |
4179 | |
4180 | FunctionDecl * |
4181 | FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const { |
4182 | // If this is a generic lambda call operator specialization, its |
4183 | // instantiation pattern is always its primary template's pattern |
4184 | // even if its primary template was instantiated from another |
4185 | // member template (which happens with nested generic lambdas). |
4186 | // Since a lambda's call operator's body is transformed eagerly, |
4187 | // we don't have to go hunting for a prototype definition template |
4188 | // (i.e. instantiated-from-member-template) to use as an instantiation |
4189 | // pattern. |
4190 | |
4191 | if (isGenericLambdaCallOperatorSpecialization( |
4192 | MD: dyn_cast<CXXMethodDecl>(Val: this))) { |
4193 | assert(getPrimaryTemplate() && "not a generic lambda call operator?"); |
4194 | return getDefinitionOrSelf(D: getPrimaryTemplate()->getTemplatedDecl()); |
4195 | } |
4196 | |
4197 | // Check for a declaration of this function that was instantiated from a |
4198 | // friend definition. |
4199 | const FunctionDecl *FD = nullptr; |
4200 | if (!isDefined(Definition&: FD, /*CheckForPendingFriendDefinition=*/true)) |
4201 | FD = this; |
4202 | |
4203 | if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) { |
4204 | if (ForDefinition && |
4205 | !clang::isTemplateInstantiation(Kind: Info->getTemplateSpecializationKind())) |
4206 | return nullptr; |
4207 | return getDefinitionOrSelf(D: cast<FunctionDecl>(Val: Info->getInstantiatedFrom())); |
4208 | } |
4209 | |
4210 | if (ForDefinition && |
4211 | !clang::isTemplateInstantiation(Kind: getTemplateSpecializationKind())) |
4212 | return nullptr; |
4213 | |
4214 | if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { |
4215 | // If we hit a point where the user provided a specialization of this |
4216 | // template, we're done looking. |
4217 | while (!ForDefinition || !Primary->isMemberSpecialization()) { |
4218 | auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate(); |
4219 | if (!NewPrimary) |
4220 | break; |
4221 | Primary = NewPrimary; |
4222 | } |
4223 | |
4224 | return getDefinitionOrSelf(D: Primary->getTemplatedDecl()); |
4225 | } |
4226 | |
4227 | return nullptr; |
4228 | } |
4229 | |
4230 | FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { |
4231 | if (FunctionTemplateSpecializationInfo *Info = |
4232 | dyn_cast_if_present<FunctionTemplateSpecializationInfo *>( |
4233 | Val: TemplateOrSpecialization)) { |
4234 | return Info->getTemplate(); |
4235 | } |
4236 | return nullptr; |
4237 | } |
4238 | |
4239 | FunctionTemplateSpecializationInfo * |
4240 | FunctionDecl::getTemplateSpecializationInfo() const { |
4241 | return dyn_cast_if_present<FunctionTemplateSpecializationInfo *>( |
4242 | Val: TemplateOrSpecialization); |
4243 | } |
4244 | |
4245 | const TemplateArgumentList * |
4246 | FunctionDecl::getTemplateSpecializationArgs() const { |
4247 | if (FunctionTemplateSpecializationInfo *Info = |
4248 | dyn_cast_if_present<FunctionTemplateSpecializationInfo *>( |
4249 | Val: TemplateOrSpecialization)) { |
4250 | return Info->TemplateArguments; |
4251 | } |
4252 | return nullptr; |
4253 | } |
4254 | |
4255 | const ASTTemplateArgumentListInfo * |
4256 | FunctionDecl::getTemplateSpecializationArgsAsWritten() const { |
4257 | if (FunctionTemplateSpecializationInfo *Info = |
4258 | dyn_cast_if_present<FunctionTemplateSpecializationInfo *>( |
4259 | Val: TemplateOrSpecialization)) { |
4260 | return Info->TemplateArgumentsAsWritten; |
4261 | } |
4262 | if (DependentFunctionTemplateSpecializationInfo *Info = |
4263 | dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>( |
4264 | Val: TemplateOrSpecialization)) { |
4265 | return Info->TemplateArgumentsAsWritten; |
4266 | } |
4267 | return nullptr; |
4268 | } |
4269 | |
4270 | void FunctionDecl::setFunctionTemplateSpecialization( |
4271 | ASTContext &C, FunctionTemplateDecl *Template, |
4272 | TemplateArgumentList *TemplateArgs, void *InsertPos, |
4273 | TemplateSpecializationKind TSK, |
4274 | const TemplateArgumentListInfo *TemplateArgsAsWritten, |
4275 | SourceLocation PointOfInstantiation) { |
4276 | assert((TemplateOrSpecialization.isNull() || |
4277 | isa<MemberSpecializationInfo *>(TemplateOrSpecialization)) && |
4278 | "Member function is already a specialization"); |
4279 | assert(TSK != TSK_Undeclared && |
4280 | "Must specify the type of function template specialization"); |
4281 | assert((TemplateOrSpecialization.isNull() || |
4282 | getFriendObjectKind() != FOK_None || |
4283 | TSK == TSK_ExplicitSpecialization) && |
4284 | "Member specialization must be an explicit specialization"); |
4285 | FunctionTemplateSpecializationInfo *Info = |
4286 | FunctionTemplateSpecializationInfo::Create( |
4287 | C, FD: this, Template, TSK, TemplateArgs, TemplateArgsAsWritten, |
4288 | POI: PointOfInstantiation, |
4289 | MSInfo: dyn_cast_if_present<MemberSpecializationInfo *>( |
4290 | Val&: TemplateOrSpecialization)); |
4291 | TemplateOrSpecialization = Info; |
4292 | Template->addSpecialization(Info, InsertPos); |
4293 | } |
4294 | |
4295 | void FunctionDecl::setDependentTemplateSpecialization( |
4296 | ASTContext &Context, const UnresolvedSetImpl &Templates, |
4297 | const TemplateArgumentListInfo *TemplateArgs) { |
4298 | assert(TemplateOrSpecialization.isNull()); |
4299 | DependentFunctionTemplateSpecializationInfo *Info = |
4300 | DependentFunctionTemplateSpecializationInfo::Create(Context, Candidates: Templates, |
4301 | TemplateArgs); |
4302 | TemplateOrSpecialization = Info; |
4303 | } |
4304 | |
4305 | DependentFunctionTemplateSpecializationInfo * |
4306 | FunctionDecl::getDependentSpecializationInfo() const { |
4307 | return dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>( |
4308 | Val: TemplateOrSpecialization); |
4309 | } |
4310 | |
4311 | DependentFunctionTemplateSpecializationInfo * |
4312 | DependentFunctionTemplateSpecializationInfo::Create( |
4313 | ASTContext &Context, const UnresolvedSetImpl &Candidates, |
4314 | const TemplateArgumentListInfo *TArgs) { |
4315 | const auto *TArgsWritten = |
4316 | TArgs ? ASTTemplateArgumentListInfo::Create(C: Context, List: *TArgs) : nullptr; |
4317 | return new (Context.Allocate( |
4318 | Size: totalSizeToAlloc<FunctionTemplateDecl *>(Counts: Candidates.size()))) |
4319 | DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten); |
4320 | } |
4321 | |
4322 | DependentFunctionTemplateSpecializationInfo:: |
4323 | DependentFunctionTemplateSpecializationInfo( |
4324 | const UnresolvedSetImpl &Candidates, |
4325 | const ASTTemplateArgumentListInfo *TemplateArgsWritten) |
4326 | : NumCandidates(Candidates.size()), |
4327 | TemplateArgumentsAsWritten(TemplateArgsWritten) { |
4328 | std::transform(first: Candidates.begin(), last: Candidates.end(), result: getTrailingObjects(), |
4329 | unary_op: [](NamedDecl *ND) { |
4330 | return cast<FunctionTemplateDecl>(Val: ND->getUnderlyingDecl()); |
4331 | }); |
4332 | } |
4333 | |
4334 | TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { |
4335 | // For a function template specialization, query the specialization |
4336 | // information object. |
4337 | if (FunctionTemplateSpecializationInfo *FTSInfo = |
4338 | dyn_cast_if_present<FunctionTemplateSpecializationInfo *>( |
4339 | Val: TemplateOrSpecialization)) |
4340 | return FTSInfo->getTemplateSpecializationKind(); |
4341 | |
4342 | if (MemberSpecializationInfo *MSInfo = |
4343 | dyn_cast_if_present<MemberSpecializationInfo *>( |
4344 | Val: TemplateOrSpecialization)) |
4345 | return MSInfo->getTemplateSpecializationKind(); |
4346 | |
4347 | // A dependent function template specialization is an explicit specialization, |
4348 | // except when it's a friend declaration. |
4349 | if (isa<DependentFunctionTemplateSpecializationInfo *>( |
4350 | Val: TemplateOrSpecialization) && |
4351 | getFriendObjectKind() == FOK_None) |
4352 | return TSK_ExplicitSpecialization; |
4353 | |
4354 | return TSK_Undeclared; |
4355 | } |
4356 | |
4357 | TemplateSpecializationKind |
4358 | FunctionDecl::getTemplateSpecializationKindForInstantiation() const { |
4359 | // This is the same as getTemplateSpecializationKind(), except that for a |
4360 | // function that is both a function template specialization and a member |
4361 | // specialization, we prefer the member specialization information. Eg: |
4362 | // |
4363 | // template<typename T> struct A { |
4364 | // template<typename U> void f() {} |
4365 | // template<> void f<int>() {} |
4366 | // }; |
4367 | // |
4368 | // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function |
4369 | // template specialization; both getTemplateSpecializationKind() and |
4370 | // getTemplateSpecializationKindForInstantiation() will return |
4371 | // TSK_ExplicitSpecialization. |
4372 | // |
4373 | // For A<int>::f<int>(): |
4374 | // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization |
4375 | // * getTemplateSpecializationKindForInstantiation() will return |
4376 | // TSK_ImplicitInstantiation |
4377 | // |
4378 | // This reflects the facts that A<int>::f<int> is an explicit specialization |
4379 | // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated |
4380 | // from A::f<int> if a definition is needed. |
4381 | if (FunctionTemplateSpecializationInfo *FTSInfo = |
4382 | dyn_cast_if_present<FunctionTemplateSpecializationInfo *>( |
4383 | Val: TemplateOrSpecialization)) { |
4384 | if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo()) |
4385 | return MSInfo->getTemplateSpecializationKind(); |
4386 | return FTSInfo->getTemplateSpecializationKind(); |
4387 | } |
4388 | |
4389 | if (MemberSpecializationInfo *MSInfo = |
4390 | dyn_cast_if_present<MemberSpecializationInfo *>( |
4391 | Val: TemplateOrSpecialization)) |
4392 | return MSInfo->getTemplateSpecializationKind(); |
4393 | |
4394 | if (isa<DependentFunctionTemplateSpecializationInfo *>( |
4395 | Val: TemplateOrSpecialization) && |
4396 | getFriendObjectKind() == FOK_None) |
4397 | return TSK_ExplicitSpecialization; |
4398 | |
4399 | return TSK_Undeclared; |
4400 | } |
4401 | |
4402 | void |
4403 | FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
4404 | SourceLocation PointOfInstantiation) { |
4405 | if (FunctionTemplateSpecializationInfo *FTSInfo = |
4406 | dyn_cast<FunctionTemplateSpecializationInfo *>( |
4407 | Val&: TemplateOrSpecialization)) { |
4408 | FTSInfo->setTemplateSpecializationKind(TSK); |
4409 | if (TSK != TSK_ExplicitSpecialization && |
4410 | PointOfInstantiation.isValid() && |
4411 | FTSInfo->getPointOfInstantiation().isInvalid()) { |
4412 | FTSInfo->setPointOfInstantiation(PointOfInstantiation); |
4413 | if (ASTMutationListener *L = getASTContext().getASTMutationListener()) |
4414 | L->InstantiationRequested(this); |
4415 | } |
4416 | } else if (MemberSpecializationInfo *MSInfo = |
4417 | dyn_cast<MemberSpecializationInfo *>( |
4418 | Val&: TemplateOrSpecialization)) { |
4419 | MSInfo->setTemplateSpecializationKind(TSK); |
4420 | if (TSK != TSK_ExplicitSpecialization && |
4421 | PointOfInstantiation.isValid() && |
4422 | MSInfo->getPointOfInstantiation().isInvalid()) { |
4423 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
4424 | if (ASTMutationListener *L = getASTContext().getASTMutationListener()) |
4425 | L->InstantiationRequested(this); |
4426 | } |
4427 | } else |
4428 | llvm_unreachable("Function cannot have a template specialization kind"); |
4429 | } |
4430 | |
4431 | SourceLocation FunctionDecl::getPointOfInstantiation() const { |
4432 | if (FunctionTemplateSpecializationInfo *FTSInfo |
4433 | = TemplateOrSpecialization.dyn_cast< |
4434 | FunctionTemplateSpecializationInfo*>()) |
4435 | return FTSInfo->getPointOfInstantiation(); |
4436 | if (MemberSpecializationInfo *MSInfo = |
4437 | TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) |
4438 | return MSInfo->getPointOfInstantiation(); |
4439 | |
4440 | return SourceLocation(); |
4441 | } |
4442 | |
4443 | bool FunctionDecl::isOutOfLine() const { |
4444 | if (Decl::isOutOfLine()) |
4445 | return true; |
4446 | |
4447 | // If this function was instantiated from a member function of a |
4448 | // class template, check whether that member function was defined out-of-line. |
4449 | if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { |
4450 | const FunctionDecl *Definition; |
4451 | if (FD->hasBody(Definition)) |
4452 | return Definition->isOutOfLine(); |
4453 | } |
4454 | |
4455 | // If this function was instantiated from a function template, |
4456 | // check whether that function template was defined out-of-line. |
4457 | if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { |
4458 | const FunctionDecl *Definition; |
4459 | if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) |
4460 | return Definition->isOutOfLine(); |
4461 | } |
4462 | |
4463 | return false; |
4464 | } |
4465 | |
4466 | SourceRange FunctionDecl::getSourceRange() const { |
4467 | return SourceRange(getOuterLocStart(), EndRangeLoc); |
4468 | } |
4469 | |
4470 | unsigned FunctionDecl::getMemoryFunctionKind() const { |
4471 | IdentifierInfo *FnInfo = getIdentifier(); |
4472 | |
4473 | if (!FnInfo) |
4474 | return 0; |
4475 | |
4476 | // Builtin handling. |
4477 | switch (getBuiltinID()) { |
4478 | case Builtin::BI__builtin_memset: |
4479 | case Builtin::BI__builtin___memset_chk: |
4480 | case Builtin::BImemset: |
4481 | return Builtin::BImemset; |
4482 | |
4483 | case Builtin::BI__builtin_memcpy: |
4484 | case Builtin::BI__builtin___memcpy_chk: |
4485 | case Builtin::BImemcpy: |
4486 | return Builtin::BImemcpy; |
4487 | |
4488 | case Builtin::BI__builtin_mempcpy: |
4489 | case Builtin::BI__builtin___mempcpy_chk: |
4490 | case Builtin::BImempcpy: |
4491 | return Builtin::BImempcpy; |
4492 | |
4493 | case Builtin::BI__builtin_trivially_relocate: |
4494 | case Builtin::BI__builtin_memmove: |
4495 | case Builtin::BI__builtin___memmove_chk: |
4496 | case Builtin::BImemmove: |
4497 | return Builtin::BImemmove; |
4498 | |
4499 | case Builtin::BIstrlcpy: |
4500 | case Builtin::BI__builtin___strlcpy_chk: |
4501 | return Builtin::BIstrlcpy; |
4502 | |
4503 | case Builtin::BIstrlcat: |
4504 | case Builtin::BI__builtin___strlcat_chk: |
4505 | return Builtin::BIstrlcat; |
4506 | |
4507 | case Builtin::BI__builtin_memcmp: |
4508 | case Builtin::BImemcmp: |
4509 | return Builtin::BImemcmp; |
4510 | |
4511 | case Builtin::BI__builtin_bcmp: |
4512 | case Builtin::BIbcmp: |
4513 | return Builtin::BIbcmp; |
4514 | |
4515 | case Builtin::BI__builtin_strncpy: |
4516 | case Builtin::BI__builtin___strncpy_chk: |
4517 | case Builtin::BIstrncpy: |
4518 | return Builtin::BIstrncpy; |
4519 | |
4520 | case Builtin::BI__builtin_strncmp: |
4521 | case Builtin::BIstrncmp: |
4522 | return Builtin::BIstrncmp; |
4523 | |
4524 | case Builtin::BI__builtin_strncasecmp: |
4525 | case Builtin::BIstrncasecmp: |
4526 | return Builtin::BIstrncasecmp; |
4527 | |
4528 | case Builtin::BI__builtin_strncat: |
4529 | case Builtin::BI__builtin___strncat_chk: |
4530 | case Builtin::BIstrncat: |
4531 | return Builtin::BIstrncat; |
4532 | |
4533 | case Builtin::BI__builtin_strndup: |
4534 | case Builtin::BIstrndup: |
4535 | return Builtin::BIstrndup; |
4536 | |
4537 | case Builtin::BI__builtin_strlen: |
4538 | case Builtin::BIstrlen: |
4539 | return Builtin::BIstrlen; |
4540 | |
4541 | case Builtin::BI__builtin_bzero: |
4542 | case Builtin::BIbzero: |
4543 | return Builtin::BIbzero; |
4544 | |
4545 | case Builtin::BI__builtin_bcopy: |
4546 | case Builtin::BIbcopy: |
4547 | return Builtin::BIbcopy; |
4548 | |
4549 | case Builtin::BIfree: |
4550 | return Builtin::BIfree; |
4551 | |
4552 | default: |
4553 | if (isExternC()) { |
4554 | if (FnInfo->isStr("memset")) |
4555 | return Builtin::BImemset; |
4556 | if (FnInfo->isStr("memcpy")) |
4557 | return Builtin::BImemcpy; |
4558 | if (FnInfo->isStr("mempcpy")) |
4559 | return Builtin::BImempcpy; |
4560 | if (FnInfo->isStr("memmove")) |
4561 | return Builtin::BImemmove; |
4562 | if (FnInfo->isStr("memcmp")) |
4563 | return Builtin::BImemcmp; |
4564 | if (FnInfo->isStr("bcmp")) |
4565 | return Builtin::BIbcmp; |
4566 | if (FnInfo->isStr("strncpy")) |
4567 | return Builtin::BIstrncpy; |
4568 | if (FnInfo->isStr("strncmp")) |
4569 | return Builtin::BIstrncmp; |
4570 | if (FnInfo->isStr("strncasecmp")) |
4571 | return Builtin::BIstrncasecmp; |
4572 | if (FnInfo->isStr("strncat")) |
4573 | return Builtin::BIstrncat; |
4574 | if (FnInfo->isStr("strndup")) |
4575 | return Builtin::BIstrndup; |
4576 | if (FnInfo->isStr("strlen")) |
4577 | return Builtin::BIstrlen; |
4578 | if (FnInfo->isStr("bzero")) |
4579 | return Builtin::BIbzero; |
4580 | if (FnInfo->isStr("bcopy")) |
4581 | return Builtin::BIbcopy; |
4582 | } else if (isInStdNamespace()) { |
4583 | if (FnInfo->isStr("free")) |
4584 | return Builtin::BIfree; |
4585 | } |
4586 | break; |
4587 | } |
4588 | return 0; |
4589 | } |
4590 | |
4591 | unsigned FunctionDecl::getODRHash() const { |
4592 | assert(hasODRHash()); |
4593 | return ODRHash; |
4594 | } |
4595 | |
4596 | unsigned FunctionDecl::getODRHash() { |
4597 | if (hasODRHash()) |
4598 | return ODRHash; |
4599 | |
4600 | if (auto *FT = getInstantiatedFromMemberFunction()) { |
4601 | setHasODRHash(true); |
4602 | ODRHash = FT->getODRHash(); |
4603 | return ODRHash; |
4604 | } |
4605 | |
4606 | class ODRHash Hash; |
4607 | Hash.AddFunctionDecl(Function: this); |
4608 | setHasODRHash(true); |
4609 | ODRHash = Hash.CalculateHash(); |
4610 | return ODRHash; |
4611 | } |
4612 | |
4613 | //===----------------------------------------------------------------------===// |
4614 | // FieldDecl Implementation |
4615 | //===----------------------------------------------------------------------===// |
4616 | |
4617 | FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, |
4618 | SourceLocation StartLoc, SourceLocation IdLoc, |
4619 | const IdentifierInfo *Id, QualType T, |
4620 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
4621 | InClassInitStyle InitStyle) { |
4622 | return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, |
4623 | BW, Mutable, InitStyle); |
4624 | } |
4625 | |
4626 | FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
4627 | return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), |
4628 | SourceLocation(), nullptr, QualType(), nullptr, |
4629 | nullptr, false, ICIS_NoInit); |
4630 | } |
4631 | |
4632 | bool FieldDecl::isAnonymousStructOrUnion() const { |
4633 | if (!isImplicit() || getDeclName()) |
4634 | return false; |
4635 | |
4636 | if (const auto *Record = getType()->getAs<RecordType>()) |
4637 | return Record->getDecl()->isAnonymousStructOrUnion(); |
4638 | |
4639 | return false; |
4640 | } |
4641 | |
4642 | Expr *FieldDecl::getInClassInitializer() const { |
4643 | if (!hasInClassInitializer()) |
4644 | return nullptr; |
4645 | |
4646 | LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init; |
4647 | return cast_if_present<Expr>( |
4648 | InitPtr.isOffset() ? InitPtr.get(Source: getASTContext().getExternalSource()) |
4649 | : InitPtr.get(Source: nullptr)); |
4650 | } |
4651 | |
4652 | void FieldDecl::setInClassInitializer(Expr *NewInit) { |
4653 | setLazyInClassInitializer(LazyDeclStmtPtr(NewInit)); |
4654 | } |
4655 | |
4656 | void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) { |
4657 | assert(hasInClassInitializer() && !getInClassInitializer()); |
4658 | if (BitField) |
4659 | InitAndBitWidth->Init = NewInit; |
4660 | else |
4661 | Init = NewInit; |
4662 | } |
4663 | |
4664 | unsigned FieldDecl::getBitWidthValue() const { |
4665 | assert(isBitField() && "not a bitfield"); |
4666 | assert(isa<ConstantExpr>(getBitWidth())); |
4667 | assert(cast<ConstantExpr>(getBitWidth())->hasAPValueResult()); |
4668 | assert(cast<ConstantExpr>(getBitWidth())->getAPValueResult().isInt()); |
4669 | return cast<ConstantExpr>(Val: getBitWidth()) |
4670 | ->getAPValueResult() |
4671 | .getInt() |
4672 | .getZExtValue(); |
4673 | } |
4674 | |
4675 | bool FieldDecl::isZeroLengthBitField() const { |
4676 | return isUnnamedBitField() && !getBitWidth()->isValueDependent() && |
4677 | getBitWidthValue() == 0; |
4678 | } |
4679 | |
4680 | bool FieldDecl::isZeroSize(const ASTContext &Ctx) const { |
4681 | if (isZeroLengthBitField()) |
4682 | return true; |
4683 | |
4684 | // C++2a [intro.object]p7: |
4685 | // An object has nonzero size if it |
4686 | // -- is not a potentially-overlapping subobject, or |
4687 | if (!hasAttr<NoUniqueAddressAttr>()) |
4688 | return false; |
4689 | |
4690 | // -- is not of class type, or |
4691 | const auto *RT = getType()->getAs<RecordType>(); |
4692 | if (!RT) |
4693 | return false; |
4694 | const RecordDecl *RD = RT->getDecl()->getDefinition(); |
4695 | if (!RD) { |
4696 | assert(isInvalidDecl() && "valid field has incomplete type"); |
4697 | return false; |
4698 | } |
4699 | |
4700 | // -- [has] virtual member functions or virtual base classes, or |
4701 | // -- has subobjects of nonzero size or bit-fields of nonzero length |
4702 | const auto *CXXRD = cast<CXXRecordDecl>(Val: RD); |
4703 | if (!CXXRD->isEmpty()) |
4704 | return false; |
4705 | |
4706 | // Otherwise, [...] the circumstances under which the object has zero size |
4707 | // are implementation-defined. |
4708 | if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft()) |
4709 | return true; |
4710 | |
4711 | // MS ABI: has nonzero size if it is a class type with class type fields, |
4712 | // whether or not they have nonzero size |
4713 | return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) { |
4714 | return Field->getType()->getAs<RecordType>(); |
4715 | }); |
4716 | } |
4717 | |
4718 | bool FieldDecl::isPotentiallyOverlapping() const { |
4719 | return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl(); |
4720 | } |
4721 | |
4722 | void FieldDecl::setCachedFieldIndex() const { |
4723 | assert(this == getCanonicalDecl() && |
4724 | "should be called on the canonical decl"); |
4725 | |
4726 | unsigned Index = 0; |
4727 | const RecordDecl *RD = getParent()->getDefinition(); |
4728 | assert(RD && "requested index for field of struct with no definition"); |
4729 | |
4730 | for (auto *Field : RD->fields()) { |
4731 | Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; |
4732 | assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 && |
4733 | "overflow in field numbering"); |
4734 | ++Index; |
4735 | } |
4736 | |
4737 | assert(CachedFieldIndex && "failed to find field in parent"); |
4738 | } |
4739 | |
4740 | SourceRange FieldDecl::getSourceRange() const { |
4741 | const Expr *FinalExpr = getInClassInitializer(); |
4742 | if (!FinalExpr) |
4743 | FinalExpr = getBitWidth(); |
4744 | if (FinalExpr) |
4745 | return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc()); |
4746 | return DeclaratorDecl::getSourceRange(); |
4747 | } |
4748 | |
4749 | void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { |
4750 | assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && |
4751 | "capturing type in non-lambda or captured record."); |
4752 | assert(StorageKind == ISK_NoInit && !BitField && |
4753 | "bit-field or field with default member initializer cannot capture " |
4754 | "VLA type"); |
4755 | StorageKind = ISK_CapturedVLAType; |
4756 | CapturedVLAType = VLAType; |
4757 | } |
4758 | |
4759 | void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { |
4760 | // Print unnamed members using name of their type. |
4761 | if (isAnonymousStructOrUnion()) { |
4762 | this->getType().print(OS, Policy); |
4763 | return; |
4764 | } |
4765 | // Otherwise, do the normal printing. |
4766 | DeclaratorDecl::printName(OS, Policy); |
4767 | } |
4768 | |
4769 | const FieldDecl *FieldDecl::findCountedByField() const { |
4770 | const auto *CAT = getType()->getAs<CountAttributedType>(); |
4771 | if (!CAT) |
4772 | return nullptr; |
4773 | |
4774 | const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr()); |
4775 | const auto *CountDecl = CountDRE->getDecl(); |
4776 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl)) |
4777 | CountDecl = IFD->getAnonField(); |
4778 | |
4779 | return dyn_cast<FieldDecl>(CountDecl); |
4780 | } |
4781 | |
4782 | //===----------------------------------------------------------------------===// |
4783 | // TagDecl Implementation |
4784 | //===----------------------------------------------------------------------===// |
4785 | |
4786 | TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
4787 | SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, |
4788 | SourceLocation StartL) |
4789 | : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), |
4790 | TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) { |
4791 | assert((DK != Enum || TK == TagTypeKind::Enum) && |
4792 | "EnumDecl not matched with TagTypeKind::Enum"); |
4793 | setPreviousDecl(PrevDecl); |
4794 | setTagKind(TK); |
4795 | setCompleteDefinition(false); |
4796 | setBeingDefined(false); |
4797 | setEmbeddedInDeclarator(false); |
4798 | setFreeStanding(false); |
4799 | setCompleteDefinitionRequired(false); |
4800 | TagDeclBits.IsThisDeclarationADemotedDefinition = false; |
4801 | } |
4802 | |
4803 | SourceLocation TagDecl::getOuterLocStart() const { |
4804 | return getTemplateOrInnerLocStart(decl: this); |
4805 | } |
4806 | |
4807 | SourceRange TagDecl::getSourceRange() const { |
4808 | SourceLocation RBraceLoc = BraceRange.getEnd(); |
4809 | SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); |
4810 | return SourceRange(getOuterLocStart(), E); |
4811 | } |
4812 | |
4813 | TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } |
4814 | |
4815 | void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { |
4816 | TypedefNameDeclOrQualifier = TDD; |
4817 | if (const Type *T = getTypeForDecl()) { |
4818 | (void)T; |
4819 | assert(T->isLinkageValid()); |
4820 | } |
4821 | assert(isLinkageValid()); |
4822 | } |
4823 | |
4824 | void TagDecl::startDefinition() { |
4825 | setBeingDefined(true); |
4826 | |
4827 | if (auto *D = dyn_cast<CXXRecordDecl>(Val: this)) { |
4828 | struct CXXRecordDecl::DefinitionData *Data = |
4829 | new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); |
4830 | for (auto *I : redecls()) |
4831 | cast<CXXRecordDecl>(I)->DefinitionData = Data; |
4832 | } |
4833 | } |
4834 | |
4835 | void TagDecl::completeDefinition() { |
4836 | assert((!isa<CXXRecordDecl>(this) || |
4837 | cast<CXXRecordDecl>(this)->hasDefinition()) && |
4838 | "definition completed but not started"); |
4839 | |
4840 | setCompleteDefinition(true); |
4841 | setBeingDefined(false); |
4842 | |
4843 | if (ASTMutationListener *L = getASTMutationListener()) |
4844 | L->CompletedTagDefinition(D: this); |
4845 | } |
4846 | |
4847 | TagDecl *TagDecl::getDefinition() const { |
4848 | if (isCompleteDefinition()) |
4849 | return const_cast<TagDecl *>(this); |
4850 | |
4851 | // If it's possible for us to have an out-of-date definition, check now. |
4852 | if (mayHaveOutOfDateDef()) { |
4853 | if (IdentifierInfo *II = getIdentifier()) { |
4854 | if (II->isOutOfDate()) { |
4855 | updateOutOfDate(*II); |
4856 | } |
4857 | } |
4858 | } |
4859 | |
4860 | if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: this)) |
4861 | return CXXRD->getDefinition(); |
4862 | |
4863 | for (auto *R : redecls()) |
4864 | if (R->isCompleteDefinition()) |
4865 | return R; |
4866 | |
4867 | return nullptr; |
4868 | } |
4869 | |
4870 | void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { |
4871 | if (QualifierLoc) { |
4872 | // Make sure the extended qualifier info is allocated. |
4873 | if (!hasExtInfo()) |
4874 | TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; |
4875 | // Set qualifier info. |
4876 | getExtInfo()->QualifierLoc = QualifierLoc; |
4877 | } else { |
4878 | // Here Qualifier == 0, i.e., we are removing the qualifier (if any). |
4879 | if (hasExtInfo()) { |
4880 | if (getExtInfo()->NumTemplParamLists == 0) { |
4881 | getASTContext().Deallocate(getExtInfo()); |
4882 | TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; |
4883 | } |
4884 | else |
4885 | getExtInfo()->QualifierLoc = QualifierLoc; |
4886 | } |
4887 | } |
4888 | } |
4889 | |
4890 | void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { |
4891 | DeclarationName Name = getDeclName(); |
4892 | // If the name is supposed to have an identifier but does not have one, then |
4893 | // the tag is anonymous and we should print it differently. |
4894 | if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) { |
4895 | // If the caller wanted to print a qualified name, they've already printed |
4896 | // the scope. And if the caller doesn't want that, the scope information |
4897 | // is already printed as part of the type. |
4898 | PrintingPolicy Copy(Policy); |
4899 | Copy.SuppressScope = true; |
4900 | getASTContext().getTagDeclType(this).print(OS, Copy); |
4901 | return; |
4902 | } |
4903 | // Otherwise, do the normal printing. |
4904 | Name.print(OS, Policy); |
4905 | } |
4906 | |
4907 | void TagDecl::setTemplateParameterListsInfo( |
4908 | ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { |
4909 | assert(!TPLists.empty()); |
4910 | // Make sure the extended decl info is allocated. |
4911 | if (!hasExtInfo()) |
4912 | // Allocate external info struct. |
4913 | TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; |
4914 | // Set the template parameter lists info. |
4915 | getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); |
4916 | } |
4917 | |
4918 | //===----------------------------------------------------------------------===// |
4919 | // EnumDecl Implementation |
4920 | //===----------------------------------------------------------------------===// |
4921 | |
4922 | EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
4923 | SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, |
4924 | bool Scoped, bool ScopedUsingClassTag, bool Fixed) |
4925 | : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) { |
4926 | assert(Scoped || !ScopedUsingClassTag); |
4927 | IntegerType = nullptr; |
4928 | setNumPositiveBits(0); |
4929 | setNumNegativeBits(0); |
4930 | setScoped(Scoped); |
4931 | setScopedUsingClassTag(ScopedUsingClassTag); |
4932 | setFixed(Fixed); |
4933 | setHasODRHash(false); |
4934 | ODRHash = 0; |
4935 | } |
4936 | |
4937 | void EnumDecl::anchor() {} |
4938 | |
4939 | EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, |
4940 | SourceLocation StartLoc, SourceLocation IdLoc, |
4941 | IdentifierInfo *Id, |
4942 | EnumDecl *PrevDecl, bool IsScoped, |
4943 | bool IsScopedUsingClassTag, bool IsFixed) { |
4944 | auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, |
4945 | IsScoped, IsScopedUsingClassTag, IsFixed); |
4946 | Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); |
4947 | C.getTypeDeclType(Enum, PrevDecl); |
4948 | return Enum; |
4949 | } |
4950 | |
4951 | EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
4952 | EnumDecl *Enum = |
4953 | new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), |
4954 | nullptr, nullptr, false, false, false); |
4955 | Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); |
4956 | return Enum; |
4957 | } |
4958 | |
4959 | SourceRange EnumDecl::getIntegerTypeRange() const { |
4960 | if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) |
4961 | return TI->getTypeLoc().getSourceRange(); |
4962 | return SourceRange(); |
4963 | } |
4964 | |
4965 | void EnumDecl::completeDefinition(QualType NewType, |
4966 | QualType NewPromotionType, |
4967 | unsigned NumPositiveBits, |
4968 | unsigned NumNegativeBits) { |
4969 | assert(!isCompleteDefinition() && "Cannot redefine enums!"); |
4970 | if (!IntegerType) |
4971 | IntegerType = NewType.getTypePtr(); |
4972 | PromotionType = NewPromotionType; |
4973 | setNumPositiveBits(NumPositiveBits); |
4974 | setNumNegativeBits(NumNegativeBits); |
4975 | TagDecl::completeDefinition(); |
4976 | } |
4977 | |
4978 | bool EnumDecl::isClosed() const { |
4979 | if (const auto *A = getAttr<EnumExtensibilityAttr>()) |
4980 | return A->getExtensibility() == EnumExtensibilityAttr::Closed; |
4981 | return true; |
4982 | } |
4983 | |
4984 | bool EnumDecl::isClosedFlag() const { |
4985 | return isClosed() && hasAttr<FlagEnumAttr>(); |
4986 | } |
4987 | |
4988 | bool EnumDecl::isClosedNonFlag() const { |
4989 | return isClosed() && !hasAttr<FlagEnumAttr>(); |
4990 | } |
4991 | |
4992 | TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { |
4993 | if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) |
4994 | return MSI->getTemplateSpecializationKind(); |
4995 | |
4996 | return TSK_Undeclared; |
4997 | } |
4998 | |
4999 | void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
5000 | SourceLocation PointOfInstantiation) { |
5001 | MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); |
5002 | assert(MSI && "Not an instantiated member enumeration?"); |
5003 | MSI->setTemplateSpecializationKind(TSK); |
5004 | if (TSK != TSK_ExplicitSpecialization && |
5005 | PointOfInstantiation.isValid() && |
5006 | MSI->getPointOfInstantiation().isInvalid()) |
5007 | MSI->setPointOfInstantiation(PointOfInstantiation); |
5008 | } |
5009 | |
5010 | EnumDecl *EnumDecl::getTemplateInstantiationPattern() const { |
5011 | if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { |
5012 | if (isTemplateInstantiation(Kind: MSInfo->getTemplateSpecializationKind())) { |
5013 | EnumDecl *ED = getInstantiatedFromMemberEnum(); |
5014 | while (auto *NewED = ED->getInstantiatedFromMemberEnum()) |
5015 | ED = NewED; |
5016 | return getDefinitionOrSelf(D: ED); |
5017 | } |
5018 | } |
5019 | |
5020 | assert(!isTemplateInstantiation(getTemplateSpecializationKind()) && |
5021 | "couldn't find pattern for enum instantiation"); |
5022 | return nullptr; |
5023 | } |
5024 | |
5025 | EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { |
5026 | if (SpecializationInfo) |
5027 | return cast<EnumDecl>(Val: SpecializationInfo->getInstantiatedFrom()); |
5028 | |
5029 | return nullptr; |
5030 | } |
5031 | |
5032 | void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, |
5033 | TemplateSpecializationKind TSK) { |
5034 | assert(!SpecializationInfo && "Member enum is already a specialization"); |
5035 | SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); |
5036 | } |
5037 | |
5038 | unsigned EnumDecl::getODRHash() { |
5039 | if (hasODRHash()) |
5040 | return ODRHash; |
5041 | |
5042 | class ODRHash Hash; |
5043 | Hash.AddEnumDecl(Enum: this); |
5044 | setHasODRHash(true); |
5045 | ODRHash = Hash.CalculateHash(); |
5046 | return ODRHash; |
5047 | } |
5048 | |
5049 | SourceRange EnumDecl::getSourceRange() const { |
5050 | auto Res = TagDecl::getSourceRange(); |
5051 | // Set end-point to enum-base, e.g. enum foo : ^bar |
5052 | if (auto *TSI = getIntegerTypeSourceInfo()) { |
5053 | // TagDecl doesn't know about the enum base. |
5054 | if (!getBraceRange().getEnd().isValid()) |
5055 | Res.setEnd(TSI->getTypeLoc().getEndLoc()); |
5056 | } |
5057 | return Res; |
5058 | } |
5059 | |
5060 | void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const { |
5061 | unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType()); |
5062 | unsigned NumNegativeBits = getNumNegativeBits(); |
5063 | unsigned NumPositiveBits = getNumPositiveBits(); |
5064 | |
5065 | if (NumNegativeBits) { |
5066 | unsigned NumBits = std::max(a: NumNegativeBits, b: NumPositiveBits + 1); |
5067 | Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1); |
5068 | Min = -Max; |
5069 | } else { |
5070 | Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits; |
5071 | Min = llvm::APInt::getZero(numBits: Bitwidth); |
5072 | } |
5073 | } |
5074 | |
5075 | //===----------------------------------------------------------------------===// |
5076 | // RecordDecl Implementation |
5077 | //===----------------------------------------------------------------------===// |
5078 | |
5079 | RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, |
5080 | DeclContext *DC, SourceLocation StartLoc, |
5081 | SourceLocation IdLoc, IdentifierInfo *Id, |
5082 | RecordDecl *PrevDecl) |
5083 | : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) { |
5084 | assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!"); |
5085 | setHasFlexibleArrayMember(false); |
5086 | setAnonymousStructOrUnion(false); |
5087 | setHasObjectMember(false); |
5088 | setHasVolatileMember(false); |
5089 | setHasLoadedFieldsFromExternalStorage(false); |
5090 | setNonTrivialToPrimitiveDefaultInitialize(false); |
5091 | setNonTrivialToPrimitiveCopy(false); |
5092 | setNonTrivialToPrimitiveDestroy(false); |
5093 | setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false); |
5094 | setHasNonTrivialToPrimitiveDestructCUnion(false); |
5095 | setHasNonTrivialToPrimitiveCopyCUnion(false); |
5096 | setHasUninitializedExplicitInitFields(false); |
5097 | setParamDestroyedInCallee(false); |
5098 | setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs); |
5099 | setIsRandomized(false); |
5100 | setODRHash(0); |
5101 | } |
5102 | |
5103 | RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
5104 | SourceLocation StartLoc, SourceLocation IdLoc, |
5105 | IdentifierInfo *Id, RecordDecl* PrevDecl) { |
5106 | RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, |
5107 | StartLoc, IdLoc, Id, PrevDecl); |
5108 | R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); |
5109 | |
5110 | C.getTypeDeclType(R, PrevDecl); |
5111 | return R; |
5112 | } |
5113 | |
5114 | RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, |
5115 | GlobalDeclID ID) { |
5116 | RecordDecl *R = new (C, ID) |
5117 | RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(), |
5118 | SourceLocation(), nullptr, nullptr); |
5119 | R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); |
5120 | return R; |
5121 | } |
5122 | |
5123 | bool RecordDecl::isInjectedClassName() const { |
5124 | return isImplicit() && getDeclName() && getDeclContext()->isRecord() && |
5125 | cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); |
5126 | } |
5127 | |
5128 | bool RecordDecl::isLambda() const { |
5129 | if (auto RD = dyn_cast<CXXRecordDecl>(Val: this)) |
5130 | return RD->isLambda(); |
5131 | return false; |
5132 | } |
5133 | |
5134 | bool RecordDecl::isCapturedRecord() const { |
5135 | return hasAttr<CapturedRecordAttr>(); |
5136 | } |
5137 | |
5138 | void RecordDecl::setCapturedRecord() { |
5139 | addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); |
5140 | } |
5141 | |
5142 | bool RecordDecl::isOrContainsUnion() const { |
5143 | if (isUnion()) |
5144 | return true; |
5145 | |
5146 | if (const RecordDecl *Def = getDefinition()) { |
5147 | for (const FieldDecl *FD : Def->fields()) { |
5148 | const RecordType *RT = FD->getType()->getAs<RecordType>(); |
5149 | if (RT && RT->getDecl()->isOrContainsUnion()) |
5150 | return true; |
5151 | } |
5152 | } |
5153 | |
5154 | return false; |
5155 | } |
5156 | |
5157 | RecordDecl::field_iterator RecordDecl::field_begin() const { |
5158 | if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage()) |
5159 | LoadFieldsFromExternalStorage(); |
5160 | // This is necessary for correctness for C++ with modules. |
5161 | // FIXME: Come up with a test case that breaks without definition. |
5162 | if (RecordDecl *D = getDefinition(); D && D != this) |
5163 | return D->field_begin(); |
5164 | return field_iterator(decl_iterator(FirstDecl)); |
5165 | } |
5166 | |
5167 | /// completeDefinition - Notes that the definition of this type is now |
5168 | /// complete. |
5169 | void RecordDecl::completeDefinition() { |
5170 | assert(!isCompleteDefinition() && "Cannot redefine record!"); |
5171 | TagDecl::completeDefinition(); |
5172 | |
5173 | ASTContext &Ctx = getASTContext(); |
5174 | |
5175 | // Layouts are dumped when computed, so if we are dumping for all complete |
5176 | // types, we need to force usage to get types that wouldn't be used elsewhere. |
5177 | // |
5178 | // If the type is dependent, then we can't compute its layout because there |
5179 | // is no way for us to know the size or alignment of a dependent type. Also |
5180 | // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts |
5181 | // on that. |
5182 | if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() && |
5183 | !isInvalidDecl()) |
5184 | (void)Ctx.getASTRecordLayout(D: this); |
5185 | } |
5186 | |
5187 | /// isMsStruct - Get whether or not this record uses ms_struct layout. |
5188 | /// This which can be turned on with an attribute, pragma, or the |
5189 | /// -mms-bitfields command-line option. |
5190 | bool RecordDecl::isMsStruct(const ASTContext &C) const { |
5191 | return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; |
5192 | } |
5193 | |
5194 | void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) { |
5195 | std::tie(args&: FirstDecl, args&: LastDecl) = DeclContext::BuildDeclChain(Decls, FieldsAlreadyLoaded: false); |
5196 | LastDecl->NextInContextAndBits.setPointer(nullptr); |
5197 | setIsRandomized(true); |
5198 | } |
5199 | |
5200 | void RecordDecl::LoadFieldsFromExternalStorage() const { |
5201 | ExternalASTSource *Source = getASTContext().getExternalSource(); |
5202 | assert(hasExternalLexicalStorage() && Source && "No external storage?"); |
5203 | |
5204 | // Notify that we have a RecordDecl doing some initialization. |
5205 | ExternalASTSource::Deserializing TheFields(Source); |
5206 | |
5207 | SmallVector<Decl*, 64> Decls; |
5208 | setHasLoadedFieldsFromExternalStorage(true); |
5209 | Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { |
5210 | return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); |
5211 | }, Decls); |
5212 | |
5213 | #ifndef NDEBUG |
5214 | // Check that all decls we got were FieldDecls. |
5215 | for (unsigned i=0, e=Decls.size(); i != e; ++i) |
5216 | assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); |
5217 | #endif |
5218 | |
5219 | if (Decls.empty()) |
5220 | return; |
5221 | |
5222 | auto [ExternalFirst, ExternalLast] = |
5223 | BuildDeclChain(Decls, |
5224 | /*FieldsAlreadyLoaded=*/false); |
5225 | ExternalLast->NextInContextAndBits.setPointer(FirstDecl); |
5226 | FirstDecl = ExternalFirst; |
5227 | if (!LastDecl) |
5228 | LastDecl = ExternalLast; |
5229 | } |
5230 | |
5231 | bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { |
5232 | ASTContext &Context = getASTContext(); |
5233 | const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & |
5234 | (SanitizerKind::Address | SanitizerKind::KernelAddress); |
5235 | if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) |
5236 | return false; |
5237 | const auto &NoSanitizeList = Context.getNoSanitizeList(); |
5238 | const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: this); |
5239 | // We may be able to relax some of these requirements. |
5240 | int ReasonToReject = -1; |
5241 | if (!CXXRD || CXXRD->isExternCContext()) |
5242 | ReasonToReject = 0; // is not C++. |
5243 | else if (CXXRD->hasAttr<PackedAttr>()) |
5244 | ReasonToReject = 1; // is packed. |
5245 | else if (CXXRD->isUnion()) |
5246 | ReasonToReject = 2; // is a union. |
5247 | else if (CXXRD->isTriviallyCopyable()) |
5248 | ReasonToReject = 3; // is trivially copyable. |
5249 | else if (CXXRD->hasTrivialDestructor()) |
5250 | ReasonToReject = 4; // has trivial destructor. |
5251 | else if (CXXRD->isStandardLayout()) |
5252 | ReasonToReject = 5; // is standard layout. |
5253 | else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(), |
5254 | "field-padding")) |
5255 | ReasonToReject = 6; // is in an excluded file. |
5256 | else if (NoSanitizeList.containsType( |
5257 | EnabledAsanMask, getQualifiedNameAsString(), "field-padding")) |
5258 | ReasonToReject = 7; // The type is excluded. |
5259 | |
5260 | if (EmitRemark) { |
5261 | if (ReasonToReject >= 0) |
5262 | Context.getDiagnostics().Report( |
5263 | getLocation(), |
5264 | diag::remark_sanitize_address_insert_extra_padding_rejected) |
5265 | << getQualifiedNameAsString() << ReasonToReject; |
5266 | else |
5267 | Context.getDiagnostics().Report( |
5268 | getLocation(), |
5269 | diag::remark_sanitize_address_insert_extra_padding_accepted) |
5270 | << getQualifiedNameAsString(); |
5271 | } |
5272 | return ReasonToReject < 0; |
5273 | } |
5274 | |
5275 | const FieldDecl *RecordDecl::findFirstNamedDataMember() const { |
5276 | for (const auto *I : fields()) { |
5277 | if (I->getIdentifier()) |
5278 | return I; |
5279 | |
5280 | if (const auto *RT = I->getType()->getAs<RecordType>()) |
5281 | if (const FieldDecl *NamedDataMember = |
5282 | RT->getDecl()->findFirstNamedDataMember()) |
5283 | return NamedDataMember; |
5284 | } |
5285 | |
5286 | // We didn't find a named data member. |
5287 | return nullptr; |
5288 | } |
5289 | |
5290 | unsigned RecordDecl::getODRHash() { |
5291 | if (hasODRHash()) |
5292 | return RecordDeclBits.ODRHash; |
5293 | |
5294 | // Only calculate hash on first call of getODRHash per record. |
5295 | ODRHash Hash; |
5296 | Hash.AddRecordDecl(Record: this); |
5297 | // For RecordDecl the ODRHash is stored in the remaining |
5298 | // bits of RecordDeclBits, adjust the hash to accommodate. |
5299 | static_assert(sizeof(Hash.CalculateHash()) * CHAR_BIT == 32); |
5300 | setODRHash(Hash.CalculateHash() >> (32 - NumOdrHashBits)); |
5301 | return RecordDeclBits.ODRHash; |
5302 | } |
5303 | |
5304 | //===----------------------------------------------------------------------===// |
5305 | // BlockDecl Implementation |
5306 | //===----------------------------------------------------------------------===// |
5307 | |
5308 | BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc) |
5309 | : Decl(Block, DC, CaretLoc), DeclContext(Block) { |
5310 | setIsVariadic(false); |
5311 | setCapturesCXXThis(false); |
5312 | setBlockMissingReturnType(true); |
5313 | setIsConversionFromLambda(false); |
5314 | setDoesNotEscape(false); |
5315 | setCanAvoidCopyToHeap(false); |
5316 | } |
5317 | |
5318 | void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { |
5319 | assert(!ParamInfo && "Already has param info!"); |
5320 | |
5321 | // Zero params -> null pointer. |
5322 | if (!NewParamInfo.empty()) { |
5323 | NumParams = NewParamInfo.size(); |
5324 | ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; |
5325 | std::copy(first: NewParamInfo.begin(), last: NewParamInfo.end(), result: ParamInfo); |
5326 | } |
5327 | } |
5328 | |
5329 | void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, |
5330 | bool CapturesCXXThis) { |
5331 | this->setCapturesCXXThis(CapturesCXXThis); |
5332 | this->NumCaptures = Captures.size(); |
5333 | |
5334 | if (Captures.empty()) { |
5335 | this->Captures = nullptr; |
5336 | return; |
5337 | } |
5338 | |
5339 | this->Captures = Captures.copy(A&: Context).data(); |
5340 | } |
5341 | |
5342 | bool BlockDecl::capturesVariable(const VarDecl *variable) const { |
5343 | for (const auto &I : captures()) |
5344 | // Only auto vars can be captured, so no redeclaration worries. |
5345 | if (I.getVariable() == variable) |
5346 | return true; |
5347 | |
5348 | return false; |
5349 | } |
5350 | |
5351 | SourceRange BlockDecl::getSourceRange() const { |
5352 | return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation()); |
5353 | } |
5354 | |
5355 | //===----------------------------------------------------------------------===// |
5356 | // Other Decl Allocation/Deallocation Method Implementations |
5357 | //===----------------------------------------------------------------------===// |
5358 | |
5359 | void TranslationUnitDecl::anchor() {} |
5360 | |
5361 | TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { |
5362 | return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); |
5363 | } |
5364 | |
5365 | void TranslationUnitDecl::setAnonymousNamespace(NamespaceDecl *D) { |
5366 | AnonymousNamespace = D; |
5367 | |
5368 | if (ASTMutationListener *Listener = Ctx.getASTMutationListener()) |
5369 | Listener->AddedAnonymousNamespace(TU: this, AnonNamespace: D); |
5370 | } |
5371 | |
5372 | void PragmaCommentDecl::anchor() {} |
5373 | |
5374 | PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, |
5375 | TranslationUnitDecl *DC, |
5376 | SourceLocation CommentLoc, |
5377 | PragmaMSCommentKind CommentKind, |
5378 | StringRef Arg) { |
5379 | PragmaCommentDecl *PCD = |
5380 | new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1)) |
5381 | PragmaCommentDecl(DC, CommentLoc, CommentKind); |
5382 | memcpy(PCD->getTrailingObjects(), Arg.data(), Arg.size()); |
5383 | PCD->getTrailingObjects<char>()[Arg.size()] = '\0'; |
5384 | return PCD; |
5385 | } |
5386 | |
5387 | PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C, |
5388 | GlobalDeclID ID, |
5389 | unsigned ArgSize) { |
5390 | return new (C, ID, additionalSizeToAlloc<char>(Counts: ArgSize + 1)) |
5391 | PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown); |
5392 | } |
5393 | |
5394 | void PragmaDetectMismatchDecl::anchor() {} |
5395 | |
5396 | PragmaDetectMismatchDecl * |
5397 | PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, |
5398 | SourceLocation Loc, StringRef Name, |
5399 | StringRef Value) { |
5400 | size_t ValueStart = Name.size() + 1; |
5401 | PragmaDetectMismatchDecl *PDMD = |
5402 | new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1)) |
5403 | PragmaDetectMismatchDecl(DC, Loc, ValueStart); |
5404 | memcpy(PDMD->getTrailingObjects(), Name.data(), Name.size()); |
5405 | PDMD->getTrailingObjects()[Name.size()] = '\0'; |
5406 | memcpy(PDMD->getTrailingObjects() + ValueStart, Value.data(), Value.size()); |
5407 | PDMD->getTrailingObjects()[ValueStart + Value.size()] = '\0'; |
5408 | return PDMD; |
5409 | } |
5410 | |
5411 | PragmaDetectMismatchDecl * |
5412 | PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID, |
5413 | unsigned NameValueSize) { |
5414 | return new (C, ID, additionalSizeToAlloc<char>(Counts: NameValueSize + 1)) |
5415 | PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0); |
5416 | } |
5417 | |
5418 | void ExternCContextDecl::anchor() {} |
5419 | |
5420 | ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, |
5421 | TranslationUnitDecl *DC) { |
5422 | return new (C, DC) ExternCContextDecl(DC); |
5423 | } |
5424 | |
5425 | void LabelDecl::anchor() {} |
5426 | |
5427 | LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, |
5428 | SourceLocation IdentL, IdentifierInfo *II) { |
5429 | return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); |
5430 | } |
5431 | |
5432 | LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, |
5433 | SourceLocation IdentL, IdentifierInfo *II, |
5434 | SourceLocation GnuLabelL) { |
5435 | assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); |
5436 | return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); |
5437 | } |
5438 | |
5439 | LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
5440 | return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, |
5441 | SourceLocation()); |
5442 | } |
5443 | |
5444 | void LabelDecl::setMSAsmLabel(StringRef Name) { |
5445 | char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; |
5446 | memcpy(dest: Buffer, src: Name.data(), n: Name.size()); |
5447 | Buffer[Name.size()] = '\0'; |
5448 | MSAsmName = Buffer; |
5449 | } |
5450 | |
5451 | void ValueDecl::anchor() {} |
5452 | |
5453 | bool ValueDecl::isWeak() const { |
5454 | auto *MostRecent = getMostRecentDecl(); |
5455 | return MostRecent->hasAttr<WeakAttr>() || |
5456 | MostRecent->hasAttr<WeakRefAttr>() || isWeakImported(); |
5457 | } |
5458 | |
5459 | bool ValueDecl::isInitCapture() const { |
5460 | if (auto *Var = llvm::dyn_cast<VarDecl>(Val: this)) |
5461 | return Var->isInitCapture(); |
5462 | return false; |
5463 | } |
5464 | |
5465 | bool ValueDecl::isParameterPack() const { |
5466 | if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: this)) |
5467 | return NTTP->isParameterPack(); |
5468 | |
5469 | return isa_and_nonnull<PackExpansionType>(Val: getType().getTypePtrOrNull()); |
5470 | } |
5471 | |
5472 | void ImplicitParamDecl::anchor() {} |
5473 | |
5474 | ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, |
5475 | SourceLocation IdLoc, |
5476 | IdentifierInfo *Id, QualType Type, |
5477 | ImplicitParamKind ParamKind) { |
5478 | return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind); |
5479 | } |
5480 | |
5481 | ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type, |
5482 | ImplicitParamKind ParamKind) { |
5483 | return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind); |
5484 | } |
5485 | |
5486 | ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, |
5487 | GlobalDeclID ID) { |
5488 | return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other); |
5489 | } |
5490 | |
5491 | FunctionDecl * |
5492 | FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
5493 | const DeclarationNameInfo &NameInfo, QualType T, |
5494 | TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, |
5495 | bool isInlineSpecified, bool hasWrittenPrototype, |
5496 | ConstexprSpecKind ConstexprKind, |
5497 | const AssociatedConstraint &TrailingRequiresClause) { |
5498 | FunctionDecl *New = new (C, DC) FunctionDecl( |
5499 | Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, |
5500 | isInlineSpecified, ConstexprKind, TrailingRequiresClause); |
5501 | New->setHasWrittenPrototype(hasWrittenPrototype); |
5502 | return New; |
5503 | } |
5504 | |
5505 | FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
5506 | return new (C, ID) FunctionDecl( |
5507 | Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), |
5508 | nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, |
5509 | /*TrailingRequiresClause=*/{}); |
5510 | } |
5511 | |
5512 | bool FunctionDecl::isReferenceableKernel() const { |
5513 | return hasAttr<CUDAGlobalAttr>() || |
5514 | DeviceKernelAttr::isOpenCLSpelling(getAttr<DeviceKernelAttr>()); |
5515 | } |
5516 | |
5517 | BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { |
5518 | return new (C, DC) BlockDecl(DC, L); |
5519 | } |
5520 | |
5521 | BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
5522 | return new (C, ID) BlockDecl(nullptr, SourceLocation()); |
5523 | } |
5524 | |
5525 | OutlinedFunctionDecl::OutlinedFunctionDecl(DeclContext *DC, unsigned NumParams) |
5526 | : Decl(OutlinedFunction, DC, SourceLocation()), |
5527 | DeclContext(OutlinedFunction), NumParams(NumParams), |
5528 | BodyAndNothrow(nullptr, false) {} |
5529 | |
5530 | OutlinedFunctionDecl *OutlinedFunctionDecl::Create(ASTContext &C, |
5531 | DeclContext *DC, |
5532 | unsigned NumParams) { |
5533 | return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams)) |
5534 | OutlinedFunctionDecl(DC, NumParams); |
5535 | } |
5536 | |
5537 | OutlinedFunctionDecl * |
5538 | OutlinedFunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID, |
5539 | unsigned NumParams) { |
5540 | return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams)) |
5541 | OutlinedFunctionDecl(nullptr, NumParams); |
5542 | } |
5543 | |
5544 | Stmt *OutlinedFunctionDecl::getBody() const { |
5545 | return BodyAndNothrow.getPointer(); |
5546 | } |
5547 | void OutlinedFunctionDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } |
5548 | |
5549 | bool OutlinedFunctionDecl::isNothrow() const { return BodyAndNothrow.getInt(); } |
5550 | void OutlinedFunctionDecl::setNothrow(bool Nothrow) { |
5551 | BodyAndNothrow.setInt(Nothrow); |
5552 | } |
5553 | |
5554 | CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams) |
5555 | : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), |
5556 | NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {} |
5557 | |
5558 | CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, |
5559 | unsigned NumParams) { |
5560 | return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams)) |
5561 | CapturedDecl(DC, NumParams); |
5562 | } |
5563 | |
5564 | CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID, |
5565 | unsigned NumParams) { |
5566 | return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams)) |
5567 | CapturedDecl(nullptr, NumParams); |
5568 | } |
5569 | |
5570 | Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); } |
5571 | void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } |
5572 | |
5573 | bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); } |
5574 | void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } |
5575 | |
5576 | EnumConstantDecl::EnumConstantDecl(const ASTContext &C, DeclContext *DC, |
5577 | SourceLocation L, IdentifierInfo *Id, |
5578 | QualType T, Expr *E, const llvm::APSInt &V) |
5579 | : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) { |
5580 | setInitVal(C, V); |
5581 | } |
5582 | |
5583 | EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, |
5584 | SourceLocation L, |
5585 | IdentifierInfo *Id, QualType T, |
5586 | Expr *E, const llvm::APSInt &V) { |
5587 | return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V); |
5588 | } |
5589 | |
5590 | EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C, |
5591 | GlobalDeclID ID) { |
5592 | return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr, |
5593 | QualType(), nullptr, llvm::APSInt()); |
5594 | } |
5595 | |
5596 | void IndirectFieldDecl::anchor() {} |
5597 | |
5598 | IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC, |
5599 | SourceLocation L, DeclarationName N, |
5600 | QualType T, |
5601 | MutableArrayRef<NamedDecl *> CH) |
5602 | : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()), |
5603 | ChainingSize(CH.size()) { |
5604 | // In C++, indirect field declarations conflict with tag declarations in the |
5605 | // same scope, so add them to IDNS_Tag so that tag redeclaration finds them. |
5606 | if (C.getLangOpts().CPlusPlus) |
5607 | IdentifierNamespace |= IDNS_Tag; |
5608 | } |
5609 | |
5610 | IndirectFieldDecl * |
5611 | IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, |
5612 | const IdentifierInfo *Id, QualType T, |
5613 | llvm::MutableArrayRef<NamedDecl *> CH) { |
5614 | return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH); |
5615 | } |
5616 | |
5617 | IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, |
5618 | GlobalDeclID ID) { |
5619 | return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(), |
5620 | DeclarationName(), QualType(), {}); |
5621 | } |
5622 | |
5623 | SourceRange EnumConstantDecl::getSourceRange() const { |
5624 | SourceLocation End = getLocation(); |
5625 | if (Init) |
5626 | End = Init->getEndLoc(); |
5627 | return SourceRange(getLocation(), End); |
5628 | } |
5629 | |
5630 | void TypeDecl::anchor() {} |
5631 | |
5632 | TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, |
5633 | SourceLocation StartLoc, SourceLocation IdLoc, |
5634 | const IdentifierInfo *Id, |
5635 | TypeSourceInfo *TInfo) { |
5636 | return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); |
5637 | } |
5638 | |
5639 | void TypedefNameDecl::anchor() {} |
5640 | |
5641 | TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { |
5642 | if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { |
5643 | auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); |
5644 | auto *ThisTypedef = this; |
5645 | if (AnyRedecl && OwningTypedef) { |
5646 | OwningTypedef = OwningTypedef->getCanonicalDecl(); |
5647 | ThisTypedef = ThisTypedef->getCanonicalDecl(); |
5648 | } |
5649 | if (OwningTypedef == ThisTypedef) |
5650 | return TT->getDecl(); |
5651 | } |
5652 | |
5653 | return nullptr; |
5654 | } |
5655 | |
5656 | bool TypedefNameDecl::isTransparentTagSlow() const { |
5657 | auto determineIsTransparent = [&]() { |
5658 | if (auto *TT = getUnderlyingType()->getAs<TagType>()) { |
5659 | if (auto *TD = TT->getDecl()) { |
5660 | if (TD->getName() != getName()) |
5661 | return false; |
5662 | SourceLocation TTLoc = getLocation(); |
5663 | SourceLocation TDLoc = TD->getLocation(); |
5664 | if (!TTLoc.isMacroID() || !TDLoc.isMacroID()) |
5665 | return false; |
5666 | SourceManager &SM = getASTContext().getSourceManager(); |
5667 | return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc); |
5668 | } |
5669 | } |
5670 | return false; |
5671 | }; |
5672 | |
5673 | bool isTransparent = determineIsTransparent(); |
5674 | MaybeModedTInfo.setInt((isTransparent << 1) | 1); |
5675 | return isTransparent; |
5676 | } |
5677 | |
5678 | TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
5679 | return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), |
5680 | nullptr, nullptr); |
5681 | } |
5682 | |
5683 | TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, |
5684 | SourceLocation StartLoc, |
5685 | SourceLocation IdLoc, |
5686 | const IdentifierInfo *Id, |
5687 | TypeSourceInfo *TInfo) { |
5688 | return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); |
5689 | } |
5690 | |
5691 | TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, |
5692 | GlobalDeclID ID) { |
5693 | return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), |
5694 | SourceLocation(), nullptr, nullptr); |
5695 | } |
5696 | |
5697 | SourceRange TypedefDecl::getSourceRange() const { |
5698 | SourceLocation RangeEnd = getLocation(); |
5699 | if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { |
5700 | if (typeIsPostfix(QT: TInfo->getType())) |
5701 | RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); |
5702 | } |
5703 | return SourceRange(getBeginLoc(), RangeEnd); |
5704 | } |
5705 | |
5706 | SourceRange TypeAliasDecl::getSourceRange() const { |
5707 | SourceLocation RangeEnd = getBeginLoc(); |
5708 | if (TypeSourceInfo *TInfo = getTypeSourceInfo()) |
5709 | RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); |
5710 | return SourceRange(getBeginLoc(), RangeEnd); |
5711 | } |
5712 | |
5713 | void FileScopeAsmDecl::anchor() {} |
5714 | |
5715 | FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, |
5716 | Expr *Str, SourceLocation AsmLoc, |
5717 | SourceLocation RParenLoc) { |
5718 | return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); |
5719 | } |
5720 | |
5721 | FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, |
5722 | GlobalDeclID ID) { |
5723 | return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), |
5724 | SourceLocation()); |
5725 | } |
5726 | |
5727 | std::string FileScopeAsmDecl::getAsmString() const { |
5728 | return GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: getAsmStringExpr()); |
5729 | } |
5730 | |
5731 | void TopLevelStmtDecl::anchor() {} |
5732 | |
5733 | TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) { |
5734 | assert(C.getLangOpts().IncrementalExtensions && |
5735 | "Must be used only in incremental mode"); |
5736 | |
5737 | SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation(); |
5738 | DeclContext *DC = C.getTranslationUnitDecl(); |
5739 | |
5740 | return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement); |
5741 | } |
5742 | |
5743 | TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C, |
5744 | GlobalDeclID ID) { |
5745 | return new (C, ID) |
5746 | TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr); |
5747 | } |
5748 | |
5749 | SourceRange TopLevelStmtDecl::getSourceRange() const { |
5750 | return SourceRange(getLocation(), Statement->getEndLoc()); |
5751 | } |
5752 | |
5753 | void TopLevelStmtDecl::setStmt(Stmt *S) { |
5754 | assert(S); |
5755 | Statement = S; |
5756 | setLocation(Statement->getBeginLoc()); |
5757 | } |
5758 | |
5759 | void EmptyDecl::anchor() {} |
5760 | |
5761 | EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { |
5762 | return new (C, DC) EmptyDecl(DC, L); |
5763 | } |
5764 | |
5765 | EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
5766 | return new (C, ID) EmptyDecl(nullptr, SourceLocation()); |
5767 | } |
5768 | |
5769 | HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer, |
5770 | SourceLocation KwLoc, IdentifierInfo *ID, |
5771 | SourceLocation IDLoc, SourceLocation LBrace) |
5772 | : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)), |
5773 | DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc), |
5774 | IsCBuffer(CBuffer), HasValidPackoffset(false), LayoutStruct(nullptr) {} |
5775 | |
5776 | HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C, |
5777 | DeclContext *LexicalParent, bool CBuffer, |
5778 | SourceLocation KwLoc, IdentifierInfo *ID, |
5779 | SourceLocation IDLoc, |
5780 | SourceLocation LBrace) { |
5781 | // For hlsl like this |
5782 | // cbuffer A { |
5783 | // cbuffer B { |
5784 | // } |
5785 | // } |
5786 | // compiler should treat it as |
5787 | // cbuffer A { |
5788 | // } |
5789 | // cbuffer B { |
5790 | // } |
5791 | // FIXME: support nested buffers if required for back-compat. |
5792 | DeclContext *DC = LexicalParent; |
5793 | HLSLBufferDecl *Result = |
5794 | new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace); |
5795 | return Result; |
5796 | } |
5797 | |
5798 | HLSLBufferDecl * |
5799 | HLSLBufferDecl::CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent, |
5800 | ArrayRef<Decl *> DefaultCBufferDecls) { |
5801 | DeclContext *DC = LexicalParent; |
5802 | IdentifierInfo *II = &C.Idents.get(Name: "$Globals", TokenCode: tok::TokenKind::identifier); |
5803 | HLSLBufferDecl *Result = new (C, DC) HLSLBufferDecl( |
5804 | DC, true, SourceLocation(), II, SourceLocation(), SourceLocation()); |
5805 | Result->setImplicit(true); |
5806 | Result->setDefaultBufferDecls(DefaultCBufferDecls); |
5807 | return Result; |
5808 | } |
5809 | |
5810 | HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C, |
5811 | GlobalDeclID ID) { |
5812 | return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr, |
5813 | SourceLocation(), SourceLocation()); |
5814 | } |
5815 | |
5816 | void HLSLBufferDecl::addLayoutStruct(CXXRecordDecl *LS) { |
5817 | assert(LayoutStruct == nullptr && "layout struct has already been set"); |
5818 | LayoutStruct = LS; |
5819 | addDecl(LS); |
5820 | } |
5821 | |
5822 | void HLSLBufferDecl::setDefaultBufferDecls(ArrayRef<Decl *> Decls) { |
5823 | assert(!Decls.empty()); |
5824 | assert(DefaultBufferDecls.empty() && "default decls are already set"); |
5825 | assert(isImplicit() && |
5826 | "default decls can only be added to the implicit/default constant " |
5827 | "buffer $Globals"); |
5828 | |
5829 | // allocate array for default decls with ASTContext allocator |
5830 | Decl **DeclsArray = new (getASTContext()) Decl *[Decls.size()]; |
5831 | std::copy(first: Decls.begin(), last: Decls.end(), result: DeclsArray); |
5832 | DefaultBufferDecls = ArrayRef<Decl *>(DeclsArray, Decls.size()); |
5833 | } |
5834 | |
5835 | HLSLBufferDecl::buffer_decl_iterator |
5836 | HLSLBufferDecl::buffer_decls_begin() const { |
5837 | return buffer_decl_iterator(llvm::iterator_range(DefaultBufferDecls.begin(), |
5838 | DefaultBufferDecls.end()), |
5839 | decl_range(decls_begin(), decls_end())); |
5840 | } |
5841 | |
5842 | HLSLBufferDecl::buffer_decl_iterator HLSLBufferDecl::buffer_decls_end() const { |
5843 | return buffer_decl_iterator( |
5844 | llvm::iterator_range(DefaultBufferDecls.end(), DefaultBufferDecls.end()), |
5845 | decl_range(decls_end(), decls_end())); |
5846 | } |
5847 | |
5848 | bool HLSLBufferDecl::buffer_decls_empty() { |
5849 | return DefaultBufferDecls.empty() && decls_empty(); |
5850 | } |
5851 | |
5852 | //===----------------------------------------------------------------------===// |
5853 | // HLSLRootSignatureDecl Implementation |
5854 | //===----------------------------------------------------------------------===// |
5855 | |
5856 | HLSLRootSignatureDecl::HLSLRootSignatureDecl(DeclContext *DC, |
5857 | SourceLocation Loc, |
5858 | IdentifierInfo *ID, |
5859 | unsigned NumElems) |
5860 | : NamedDecl(Decl::Kind::HLSLRootSignature, DC, Loc, DeclarationName(ID)), |
5861 | NumElems(NumElems) {} |
5862 | |
5863 | HLSLRootSignatureDecl *HLSLRootSignatureDecl::Create( |
5864 | ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID, |
5865 | ArrayRef<llvm::hlsl::rootsig::RootElement> RootElements) { |
5866 | HLSLRootSignatureDecl *RSDecl = |
5867 | new (C, DC, |
5868 | additionalSizeToAlloc<llvm::hlsl::rootsig::RootElement>( |
5869 | Counts: RootElements.size())) |
5870 | HLSLRootSignatureDecl(DC, Loc, ID, RootElements.size()); |
5871 | auto *StoredElems = RSDecl->getElems(); |
5872 | std::uninitialized_copy(first: RootElements.begin(), last: RootElements.end(), |
5873 | result: StoredElems); |
5874 | return RSDecl; |
5875 | } |
5876 | |
5877 | HLSLRootSignatureDecl * |
5878 | HLSLRootSignatureDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
5879 | HLSLRootSignatureDecl *Result = new (C, ID) |
5880 | HLSLRootSignatureDecl(nullptr, SourceLocation(), nullptr, /*NumElems=*/0); |
5881 | return Result; |
5882 | } |
5883 | |
5884 | //===----------------------------------------------------------------------===// |
5885 | // ImportDecl Implementation |
5886 | //===----------------------------------------------------------------------===// |
5887 | |
5888 | /// Retrieve the number of module identifiers needed to name the given |
5889 | /// module. |
5890 | static unsigned getNumModuleIdentifiers(Module *Mod) { |
5891 | unsigned Result = 1; |
5892 | while (Mod->Parent) { |
5893 | Mod = Mod->Parent; |
5894 | ++Result; |
5895 | } |
5896 | return Result; |
5897 | } |
5898 | |
5899 | ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, |
5900 | Module *Imported, |
5901 | ArrayRef<SourceLocation> IdentifierLocs) |
5902 | : Decl(Import, DC, StartLoc), ImportedModule(Imported), |
5903 | NextLocalImportAndComplete(nullptr, true) { |
5904 | assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); |
5905 | auto *StoredLocs = getTrailingObjects(); |
5906 | llvm::uninitialized_copy(IdentifierLocs, StoredLocs); |
5907 | } |
5908 | |
5909 | ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, |
5910 | Module *Imported, SourceLocation EndLoc) |
5911 | : Decl(Import, DC, StartLoc), ImportedModule(Imported), |
5912 | NextLocalImportAndComplete(nullptr, false) { |
5913 | *getTrailingObjects() = EndLoc; |
5914 | } |
5915 | |
5916 | ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, |
5917 | SourceLocation StartLoc, Module *Imported, |
5918 | ArrayRef<SourceLocation> IdentifierLocs) { |
5919 | return new (C, DC, |
5920 | additionalSizeToAlloc<SourceLocation>(Counts: IdentifierLocs.size())) |
5921 | ImportDecl(DC, StartLoc, Imported, IdentifierLocs); |
5922 | } |
5923 | |
5924 | ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, |
5925 | SourceLocation StartLoc, |
5926 | Module *Imported, |
5927 | SourceLocation EndLoc) { |
5928 | ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(Counts: 1)) |
5929 | ImportDecl(DC, StartLoc, Imported, EndLoc); |
5930 | Import->setImplicit(); |
5931 | return Import; |
5932 | } |
5933 | |
5934 | ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID, |
5935 | unsigned NumLocations) { |
5936 | return new (C, ID, additionalSizeToAlloc<SourceLocation>(Counts: NumLocations)) |
5937 | ImportDecl(EmptyShell()); |
5938 | } |
5939 | |
5940 | ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { |
5941 | if (!isImportComplete()) |
5942 | return {}; |
5943 | |
5944 | return getTrailingObjects(getNumModuleIdentifiers(Mod: getImportedModule())); |
5945 | } |
5946 | |
5947 | SourceRange ImportDecl::getSourceRange() const { |
5948 | if (!isImportComplete()) |
5949 | return SourceRange(getLocation(), *getTrailingObjects()); |
5950 | |
5951 | return SourceRange(getLocation(), getIdentifierLocs().back()); |
5952 | } |
5953 | |
5954 | //===----------------------------------------------------------------------===// |
5955 | // ExportDecl Implementation |
5956 | //===----------------------------------------------------------------------===// |
5957 | |
5958 | void ExportDecl::anchor() {} |
5959 | |
5960 | ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC, |
5961 | SourceLocation ExportLoc) { |
5962 | return new (C, DC) ExportDecl(DC, ExportLoc); |
5963 | } |
5964 | |
5965 | ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { |
5966 | return new (C, ID) ExportDecl(nullptr, SourceLocation()); |
5967 | } |
5968 | |
5969 | bool clang::IsArmStreamingFunction(const FunctionDecl *FD, |
5970 | bool IncludeLocallyStreaming) { |
5971 | if (IncludeLocallyStreaming) |
5972 | if (FD->hasAttr<ArmLocallyStreamingAttr>()) |
5973 | return true; |
5974 | |
5975 | if (const Type *Ty = FD->getType().getTypePtrOrNull()) |
5976 | if (const auto *FPT = Ty->getAs<FunctionProtoType>()) |
5977 | if (FPT->getAArch64SMEAttributes() & |
5978 | FunctionType::SME_PStateSMEnabledMask) |
5979 | return true; |
5980 | |
5981 | return false; |
5982 | } |
5983 | |
5984 | bool clang::hasArmZAState(const FunctionDecl *FD) { |
5985 | const auto *T = FD->getType()->getAs<FunctionProtoType>(); |
5986 | return (T && FunctionType::getArmZAState(T->getAArch64SMEAttributes()) != |
5987 | FunctionType::ARM_None) || |
5988 | (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA()); |
5989 | } |
5990 | |
5991 | bool clang::hasArmZT0State(const FunctionDecl *FD) { |
5992 | const auto *T = FD->getType()->getAs<FunctionProtoType>(); |
5993 | return (T && FunctionType::getArmZT0State(T->getAArch64SMEAttributes()) != |
5994 | FunctionType::ARM_None) || |
5995 | (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0()); |
5996 | } |
5997 |
Definitions
- getPrimaryMergedDecl
- isOutOfLine
- TranslationUnitDecl
- hasExplicitVisibilityAlready
- withExplicitVisibilityAlready
- getExplicitVisibility
- usesTypeVisibility
- isExplicitMemberSpecialization
- isExplicitMemberSpecialization
- getVisibilityFromAttr
- getVisibilityOf
- getLVForType
- getLVForTemplateParameterList
- getOutermostFuncOrBlockContext
- getLVForTemplateArgumentList
- getLVForTemplateArgumentList
- shouldConsiderTemplateVisibility
- mergeTemplateLV
- hasDirectVisibilityAttribute
- shouldConsiderTemplateVisibility
- mergeTemplateLV
- shouldConsiderTemplateVisibility
- mergeTemplateLV
- useInlineVisibilityHidden
- isFirstInExternCContext
- isSingleLineLanguageLinkage
- getExternalLinkageFor
- getStorageClass
- getLVForNamespaceScopeDecl
- getLVForClassMember
- anchor
- isLinkageValid
- isPlaceholderVar
- isReserved
- getObjCFStringFormattingFamily
- getLinkageInternal
- isExportedFromModuleInterfaceUnit
- getFormalLinkage
- getLinkageAndVisibility
- getExplicitVisibilityAux
- getExplicitVisibility
- getLVForClosure
- getLVForLocalDecl
- computeLVForDecl
- getLVForDecl
- getDeclLinkageAndVisibility
- getOwningModuleForLinkage
- printName
- printName
- getQualifiedNameAsString
- printQualifiedName
- printQualifiedName
- printNestedNameSpecifier
- printNestedNameSpecifier
- getNameForDiagnostic
- isRedeclarableImpl
- isRedeclarableImpl
- isRedeclarable
- declarationReplaces
- hasLinkage
- getUnderlyingDeclImpl
- isCXXInstanceMember
- getTemplateOrInnerLocStart
- getTypeSpecStartLoc
- getTypeSpecEndLoc
- setQualifierInfo
- setTrailingRequiresClause
- setTemplateParameterListsInfo
- getOuterLocStart
- typeIsPostfix
- getSourceRange
- setTemplateParameterListsInfo
- getStorageClassSpecifierString
- VarDecl
- Create
- CreateDeserialized
- setStorageClass
- getTLSKind
- getSourceRange
- getDeclLanguageLinkage
- isDeclExternC
- getLanguageLinkage
- isExternC
- isInExternCContext
- isInExternCXXContext
- getCanonicalDecl
- isThisDeclarationADefinition
- getActingDefinition
- getDefinition
- hasDefinition
- getAnyInitializer
- hasInit
- getInit
- getInitAddress
- getInitializingDeclaration
- isOutOfLine
- setInit
- mightBeUsableInConstantExpressions
- isUsableInConstantExpressions
- ensureEvaluatedStmt
- getEvaluatedStmt
- evaluateValue
- evaluateValueImpl
- getEvaluatedValue
- hasICEInitializer
- hasConstantInitialization
- checkForConstantInitialization
- getDefinitionOrSelf
- isEscapingByref
- isNonEscapingByref
- hasDependentAlignment
- getTemplateInstantiationPattern
- getInstantiatedFromStaticDataMember
- getTemplateSpecializationKind
- getTemplateSpecializationKindForInstantiation
- getPointOfInstantiation
- getDescribedVarTemplate
- setDescribedVarTemplate
- isKnownToBeDefined
- isNoDestroy
- needsDestruction
- hasFlexibleArrayInit
- getFlexibleArrayInitChars
- getMemberSpecializationInfo
- setTemplateSpecializationKind
- setInstantiationOfStaticDataMember
- Create
- getOriginalType
- CreateDeserialized
- getSourceRange
- isDestroyedInCallee
- getDefaultArg
- setDefaultArg
- getDefaultArgRange
- setUninstantiatedDefaultArg
- getUninstantiatedDefaultArg
- hasDefaultArg
- setParameterIndexLarge
- getParameterIndexLarge
- FunctionDecl
- getNameForDiagnostic
- isVariadic
- Create
- setDefaultedOrDeletedInfo
- setDeletedAsWritten
- setDeletedMessage
- getDefalutedOrDeletedInfo
- hasBody
- hasTrivialBody
- isThisDeclarationInstantiatedFromAFriendDefinition
- isDefined
- getBody
- setBody
- setIsPureVirtual
- isNamed
- isImmediateEscalating
- isImmediateFunction
- isMain
- isMSVCRTEntryPoint
- isReservedGlobalPlacementOperator
- isUsableAsGlobalAllocationFunctionInConstantEvaluation
- isInlineBuiltinDeclaration
- isDestroyingOperatorDelete
- setIsDestroyingOperatorDelete
- isTypeAwareOperatorNewOrDelete
- setIsTypeAwareOperatorNewOrDelete
- getLanguageLinkage
- isExternC
- isInExternCContext
- isInExternCXXContext
- isGlobal
- isNoReturn
- isMemberLikeConstrainedFriend
- getMultiVersionKind
- isCPUDispatchMultiVersion
- isCPUSpecificMultiVersion
- isTargetMultiVersion
- isTargetMultiVersionDefault
- isTargetClonesMultiVersion
- isTargetVersionMultiVersion
- setPreviousDeclaration
- getCanonicalDecl
- getBuiltinID
- getNumParams
- setParams
- getMinRequiredArguments
- hasCXXExplicitFunctionObjectParameter
- getNumNonObjectParams
- getMinRequiredExplicitArguments
- hasOneParamOrDefaultArgs
- isMSExternInline
- redeclForcesDefMSVC
- RedeclForcesDefC99
- doesDeclarationForceExternallyVisibleDefinition
- getFunctionTypeLoc
- getReturnTypeSourceRange
- getParametersSourceRange
- getExceptionSpecSourceRange
- isInlineDefinitionExternallyVisible
- getOverloadedOperator
- getLiteralIdentifier
- getTemplatedKind
- getInstantiatedFromMemberFunction
- getMemberSpecializationInfo
- setInstantiationOfMemberFunction
- getDescribedFunctionTemplate
- setDescribedFunctionTemplate
- isFunctionTemplateSpecialization
- setInstantiatedFromDecl
- getInstantiatedFromDecl
- isImplicitlyInstantiable
- isTemplateInstantiation
- getTemplateInstantiationPattern
- getPrimaryTemplate
- getTemplateSpecializationInfo
- getTemplateSpecializationArgs
- getTemplateSpecializationArgsAsWritten
- setFunctionTemplateSpecialization
- setDependentTemplateSpecialization
- getDependentSpecializationInfo
- Create
- DependentFunctionTemplateSpecializationInfo
- getTemplateSpecializationKind
- getTemplateSpecializationKindForInstantiation
- setTemplateSpecializationKind
- getPointOfInstantiation
- isOutOfLine
- getSourceRange
- getMemoryFunctionKind
- getODRHash
- getODRHash
- Create
- CreateDeserialized
- isAnonymousStructOrUnion
- getInClassInitializer
- setInClassInitializer
- setLazyInClassInitializer
- getBitWidthValue
- isZeroLengthBitField
- isZeroSize
- isPotentiallyOverlapping
- setCachedFieldIndex
- getSourceRange
- setCapturedVLAType
- printName
- findCountedByField
- TagDecl
- getOuterLocStart
- getSourceRange
- getCanonicalDecl
- setTypedefNameForAnonDecl
- startDefinition
- completeDefinition
- getDefinition
- setQualifierInfo
- printName
- setTemplateParameterListsInfo
- EnumDecl
- anchor
- Create
- CreateDeserialized
- getIntegerTypeRange
- completeDefinition
- isClosed
- isClosedFlag
- isClosedNonFlag
- getTemplateSpecializationKind
- setTemplateSpecializationKind
- getTemplateInstantiationPattern
- getInstantiatedFromMemberEnum
- setInstantiationOfMemberEnum
- getODRHash
- getSourceRange
- getValueRange
- RecordDecl
- Create
- CreateDeserialized
- isInjectedClassName
- isLambda
- isCapturedRecord
- setCapturedRecord
- isOrContainsUnion
- field_begin
- completeDefinition
- isMsStruct
- reorderDecls
- LoadFieldsFromExternalStorage
- mayInsertExtraPadding
- findFirstNamedDataMember
- getODRHash
- BlockDecl
- setParams
- setCaptures
- capturesVariable
- getSourceRange
- anchor
- Create
- setAnonymousNamespace
- anchor
- Create
- CreateDeserialized
- anchor
- Create
- CreateDeserialized
- anchor
- Create
- anchor
- Create
- Create
- CreateDeserialized
- setMSAsmLabel
- anchor
- isWeak
- isInitCapture
- isParameterPack
- anchor
- Create
- Create
- CreateDeserialized
- Create
- CreateDeserialized
- isReferenceableKernel
- Create
- CreateDeserialized
- OutlinedFunctionDecl
- Create
- CreateDeserialized
- getBody
- setBody
- isNothrow
- setNothrow
- CapturedDecl
- Create
- CreateDeserialized
- getBody
- setBody
- isNothrow
- setNothrow
- EnumConstantDecl
- Create
- CreateDeserialized
- anchor
- IndirectFieldDecl
- Create
- CreateDeserialized
- getSourceRange
- anchor
- Create
- anchor
- getAnonDeclWithTypedefName
- isTransparentTagSlow
- CreateDeserialized
- Create
- CreateDeserialized
- getSourceRange
- getSourceRange
- anchor
- Create
- CreateDeserialized
- getAsmString
- anchor
- Create
- CreateDeserialized
- getSourceRange
- setStmt
- anchor
- Create
- CreateDeserialized
- HLSLBufferDecl
- Create
- CreateDefaultCBuffer
- CreateDeserialized
- addLayoutStruct
- setDefaultBufferDecls
- buffer_decls_begin
- buffer_decls_end
- buffer_decls_empty
- HLSLRootSignatureDecl
- Create
- CreateDeserialized
- getNumModuleIdentifiers
- ImportDecl
- ImportDecl
- Create
- CreateImplicit
- CreateDeserialized
- getIdentifierLocs
- getSourceRange
- anchor
- Create
- CreateDeserialized
- IsArmStreamingFunction
- hasArmZAState
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more