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