Bug Summary

File:tools/clang/lib/AST/QualTypeNames.cpp
Warning:line 198, column 9
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/lib/AST/QualTypeNames.cpp

1//===------- QualTypeNames.cpp - Generate Complete QualType Names ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5//===----------------------------------------------------------------------===//
6//
7// This file is distributed under the University of Illinois Open Source
8// License. See LICENSE.TXT for details.
9//
10//===----------------------------------------------------------------------===//
11
12#include "clang/AST/DeclTemplate.h"
13#include "clang/AST/DeclarationName.h"
14#include "clang/AST/GlobalDecl.h"
15#include "clang/AST/Mangle.h"
16#include "clang/AST/QualTypeNames.h"
17
18#include <stdio.h>
19#include <memory>
20
21namespace clang {
22
23namespace TypeName {
24
25/// \brief Create a NestedNameSpecifier for Namesp and its enclosing
26/// scopes.
27///
28/// \param[in] Ctx - the AST Context to be used.
29/// \param[in] Namesp - the NamespaceDecl for which a NestedNameSpecifier
30/// is requested.
31/// \param[in] WithGlobalNsPrefix - Indicate whether the global namespace
32/// specifier "::" should be prepended or not.
33static NestedNameSpecifier *createNestedNameSpecifier(
34 const ASTContext &Ctx,
35 const NamespaceDecl *Namesp,
36 bool WithGlobalNsPrefix);
37
38/// \brief Create a NestedNameSpecifier for TagDecl and its enclosing
39/// scopes.
40///
41/// \param[in] Ctx - the AST Context to be used.
42/// \param[in] TD - the TagDecl for which a NestedNameSpecifier is
43/// requested.
44/// \param[in] FullyQualify - Convert all template arguments into fully
45/// qualified names.
46/// \param[in] WithGlobalNsPrefix - Indicate whether the global namespace
47/// specifier "::" should be prepended or not.
48static NestedNameSpecifier *createNestedNameSpecifier(
49 const ASTContext &Ctx, const TypeDecl *TD,
50 bool FullyQualify, bool WithGlobalNsPrefix);
51
52static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
53 const ASTContext &Ctx, const Decl *decl,
54 bool FullyQualified, bool WithGlobalNsPrefix);
55
56static NestedNameSpecifier *getFullyQualifiedNestedNameSpecifier(
57 const ASTContext &Ctx, NestedNameSpecifier *scope, bool WithGlobalNsPrefix);
58
59static bool getFullyQualifiedTemplateName(const ASTContext &Ctx,
60 TemplateName &TName,
61 bool WithGlobalNsPrefix) {
62 bool Changed = false;
63 NestedNameSpecifier *NNS = nullptr;
64
65 TemplateDecl *ArgTDecl = TName.getAsTemplateDecl();
66 // ArgTDecl won't be NULL because we asserted that this isn't a
67 // dependent context very early in the call chain.
68 assert(ArgTDecl != nullptr)(static_cast <bool> (ArgTDecl != nullptr) ? void (0) : __assert_fail
("ArgTDecl != nullptr", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/lib/AST/QualTypeNames.cpp"
, 68, __extension__ __PRETTY_FUNCTION__))
;
69 QualifiedTemplateName *QTName = TName.getAsQualifiedTemplateName();
70
71 if (QTName && !QTName->hasTemplateKeyword()) {
1
Assuming 'QTName' is null
72 NNS = QTName->getQualifier();
73 NestedNameSpecifier *QNNS = getFullyQualifiedNestedNameSpecifier(
74 Ctx, NNS, WithGlobalNsPrefix);
75 if (QNNS != NNS) {
76 Changed = true;
77 NNS = QNNS;
78 } else {
79 NNS = nullptr;
80 }
81 } else {
82 NNS = createNestedNameSpecifierForScopeOf(
2
Calling 'createNestedNameSpecifierForScopeOf'
83 Ctx, ArgTDecl, true, WithGlobalNsPrefix);
84 }
85 if (NNS) {
86 TName = Ctx.getQualifiedTemplateName(NNS,
87 /*TemplateKeyword=*/false, ArgTDecl);
88 Changed = true;
89 }
90 return Changed;
91}
92
93static bool getFullyQualifiedTemplateArgument(const ASTContext &Ctx,
94 TemplateArgument &Arg,
95 bool WithGlobalNsPrefix) {
96 bool Changed = false;
97
98 // Note: we do not handle TemplateArgument::Expression, to replace it
99 // we need the information for the template instance decl.
100
101 if (Arg.getKind() == TemplateArgument::Template) {
102 TemplateName TName = Arg.getAsTemplate();
103 Changed = getFullyQualifiedTemplateName(Ctx, TName, WithGlobalNsPrefix);
104 if (Changed) {
105 Arg = TemplateArgument(TName);
106 }
107 } else if (Arg.getKind() == TemplateArgument::Type) {
108 QualType SubTy = Arg.getAsType();
109 // Check if the type needs more desugaring and recurse.
110 QualType QTFQ = getFullyQualifiedType(SubTy, Ctx, WithGlobalNsPrefix);
111 if (QTFQ != SubTy) {
112 Arg = TemplateArgument(QTFQ);
113 Changed = true;
114 }
115 }
116 return Changed;
117}
118
119static const Type *getFullyQualifiedTemplateType(const ASTContext &Ctx,
120 const Type *TypePtr,
121 bool WithGlobalNsPrefix) {
122 // DependentTemplateTypes exist within template declarations and
123 // definitions. Therefore we shouldn't encounter them at the end of
124 // a translation unit. If we do, the caller has made an error.
125 assert(!isa<DependentTemplateSpecializationType>(TypePtr))(static_cast <bool> (!isa<DependentTemplateSpecializationType
>(TypePtr)) ? void (0) : __assert_fail ("!isa<DependentTemplateSpecializationType>(TypePtr)"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/lib/AST/QualTypeNames.cpp"
, 125, __extension__ __PRETTY_FUNCTION__))
;
126 // In case of template specializations, iterate over the arguments
127 // and fully qualify them as well.
128 if (const auto *TST = dyn_cast<const TemplateSpecializationType>(TypePtr)) {
129 bool MightHaveChanged = false;
130 SmallVector<TemplateArgument, 4> FQArgs;
131 for (TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();
132 I != E; ++I) {
133 // Cheap to copy and potentially modified by
134 // getFullyQualifedTemplateArgument.
135 TemplateArgument Arg(*I);
136 MightHaveChanged |= getFullyQualifiedTemplateArgument(
137 Ctx, Arg, WithGlobalNsPrefix);
138 FQArgs.push_back(Arg);
139 }
140
141 // If a fully qualified arg is different from the unqualified arg,
142 // allocate new type in the AST.
143 if (MightHaveChanged) {
144 QualType QT = Ctx.getTemplateSpecializationType(
145 TST->getTemplateName(), FQArgs,
146 TST->getCanonicalTypeInternal());
147 // getTemplateSpecializationType returns a fully qualified
148 // version of the specialization itself, so no need to qualify
149 // it.
150 return QT.getTypePtr();
151 }
152 } else if (const auto *TSTRecord = dyn_cast<const RecordType>(TypePtr)) {
153 // We are asked to fully qualify and we have a Record Type,
154 // which can point to a template instantiation with no sugar in any of
155 // its template argument, however we still need to fully qualify them.
156
157 if (const auto *TSTDecl =
158 dyn_cast<ClassTemplateSpecializationDecl>(TSTRecord->getDecl())) {
159 const TemplateArgumentList &TemplateArgs = TSTDecl->getTemplateArgs();
160
161 bool MightHaveChanged = false;
162 SmallVector<TemplateArgument, 4> FQArgs;
163 for (unsigned int I = 0, E = TemplateArgs.size(); I != E; ++I) {
164 // cheap to copy and potentially modified by
165 // getFullyQualifedTemplateArgument
166 TemplateArgument Arg(TemplateArgs[I]);
167 MightHaveChanged |= getFullyQualifiedTemplateArgument(
168 Ctx, Arg, WithGlobalNsPrefix);
169 FQArgs.push_back(Arg);
170 }
171
172 // If a fully qualified arg is different from the unqualified arg,
173 // allocate new type in the AST.
174 if (MightHaveChanged) {
175 TemplateName TN(TSTDecl->getSpecializedTemplate());
176 QualType QT = Ctx.getTemplateSpecializationType(
177 TN, FQArgs,
178 TSTRecord->getCanonicalTypeInternal());
179 // getTemplateSpecializationType returns a fully qualified
180 // version of the specialization itself, so no need to qualify
181 // it.
182 return QT.getTypePtr();
183 }
184 }
185 }
186 return TypePtr;
187}
188
189static NestedNameSpecifier *createOuterNNS(const ASTContext &Ctx, const Decl *D,
190 bool FullyQualify,
191 bool WithGlobalNsPrefix) {
192 const DeclContext *DC = D->getDeclContext();
193 if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
11
Assuming 'NS' is non-null
12
Taking true branch
194 while (NS && NS->isInline()) {
13
Loop condition is true. Entering loop body
53
Assuming 'NS' is null
54
Assuming pointer value is null
195 // Ignore inline namespace;
196 NS = dyn_cast<NamespaceDecl>(NS->getDeclContext());
14
Calling 'dyn_cast'
51
Returning from 'dyn_cast'
52
Value assigned to 'NS'
197 }
198 if (NS->getDeclName()) {
55
Called C++ object pointer is null
199 return createNestedNameSpecifier(Ctx, NS, WithGlobalNsPrefix);
200 }
201 return nullptr; // no starting '::', no anonymous
202 } else if (const auto *TD = dyn_cast<TagDecl>(DC)) {
203 return createNestedNameSpecifier(Ctx, TD, FullyQualify, WithGlobalNsPrefix);
204 } else if (const auto *TDD = dyn_cast<TypedefNameDecl>(DC)) {
205 return createNestedNameSpecifier(
206 Ctx, TDD, FullyQualify, WithGlobalNsPrefix);
207 } else if (WithGlobalNsPrefix && DC->isTranslationUnit()) {
208 return NestedNameSpecifier::GlobalSpecifier(Ctx);
209 }
210 return nullptr; // no starting '::' if |WithGlobalNsPrefix| is false
211}
212
213/// \brief Return a fully qualified version of this name specifier.
214static NestedNameSpecifier *getFullyQualifiedNestedNameSpecifier(
215 const ASTContext &Ctx, NestedNameSpecifier *Scope,
216 bool WithGlobalNsPrefix) {
217 switch (Scope->getKind()) {
218 case NestedNameSpecifier::Global:
219 // Already fully qualified
220 return Scope;
221 case NestedNameSpecifier::Namespace:
222 return TypeName::createNestedNameSpecifier(
223 Ctx, Scope->getAsNamespace(), WithGlobalNsPrefix);
224 case NestedNameSpecifier::NamespaceAlias:
225 // Namespace aliases are only valid for the duration of the
226 // scope where they were introduced, and therefore are often
227 // invalid at the end of the TU. So use the namespace name more
228 // likely to be valid at the end of the TU.
229 return TypeName::createNestedNameSpecifier(
230 Ctx,
231 Scope->getAsNamespaceAlias()->getNamespace()->getCanonicalDecl(),
232 WithGlobalNsPrefix);
233 case NestedNameSpecifier::Identifier:
234 // A function or some other construct that makes it un-namable
235 // at the end of the TU. Skip the current component of the name,
236 // but use the name of it's prefix.
237 return getFullyQualifiedNestedNameSpecifier(
238 Ctx, Scope->getPrefix(), WithGlobalNsPrefix);
239 case NestedNameSpecifier::Super:
240 case NestedNameSpecifier::TypeSpec:
241 case NestedNameSpecifier::TypeSpecWithTemplate: {
242 const Type *Type = Scope->getAsType();
243 // Find decl context.
244 const TagDecl *TD = nullptr;
245 if (const TagType *TagDeclType = Type->getAs<TagType>()) {
246 TD = TagDeclType->getDecl();
247 } else {
248 TD = Type->getAsCXXRecordDecl();
249 }
250 if (TD) {
251 return TypeName::createNestedNameSpecifier(Ctx, TD,
252 true /*FullyQualified*/,
253 WithGlobalNsPrefix);
254 } else if (const auto *TDD = dyn_cast<TypedefType>(Type)) {
255 return TypeName::createNestedNameSpecifier(Ctx, TDD->getDecl(),
256 true /*FullyQualified*/,
257 WithGlobalNsPrefix);
258 }
259 return Scope;
260 }
261 }
262 llvm_unreachable("bad NNS kind")::llvm::llvm_unreachable_internal("bad NNS kind", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/lib/AST/QualTypeNames.cpp"
, 262)
;
263}
264
265/// \brief Create a nested name specifier for the declaring context of
266/// the type.
267static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
268 const ASTContext &Ctx, const Decl *Decl,
269 bool FullyQualified, bool WithGlobalNsPrefix) {
270 assert(Decl)(static_cast <bool> (Decl) ? void (0) : __assert_fail (
"Decl", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/lib/AST/QualTypeNames.cpp"
, 270, __extension__ __PRETTY_FUNCTION__))
;
271
272 const DeclContext *DC = Decl->getDeclContext()->getRedeclContext();
273 const auto *Outer = dyn_cast_or_null<NamedDecl>(DC);
274 const auto *OuterNS = dyn_cast_or_null<NamespaceDecl>(DC);
275 if (Outer && !(OuterNS && OuterNS->isAnonymousNamespace())) {
3
Assuming 'Outer' is non-null
4
Taking true branch
276 if (const auto *CxxDecl = dyn_cast<CXXRecordDecl>(DC)) {
5
Taking false branch
277 if (ClassTemplateDecl *ClassTempl =
278 CxxDecl->getDescribedClassTemplate()) {
279 // We are in the case of a type(def) that was declared in a
280 // class template but is *not* type dependent. In clang, it
281 // gets attached to the class template declaration rather than
282 // any specific class template instantiation. This result in
283 // 'odd' fully qualified typename:
284 //
285 // vector<_Tp,_Alloc>::size_type
286 //
287 // Make the situation is 'useable' but looking a bit odd by
288 // picking a random instance as the declaring context.
289 if (ClassTempl->spec_begin() != ClassTempl->spec_end()) {
290 Decl = *(ClassTempl->spec_begin());
291 Outer = dyn_cast<NamedDecl>(Decl);
292 OuterNS = dyn_cast<NamespaceDecl>(Decl);
293 }
294 }
295 }
296
297 if (OuterNS) {
6
Taking false branch
298 return createNestedNameSpecifier(Ctx, OuterNS, WithGlobalNsPrefix);
299 } else if (const auto *TD = dyn_cast<TagDecl>(Outer)) {
7
Assuming 'TD' is non-null
8
Taking true branch
300 return createNestedNameSpecifier(
9
Calling 'createNestedNameSpecifier'
301 Ctx, TD, FullyQualified, WithGlobalNsPrefix);
302 } else if (dyn_cast<TranslationUnitDecl>(Outer)) {
303 // Context is the TU. Nothing needs to be done.
304 return nullptr;
305 } else {
306 // Decl's context was neither the TU, a namespace, nor a
307 // TagDecl, which means it is a type local to a scope, and not
308 // accessible at the end of the TU.
309 return nullptr;
310 }
311 } else if (WithGlobalNsPrefix && DC->isTranslationUnit()) {
312 return NestedNameSpecifier::GlobalSpecifier(Ctx);
313 }
314 return nullptr;
315}
316
317/// \brief Create a nested name specifier for the declaring context of
318/// the type.
319static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
320 const ASTContext &Ctx, const Type *TypePtr,
321 bool FullyQualified, bool WithGlobalNsPrefix) {
322 if (!TypePtr) return nullptr;
323
324 Decl *Decl = nullptr;
325 // There are probably other cases ...
326 if (const auto *TDT = dyn_cast<TypedefType>(TypePtr)) {
327 Decl = TDT->getDecl();
328 } else if (const auto *TagDeclType = dyn_cast<TagType>(TypePtr)) {
329 Decl = TagDeclType->getDecl();
330 } else if (const auto *TST = dyn_cast<TemplateSpecializationType>(TypePtr)) {
331 Decl = TST->getTemplateName().getAsTemplateDecl();
332 } else {
333 Decl = TypePtr->getAsCXXRecordDecl();
334 }
335
336 if (!Decl) return nullptr;
337
338 return createNestedNameSpecifierForScopeOf(
339 Ctx, Decl, FullyQualified, WithGlobalNsPrefix);
340}
341
342NestedNameSpecifier *createNestedNameSpecifier(const ASTContext &Ctx,
343 const NamespaceDecl *Namespace,
344 bool WithGlobalNsPrefix) {
345 while (Namespace && Namespace->isInline()) {
346 // Ignore inline namespace;
347 Namespace = dyn_cast<NamespaceDecl>(Namespace->getDeclContext());
348 }
349 if (!Namespace) return nullptr;
350
351 bool FullyQualified = true; // doesn't matter, DeclContexts are namespaces
352 return NestedNameSpecifier::Create(
353 Ctx,
354 createOuterNNS(Ctx, Namespace, FullyQualified, WithGlobalNsPrefix),
355 Namespace);
356}
357
358NestedNameSpecifier *createNestedNameSpecifier(const ASTContext &Ctx,
359 const TypeDecl *TD,
360 bool FullyQualify,
361 bool WithGlobalNsPrefix) {
362 return NestedNameSpecifier::Create(
363 Ctx,
364 createOuterNNS(Ctx, TD, FullyQualify, WithGlobalNsPrefix),
10
Calling 'createOuterNNS'
365 false /*No TemplateKeyword*/,
366 TD->getTypeForDecl());
367}
368
369/// \brief Return the fully qualified type, including fully-qualified
370/// versions of any template parameters.
371QualType getFullyQualifiedType(QualType QT, const ASTContext &Ctx,
372 bool WithGlobalNsPrefix) {
373 // In case of myType* we need to strip the pointer first, fully
374 // qualify and attach the pointer once again.
375 if (isa<PointerType>(QT.getTypePtr())) {
376 // Get the qualifiers.
377 Qualifiers Quals = QT.getQualifiers();
378 QT = getFullyQualifiedType(QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
379 QT = Ctx.getPointerType(QT);
380 // Add back the qualifiers.
381 QT = Ctx.getQualifiedType(QT, Quals);
382 return QT;
383 }
384
385 // In case of myType& we need to strip the reference first, fully
386 // qualify and attach the reference once again.
387 if (isa<ReferenceType>(QT.getTypePtr())) {
388 // Get the qualifiers.
389 bool IsLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr());
390 Qualifiers Quals = QT.getQualifiers();
391 QT = getFullyQualifiedType(QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
392 // Add the r- or l-value reference type back to the fully
393 // qualified one.
394 if (IsLValueRefTy)
395 QT = Ctx.getLValueReferenceType(QT);
396 else
397 QT = Ctx.getRValueReferenceType(QT);
398 // Add back the qualifiers.
399 QT = Ctx.getQualifiedType(QT, Quals);
400 return QT;
401 }
402
403 // Remove the part of the type related to the type being a template
404 // parameter (we won't report it as part of the 'type name' and it
405 // is actually make the code below to be more complex (to handle
406 // those)
407 while (isa<SubstTemplateTypeParmType>(QT.getTypePtr())) {
408 // Get the qualifiers.
409 Qualifiers Quals = QT.getQualifiers();
410
411 QT = dyn_cast<SubstTemplateTypeParmType>(QT.getTypePtr())->desugar();
412
413 // Add back the qualifiers.
414 QT = Ctx.getQualifiedType(QT, Quals);
415 }
416
417 NestedNameSpecifier *Prefix = nullptr;
418 // Local qualifiers are attached to the QualType outside of the
419 // elaborated type. Retrieve them before descending into the
420 // elaborated type.
421 Qualifiers PrefixQualifiers = QT.getLocalQualifiers();
422 QT = QualType(QT.getTypePtr(), 0);
423 ElaboratedTypeKeyword Keyword = ETK_None;
424 if (const auto *ETypeInput = dyn_cast<ElaboratedType>(QT.getTypePtr())) {
425 QT = ETypeInput->getNamedType();
426 assert(!QT.hasLocalQualifiers())(static_cast <bool> (!QT.hasLocalQualifiers()) ? void (
0) : __assert_fail ("!QT.hasLocalQualifiers()", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/lib/AST/QualTypeNames.cpp"
, 426, __extension__ __PRETTY_FUNCTION__))
;
427 Keyword = ETypeInput->getKeyword();
428 }
429 // Create a nested name specifier if needed.
430 Prefix = createNestedNameSpecifierForScopeOf(Ctx, QT.getTypePtr(),
431 true /*FullyQualified*/,
432 WithGlobalNsPrefix);
433
434 // In case of template specializations iterate over the arguments and
435 // fully qualify them as well.
436 if (isa<const TemplateSpecializationType>(QT.getTypePtr()) ||
437 isa<const RecordType>(QT.getTypePtr())) {
438 // We are asked to fully qualify and we have a Record Type (which
439 // may point to a template specialization) or Template
440 // Specialization Type. We need to fully qualify their arguments.
441
442 const Type *TypePtr = getFullyQualifiedTemplateType(
443 Ctx, QT.getTypePtr(), WithGlobalNsPrefix);
444 QT = QualType(TypePtr, 0);
445 }
446 if (Prefix || Keyword != ETK_None) {
447 QT = Ctx.getElaboratedType(Keyword, Prefix, QT);
448 }
449 QT = Ctx.getQualifiedType(QT, PrefixQualifiers);
450 return QT;
451}
452
453std::string getFullyQualifiedName(QualType QT,
454 const ASTContext &Ctx,
455 bool WithGlobalNsPrefix) {
456 PrintingPolicy Policy(Ctx.getPrintingPolicy());
457 Policy.SuppressScope = false;
458 Policy.AnonymousTagLocations = false;
459 Policy.PolishForDeclaration = true;
460 Policy.SuppressUnwrittenScope = true;
461 QualType FQQT = getFullyQualifiedType(QT, Ctx, WithGlobalNsPrefix);
462 return FQQT.getAsString(Policy);
463}
464
465} // end namespace TypeName
466} // end namespace clang

/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
18
Calling 'simplify_type::getSimplifiedValue'
19
Returning from 'simplify_type::getSimplifiedValue'
40
Calling 'simplify_type::getSimplifiedValue'
41
Returning from 'simplify_type::getSimplifiedValue'
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
23
Within the expansion of the macro 'assert':
a
Assuming 'Val' is non-null
107 return isa_impl<To, From>::doit(*Val);
24
Calling 'isa_impl::doit'
30
Returning from 'isa_impl::doit'
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
21
Calling 'isa_impl_wrap::doit'
32
Returning from 'isa_impl_wrap::doit'
43
Calling 'isa_impl_wrap::doit'
44
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
17
Calling 'simplify_type::getSimplifiedValue'
20
Returning from 'simplify_type::getSimplifiedValue'
39
Calling 'simplify_type::getSimplifiedValue'
42
Returning from 'simplify_type::getSimplifiedValue'
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
22
Calling 'isa_impl_cl::doit'
31
Returning from 'isa_impl_cl::doit'
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
16
Calling 'isa_impl_wrap::doit'
33
Returning from 'isa_impl_wrap::doit'
38
Calling 'isa_impl_wrap::doit'
45
Returning from 'isa_impl_wrap::doit'
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
37
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
c
Assuming the condition is true
256 return cast_convert_val<X, Y*,
46
Calling 'cast_convert_val::doit'
49
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return cast<X>(Val);
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
15
Calling 'isa'
34
Returning from 'isa'
35
'?' condition is true
36
Calling 'cast'
50
Returning from 'cast'
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Decl and DeclContext interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLBASE_H
15#define LLVM_CLANG_AST_DECLBASE_H
16
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/Specifiers.h"
22#include "clang/Basic/VersionTuple.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include <algorithm>
32#include <cassert>
33#include <cstddef>
34#include <iterator>
35#include <string>
36#include <type_traits>
37#include <utility>
38
39namespace clang {
40
41class ASTContext;
42class ASTMutationListener;
43class Attr;
44class DeclContext;
45class ExternalSourceSymbolAttr;
46class FunctionDecl;
47class FunctionType;
48class IdentifierInfo;
49enum Linkage : unsigned char;
50class LinkageSpecDecl;
51class Module;
52class NamedDecl;
53class ObjCCategoryDecl;
54class ObjCCategoryImplDecl;
55class ObjCContainerDecl;
56class ObjCImplDecl;
57class ObjCImplementationDecl;
58class ObjCInterfaceDecl;
59class ObjCMethodDecl;
60class ObjCProtocolDecl;
61struct PrintingPolicy;
62class RecordDecl;
63class SourceManager;
64class Stmt;
65class StoredDeclsMap;
66class TemplateDecl;
67class TranslationUnitDecl;
68class UsingDirectiveDecl;
69
70/// \brief Captures the result of checking the availability of a
71/// declaration.
72enum AvailabilityResult {
73 AR_Available = 0,
74 AR_NotYetIntroduced,
75 AR_Deprecated,
76 AR_Unavailable
77};
78
79/// Decl - This represents one declaration (or definition), e.g. a variable,
80/// typedef, function, struct, etc.
81///
82/// Note: There are objects tacked on before the *beginning* of Decl
83/// (and its subclasses) in its Decl::operator new(). Proper alignment
84/// of all subclasses (not requiring more than the alignment of Decl) is
85/// asserted in DeclBase.cpp.
86class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)alignas(8) Decl {
87public:
88 /// \brief Lists the kind of concrete classes of Decl.
89 enum Kind {
90#define DECL(DERIVED, BASE) DERIVED,
91#define ABSTRACT_DECL(DECL)
92#define DECL_RANGE(BASE, START, END) \
93 first##BASE = START, last##BASE = END,
94#define LAST_DECL_RANGE(BASE, START, END) \
95 first##BASE = START, last##BASE = END
96#include "clang/AST/DeclNodes.inc"
97 };
98
99 /// \brief A placeholder type used to construct an empty shell of a
100 /// decl-derived type that will be filled in later (e.g., by some
101 /// deserialization method).
102 struct EmptyShell {};
103
104 /// IdentifierNamespace - The different namespaces in which
105 /// declarations may appear. According to C99 6.2.3, there are
106 /// four namespaces, labels, tags, members and ordinary
107 /// identifiers. C++ describes lookup completely differently:
108 /// certain lookups merely "ignore" certain kinds of declarations,
109 /// usually based on whether the declaration is of a type, etc.
110 ///
111 /// These are meant as bitmasks, so that searches in
112 /// C++ can look into the "tag" namespace during ordinary lookup.
113 ///
114 /// Decl currently provides 15 bits of IDNS bits.
115 enum IdentifierNamespace {
116 /// Labels, declared with 'x:' and referenced with 'goto x'.
117 IDNS_Label = 0x0001,
118
119 /// Tags, declared with 'struct foo;' and referenced with
120 /// 'struct foo'. All tags are also types. This is what
121 /// elaborated-type-specifiers look for in C.
122 /// This also contains names that conflict with tags in the
123 /// same scope but that are otherwise ordinary names (non-type
124 /// template parameters and indirect field declarations).
125 IDNS_Tag = 0x0002,
126
127 /// Types, declared with 'struct foo', typedefs, etc.
128 /// This is what elaborated-type-specifiers look for in C++,
129 /// but note that it's ill-formed to find a non-tag.
130 IDNS_Type = 0x0004,
131
132 /// Members, declared with object declarations within tag
133 /// definitions. In C, these can only be found by "qualified"
134 /// lookup in member expressions. In C++, they're found by
135 /// normal lookup.
136 IDNS_Member = 0x0008,
137
138 /// Namespaces, declared with 'namespace foo {}'.
139 /// Lookup for nested-name-specifiers find these.
140 IDNS_Namespace = 0x0010,
141
142 /// Ordinary names. In C, everything that's not a label, tag,
143 /// member, or function-local extern ends up here.
144 IDNS_Ordinary = 0x0020,
145
146 /// Objective C \@protocol.
147 IDNS_ObjCProtocol = 0x0040,
148
149 /// This declaration is a friend function. A friend function
150 /// declaration is always in this namespace but may also be in
151 /// IDNS_Ordinary if it was previously declared.
152 IDNS_OrdinaryFriend = 0x0080,
153
154 /// This declaration is a friend class. A friend class
155 /// declaration is always in this namespace but may also be in
156 /// IDNS_Tag|IDNS_Type if it was previously declared.
157 IDNS_TagFriend = 0x0100,
158
159 /// This declaration is a using declaration. A using declaration
160 /// *introduces* a number of other declarations into the current
161 /// scope, and those declarations use the IDNS of their targets,
162 /// but the actual using declarations go in this namespace.
163 IDNS_Using = 0x0200,
164
165 /// This declaration is a C++ operator declared in a non-class
166 /// context. All such operators are also in IDNS_Ordinary.
167 /// C++ lexical operator lookup looks for these.
168 IDNS_NonMemberOperator = 0x0400,
169
170 /// This declaration is a function-local extern declaration of a
171 /// variable or function. This may also be IDNS_Ordinary if it
172 /// has been declared outside any function. These act mostly like
173 /// invisible friend declarations, but are also visible to unqualified
174 /// lookup within the scope of the declaring function.
175 IDNS_LocalExtern = 0x0800,
176
177 /// This declaration is an OpenMP user defined reduction construction.
178 IDNS_OMPReduction = 0x1000
179 };
180
181 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
182 /// parameter types in method declarations. Other than remembering
183 /// them and mangling them into the method's signature string, these
184 /// are ignored by the compiler; they are consumed by certain
185 /// remote-messaging frameworks.
186 ///
187 /// in, inout, and out are mutually exclusive and apply only to
188 /// method parameters. bycopy and byref are mutually exclusive and
189 /// apply only to method parameters (?). oneway applies only to
190 /// results. All of these expect their corresponding parameter to
191 /// have a particular type. None of this is currently enforced by
192 /// clang.
193 ///
194 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
195 enum ObjCDeclQualifier {
196 OBJC_TQ_None = 0x0,
197 OBJC_TQ_In = 0x1,
198 OBJC_TQ_Inout = 0x2,
199 OBJC_TQ_Out = 0x4,
200 OBJC_TQ_Bycopy = 0x8,
201 OBJC_TQ_Byref = 0x10,
202 OBJC_TQ_Oneway = 0x20,
203
204 /// The nullability qualifier is set when the nullability of the
205 /// result or parameter was expressed via a context-sensitive
206 /// keyword.
207 OBJC_TQ_CSNullability = 0x40
208 };
209
210 /// The kind of ownership a declaration has, for visibility purposes.
211 /// This enumeration is designed such that higher values represent higher
212 /// levels of name hiding.
213 enum class ModuleOwnershipKind : unsigned {
214 /// This declaration is not owned by a module.
215 Unowned,
216
217 /// This declaration has an owning module, but is globally visible
218 /// (typically because its owning module is visible and we know that
219 /// modules cannot later become hidden in this compilation).
220 /// After serialization and deserialization, this will be converted
221 /// to VisibleWhenImported.
222 Visible,
223
224 /// This declaration has an owning module, and is visible when that
225 /// module is imported.
226 VisibleWhenImported,
227
228 /// This declaration has an owning module, but is only visible to
229 /// lookups that occur within that module.
230 ModulePrivate
231 };
232
233protected:
234 /// \brief The next declaration within the same lexical
235 /// DeclContext. These pointers form the linked list that is
236 /// traversed via DeclContext's decls_begin()/decls_end().
237 ///
238 /// The extra two bits are used for the ModuleOwnershipKind.
239 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
240
241private:
242 friend class DeclContext;
243
244 struct MultipleDC {
245 DeclContext *SemanticDC;
246 DeclContext *LexicalDC;
247 };
248
249 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
250 /// For declarations that don't contain C++ scope specifiers, it contains
251 /// the DeclContext where the Decl was declared.
252 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
253 /// with the context where it semantically belongs (SemanticDC) and the
254 /// context where it was lexically declared (LexicalDC).
255 /// e.g.:
256 ///
257 /// namespace A {
258 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
259 /// }
260 /// void A::f(); // SemanticDC == namespace 'A'
261 /// // LexicalDC == global namespace
262 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
263
264 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
265 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
266
267 MultipleDC *getMultipleDC() const {
268 return DeclCtx.get<MultipleDC*>();
269 }
270
271 DeclContext *getSemanticDC() const {
272 return DeclCtx.get<DeclContext*>();
273 }
274
275 /// Loc - The location of this decl.
276 SourceLocation Loc;
277
278 /// DeclKind - This indicates which class this is.
279 unsigned DeclKind : 7;
280
281 /// InvalidDecl - This indicates a semantic error occurred.
282 unsigned InvalidDecl : 1;
283
284 /// HasAttrs - This indicates whether the decl has attributes or not.
285 unsigned HasAttrs : 1;
286
287 /// Implicit - Whether this declaration was implicitly generated by
288 /// the implementation rather than explicitly written by the user.
289 unsigned Implicit : 1;
290
291 /// \brief Whether this declaration was "used", meaning that a definition is
292 /// required.
293 unsigned Used : 1;
294
295 /// \brief Whether this declaration was "referenced".
296 /// The difference with 'Used' is whether the reference appears in a
297 /// evaluated context or not, e.g. functions used in uninstantiated templates
298 /// are regarded as "referenced" but not "used".
299 unsigned Referenced : 1;
300
301 /// \brief Whether this declaration is a top-level declaration (function,
302 /// global variable, etc.) that is lexically inside an objc container
303 /// definition.
304 unsigned TopLevelDeclInObjCContainer : 1;
305
306 /// \brief Whether statistic collection is enabled.
307 static bool StatisticsEnabled;
308
309protected:
310 friend class ASTDeclReader;
311 friend class ASTDeclWriter;
312 friend class ASTReader;
313 friend class CXXClassMemberWrapper;
314 friend class LinkageComputer;
315 template<typename decl_type> friend class Redeclarable;
316
317 /// Access - Used by C++ decls for the access specifier.
318 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
319 unsigned Access : 2;
320
321 /// \brief Whether this declaration was loaded from an AST file.
322 unsigned FromASTFile : 1;
323
324 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
325 unsigned IdentifierNamespace : 13;
326
327 /// \brief If 0, we have not computed the linkage of this declaration.
328 /// Otherwise, it is the linkage + 1.
329 mutable unsigned CacheValidAndLinkage : 3;
330
331 /// \brief Allocate memory for a deserialized declaration.
332 ///
333 /// This routine must be used to allocate memory for any declaration that is
334 /// deserialized from a module file.
335 ///
336 /// \param Size The size of the allocated object.
337 /// \param Ctx The context in which we will allocate memory.
338 /// \param ID The global ID of the deserialized declaration.
339 /// \param Extra The amount of extra space to allocate after the object.
340 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
341 std::size_t Extra = 0);
342
343 /// \brief Allocate memory for a non-deserialized declaration.
344 void *operator new(std::size_t Size, const ASTContext &Ctx,
345 DeclContext *Parent, std::size_t Extra = 0);
346
347private:
348 bool AccessDeclContextSanity() const;
349
350 /// Get the module ownership kind to use for a local lexical child of \p DC,
351 /// which may be either a local or (rarely) an imported declaration.
352 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
353 if (DC) {
354 auto *D = cast<Decl>(DC);
355 auto MOK = D->getModuleOwnershipKind();
356 if (MOK != ModuleOwnershipKind::Unowned &&
357 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
358 return MOK;
359 // If D is not local and we have no local module storage, then we don't
360 // need to track module ownership at all.
361 }
362 return ModuleOwnershipKind::Unowned;
363 }
364
365protected:
366 Decl(Kind DK, DeclContext *DC, SourceLocation L)
367 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
368 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
369 Implicit(false), Used(false), Referenced(false),
370 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
371 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
372 CacheValidAndLinkage(0) {
373 if (StatisticsEnabled) add(DK);
374 }
375
376 Decl(Kind DK, EmptyShell Empty)
377 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
378 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
379 Access(AS_none), FromASTFile(0),
380 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
381 CacheValidAndLinkage(0) {
382 if (StatisticsEnabled) add(DK);
383 }
384
385 virtual ~Decl();
386
387 /// \brief Update a potentially out-of-date declaration.
388 void updateOutOfDate(IdentifierInfo &II) const;
389
390 Linkage getCachedLinkage() const {
391 return Linkage(CacheValidAndLinkage - 1);
392 }
393
394 void setCachedLinkage(Linkage L) const {
395 CacheValidAndLinkage = L + 1;
396 }
397
398 bool hasCachedLinkage() const {
399 return CacheValidAndLinkage;
400 }
401
402public:
403 /// \brief Source range that this declaration covers.
404 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
405 return SourceRange(getLocation(), getLocation());
406 }
407
408 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
409 return getSourceRange().getBegin();
410 }
411
412 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
413 return getSourceRange().getEnd();
414 }
415
416 SourceLocation getLocation() const { return Loc; }
417 void setLocation(SourceLocation L) { Loc = L; }
418
419 Kind getKind() const { return static_cast<Kind>(DeclKind); }
420 const char *getDeclKindName() const;
421
422 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
423 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
424
425 DeclContext *getDeclContext() {
426 if (isInSemaDC())
427 return getSemanticDC();
428 return getMultipleDC()->SemanticDC;
429 }
430 const DeclContext *getDeclContext() const {
431 return const_cast<Decl*>(this)->getDeclContext();
432 }
433
434 /// Find the innermost non-closure ancestor of this declaration,
435 /// walking up through blocks, lambdas, etc. If that ancestor is
436 /// not a code context (!isFunctionOrMethod()), returns null.
437 ///
438 /// A declaration may be its own non-closure context.
439 Decl *getNonClosureContext();
440 const Decl *getNonClosureContext() const {
441 return const_cast<Decl*>(this)->getNonClosureContext();
442 }
443
444 TranslationUnitDecl *getTranslationUnitDecl();
445 const TranslationUnitDecl *getTranslationUnitDecl() const {
446 return const_cast<Decl*>(this)->getTranslationUnitDecl();
447 }
448
449 bool isInAnonymousNamespace() const;
450
451 bool isInStdNamespace() const;
452
453 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
454
455 void setAccess(AccessSpecifier AS) {
456 Access = AS;
457 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 457, __extension__ __PRETTY_FUNCTION__))
;
458 }
459
460 AccessSpecifier getAccess() const {
461 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 461, __extension__ __PRETTY_FUNCTION__))
;
462 return AccessSpecifier(Access);
463 }
464
465 /// \brief Retrieve the access specifier for this declaration, even though
466 /// it may not yet have been properly set.
467 AccessSpecifier getAccessUnsafe() const {
468 return AccessSpecifier(Access);
469 }
470
471 bool hasAttrs() const { return HasAttrs; }
472
473 void setAttrs(const AttrVec& Attrs) {
474 return setAttrsImpl(Attrs, getASTContext());
475 }
476
477 AttrVec &getAttrs() {
478 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
479 }
480
481 const AttrVec &getAttrs() const;
482 void dropAttrs();
483
484 void addAttr(Attr *A) {
485 if (hasAttrs())
486 getAttrs().push_back(A);
487 else
488 setAttrs(AttrVec(1, A));
489 }
490
491 using attr_iterator = AttrVec::const_iterator;
492 using attr_range = llvm::iterator_range<attr_iterator>;
493
494 attr_range attrs() const {
495 return attr_range(attr_begin(), attr_end());
496 }
497
498 attr_iterator attr_begin() const {
499 return hasAttrs() ? getAttrs().begin() : nullptr;
500 }
501 attr_iterator attr_end() const {
502 return hasAttrs() ? getAttrs().end() : nullptr;
503 }
504
505 template <typename T>
506 void dropAttr() {
507 if (!HasAttrs) return;
508
509 AttrVec &Vec = getAttrs();
510 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
511
512 if (Vec.empty())
513 HasAttrs = false;
514 }
515
516 template <typename T>
517 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
518 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
519 }
520
521 template <typename T>
522 specific_attr_iterator<T> specific_attr_begin() const {
523 return specific_attr_iterator<T>(attr_begin());
524 }
525
526 template <typename T>
527 specific_attr_iterator<T> specific_attr_end() const {
528 return specific_attr_iterator<T>(attr_end());
529 }
530
531 template<typename T> T *getAttr() const {
532 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
533 }
534
535 template<typename T> bool hasAttr() const {
536 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
537 }
538
539 /// getMaxAlignment - return the maximum alignment specified by attributes
540 /// on this decl, 0 if there are none.
541 unsigned getMaxAlignment() const;
542
543 /// setInvalidDecl - Indicates the Decl had a semantic error. This
544 /// allows for graceful error recovery.
545 void setInvalidDecl(bool Invalid = true);
546 bool isInvalidDecl() const { return (bool) InvalidDecl; }
547
548 /// isImplicit - Indicates whether the declaration was implicitly
549 /// generated by the implementation. If false, this declaration
550 /// was written explicitly in the source code.
551 bool isImplicit() const { return Implicit; }
552 void setImplicit(bool I = true) { Implicit = I; }
553
554 /// \brief Whether *any* (re-)declaration of the entity was used, meaning that
555 /// a definition is required.
556 ///
557 /// \param CheckUsedAttr When true, also consider the "used" attribute
558 /// (in addition to the "used" bit set by \c setUsed()) when determining
559 /// whether the function is used.
560 bool isUsed(bool CheckUsedAttr = true) const;
561
562 /// \brief Set whether the declaration is used, in the sense of odr-use.
563 ///
564 /// This should only be used immediately after creating a declaration.
565 /// It intentionally doesn't notify any listeners.
566 void setIsUsed() { getCanonicalDecl()->Used = true; }
567
568 /// \brief Mark the declaration used, in the sense of odr-use.
569 ///
570 /// This notifies any mutation listeners in addition to setting a bit
571 /// indicating the declaration is used.
572 void markUsed(ASTContext &C);
573
574 /// \brief Whether any declaration of this entity was referenced.
575 bool isReferenced() const;
576
577 /// \brief Whether this declaration was referenced. This should not be relied
578 /// upon for anything other than debugging.
579 bool isThisDeclarationReferenced() const { return Referenced; }
580
581 void setReferenced(bool R = true) { Referenced = R; }
582
583 /// \brief Whether this declaration is a top-level declaration (function,
584 /// global variable, etc.) that is lexically inside an objc container
585 /// definition.
586 bool isTopLevelDeclInObjCContainer() const {
587 return TopLevelDeclInObjCContainer;
588 }
589
590 void setTopLevelDeclInObjCContainer(bool V = true) {
591 TopLevelDeclInObjCContainer = V;
592 }
593
594 /// \brief Looks on this and related declarations for an applicable
595 /// external source symbol attribute.
596 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
597
598 /// \brief Whether this declaration was marked as being private to the
599 /// module in which it was defined.
600 bool isModulePrivate() const {
601 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
602 }
603
604 /// \brief Whether this declaration is exported (by virtue of being lexically
605 /// within an ExportDecl or by being a NamespaceDecl).
606 bool isExported() const;
607
608 /// Return true if this declaration has an attribute which acts as
609 /// definition of the entity, such as 'alias' or 'ifunc'.
610 bool hasDefiningAttr() const;
611
612 /// Return this declaration's defining attribute if it has one.
613 const Attr *getDefiningAttr() const;
614
615protected:
616 /// \brief Specify that this declaration was marked as being private
617 /// to the module in which it was defined.
618 void setModulePrivate() {
619 // The module-private specifier has no effect on unowned declarations.
620 // FIXME: We should track this in some way for source fidelity.
621 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
622 return;
623 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
624 }
625
626 /// \brief Set the owning module ID.
627 void setOwningModuleID(unsigned ID) {
628 assert(isFromASTFile() && "Only works on a deserialized declaration")(static_cast <bool> (isFromASTFile() && "Only works on a deserialized declaration"
) ? void (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 628, __extension__ __PRETTY_FUNCTION__))
;
629 *((unsigned*)this - 2) = ID;
630 }
631
632public:
633 /// \brief Determine the availability of the given declaration.
634 ///
635 /// This routine will determine the most restrictive availability of
636 /// the given declaration (e.g., preferring 'unavailable' to
637 /// 'deprecated').
638 ///
639 /// \param Message If non-NULL and the result is not \c
640 /// AR_Available, will be set to a (possibly empty) message
641 /// describing why the declaration has not been introduced, is
642 /// deprecated, or is unavailable.
643 ///
644 /// \param EnclosingVersion The version to compare with. If empty, assume the
645 /// deployment target version.
646 AvailabilityResult
647 getAvailability(std::string *Message = nullptr,
648 VersionTuple EnclosingVersion = VersionTuple()) const;
649
650 /// \brief Retrieve the version of the target platform in which this
651 /// declaration was introduced.
652 ///
653 /// \returns An empty version tuple if this declaration has no 'introduced'
654 /// availability attributes, or the version tuple that's specified in the
655 /// attribute otherwise.
656 VersionTuple getVersionIntroduced() const;
657
658 /// \brief Determine whether this declaration is marked 'deprecated'.
659 ///
660 /// \param Message If non-NULL and the declaration is deprecated,
661 /// this will be set to the message describing why the declaration
662 /// was deprecated (which may be empty).
663 bool isDeprecated(std::string *Message = nullptr) const {
664 return getAvailability(Message) == AR_Deprecated;
665 }
666
667 /// \brief Determine whether this declaration is marked 'unavailable'.
668 ///
669 /// \param Message If non-NULL and the declaration is unavailable,
670 /// this will be set to the message describing why the declaration
671 /// was made unavailable (which may be empty).
672 bool isUnavailable(std::string *Message = nullptr) const {
673 return getAvailability(Message) == AR_Unavailable;
674 }
675
676 /// \brief Determine whether this is a weak-imported symbol.
677 ///
678 /// Weak-imported symbols are typically marked with the
679 /// 'weak_import' attribute, but may also be marked with an
680 /// 'availability' attribute where we're targing a platform prior to
681 /// the introduction of this feature.
682 bool isWeakImported() const;
683
684 /// \brief Determines whether this symbol can be weak-imported,
685 /// e.g., whether it would be well-formed to add the weak_import
686 /// attribute.
687 ///
688 /// \param IsDefinition Set to \c true to indicate that this
689 /// declaration cannot be weak-imported because it has a definition.
690 bool canBeWeakImported(bool &IsDefinition) const;
691
692 /// \brief Determine whether this declaration came from an AST file (such as
693 /// a precompiled header or module) rather than having been parsed.
694 bool isFromASTFile() const { return FromASTFile; }
695
696 /// \brief Retrieve the global declaration ID associated with this
697 /// declaration, which specifies where this Decl was loaded from.
698 unsigned getGlobalID() const {
699 if (isFromASTFile())
700 return *((const unsigned*)this - 1);
701 return 0;
702 }
703
704 /// \brief Retrieve the global ID of the module that owns this particular
705 /// declaration.
706 unsigned getOwningModuleID() const {
707 if (isFromASTFile())
708 return *((const unsigned*)this - 2);
709 return 0;
710 }
711
712private:
713 Module *getOwningModuleSlow() const;
714
715protected:
716 bool hasLocalOwningModuleStorage() const;
717
718public:
719 /// \brief Get the imported owning module, if this decl is from an imported
720 /// (non-local) module.
721 Module *getImportedOwningModule() const {
722 if (!isFromASTFile() || !hasOwningModule())
723 return nullptr;
724
725 return getOwningModuleSlow();
726 }
727
728 /// \brief Get the local owning module, if known. Returns nullptr if owner is
729 /// not yet known or declaration is not from a module.
730 Module *getLocalOwningModule() const {
731 if (isFromASTFile() || !hasOwningModule())
732 return nullptr;
733
734 assert(hasLocalOwningModuleStorage() &&(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 735, __extension__ __PRETTY_FUNCTION__))
735 "owned local decl but no local module storage")(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 735, __extension__ __PRETTY_FUNCTION__))
;
736 return reinterpret_cast<Module *const *>(this)[-1];
737 }
738 void setLocalOwningModule(Module *M) {
739 assert(!isFromASTFile() && hasOwningModule() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 741, __extension__ __PRETTY_FUNCTION__))
740 hasLocalOwningModuleStorage() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 741, __extension__ __PRETTY_FUNCTION__))
741 "should not have a cached owning module")(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 741, __extension__ __PRETTY_FUNCTION__))
;
742 reinterpret_cast<Module **>(this)[-1] = M;
743 }
744
745 /// Is this declaration owned by some module?
746 bool hasOwningModule() const {
747 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
748 }
749
750 /// Get the module that owns this declaration (for visibility purposes).
751 Module *getOwningModule() const {
752 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
753 }
754
755 /// Get the module that owns this declaration for linkage purposes.
756 /// There only ever is such a module under the C++ Modules TS.
757 ///
758 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
759 /// all declarations in a global module fragment are unowned.
760 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
761
762 /// \brief Determine whether this declaration might be hidden from name
763 /// lookup. Note that the declaration might be visible even if this returns
764 /// \c false, if the owning module is visible within the query context.
765 // FIXME: Rename this to make it clearer what it does.
766 bool isHidden() const {
767 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
768 }
769
770 /// Set that this declaration is globally visible, even if it came from a
771 /// module that is not visible.
772 void setVisibleDespiteOwningModule() {
773 if (isHidden())
774 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
775 }
776
777 /// \brief Get the kind of module ownership for this declaration.
778 ModuleOwnershipKind getModuleOwnershipKind() const {
779 return NextInContextAndBits.getInt();
780 }
781
782 /// \brief Set whether this declaration is hidden from name lookup.
783 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
784 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
785 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
786 !hasLocalOwningModuleStorage()) &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
787 "no storage available for owning module for this declaration")(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
;
788 NextInContextAndBits.setInt(MOK);
789 }
790
791 unsigned getIdentifierNamespace() const {
792 return IdentifierNamespace;
793 }
794
795 bool isInIdentifierNamespace(unsigned NS) const {
796 return getIdentifierNamespace() & NS;
797 }
798
799 static unsigned getIdentifierNamespaceForKind(Kind DK);
800
801 bool hasTagIdentifierNamespace() const {
802 return isTagIdentifierNamespace(getIdentifierNamespace());
803 }
804
805 static bool isTagIdentifierNamespace(unsigned NS) {
806 // TagDecls have Tag and Type set and may also have TagFriend.
807 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
808 }
809
810 /// getLexicalDeclContext - The declaration context where this Decl was
811 /// lexically declared (LexicalDC). May be different from
812 /// getDeclContext() (SemanticDC).
813 /// e.g.:
814 ///
815 /// namespace A {
816 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
817 /// }
818 /// void A::f(); // SemanticDC == namespace 'A'
819 /// // LexicalDC == global namespace
820 DeclContext *getLexicalDeclContext() {
821 if (isInSemaDC())
822 return getSemanticDC();
823 return getMultipleDC()->LexicalDC;
824 }
825 const DeclContext *getLexicalDeclContext() const {
826 return const_cast<Decl*>(this)->getLexicalDeclContext();
827 }
828
829 /// Determine whether this declaration is declared out of line (outside its
830 /// semantic context).
831 virtual bool isOutOfLine() const;
832
833 /// setDeclContext - Set both the semantic and lexical DeclContext
834 /// to DC.
835 void setDeclContext(DeclContext *DC);
836
837 void setLexicalDeclContext(DeclContext *DC);
838
839 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
840 /// scoped decl is defined outside the current function or method. This is
841 /// roughly global variables and functions, but also handles enums (which
842 /// could be defined inside or outside a function etc).
843 bool isDefinedOutsideFunctionOrMethod() const {
844 return getParentFunctionOrMethod() == nullptr;
845 }
846
847 /// \brief Returns true if this declaration lexically is inside a function.
848 /// It recognizes non-defining declarations as well as members of local
849 /// classes:
850 /// \code
851 /// void foo() { void bar(); }
852 /// void foo2() { class ABC { void bar(); }; }
853 /// \endcode
854 bool isLexicallyWithinFunctionOrMethod() const;
855
856 /// \brief If this decl is defined inside a function/method/block it returns
857 /// the corresponding DeclContext, otherwise it returns null.
858 const DeclContext *getParentFunctionOrMethod() const;
859 DeclContext *getParentFunctionOrMethod() {
860 return const_cast<DeclContext*>(
861 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
862 }
863
864 /// \brief Retrieves the "canonical" declaration of the given declaration.
865 virtual Decl *getCanonicalDecl() { return this; }
866 const Decl *getCanonicalDecl() const {
867 return const_cast<Decl*>(this)->getCanonicalDecl();
868 }
869
870 /// \brief Whether this particular Decl is a canonical one.
871 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
872
873protected:
874 /// \brief Returns the next redeclaration or itself if this is the only decl.
875 ///
876 /// Decl subclasses that can be redeclared should override this method so that
877 /// Decl::redecl_iterator can iterate over them.
878 virtual Decl *getNextRedeclarationImpl() { return this; }
879
880 /// \brief Implementation of getPreviousDecl(), to be overridden by any
881 /// subclass that has a redeclaration chain.
882 virtual Decl *getPreviousDeclImpl() { return nullptr; }
883
884 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
885 /// subclass that has a redeclaration chain.
886 virtual Decl *getMostRecentDeclImpl() { return this; }
887
888public:
889 /// \brief Iterates through all the redeclarations of the same decl.
890 class redecl_iterator {
891 /// Current - The current declaration.
892 Decl *Current = nullptr;
893 Decl *Starter;
894
895 public:
896 using value_type = Decl *;
897 using reference = const value_type &;
898 using pointer = const value_type *;
899 using iterator_category = std::forward_iterator_tag;
900 using difference_type = std::ptrdiff_t;
901
902 redecl_iterator() = default;
903 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
904
905 reference operator*() const { return Current; }
906 value_type operator->() const { return Current; }
907
908 redecl_iterator& operator++() {
909 assert(Current && "Advancing while iterator has reached end")(static_cast <bool> (Current && "Advancing while iterator has reached end"
) ? void (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 909, __extension__ __PRETTY_FUNCTION__))
;
910 // Get either previous decl or latest decl.
911 Decl *Next = Current->getNextRedeclarationImpl();
912 assert(Next && "Should return next redeclaration or itself, never null!")(static_cast <bool> (Next && "Should return next redeclaration or itself, never null!"
) ? void (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 912, __extension__ __PRETTY_FUNCTION__))
;
913 Current = (Next != Starter) ? Next : nullptr;
914 return *this;
915 }
916
917 redecl_iterator operator++(int) {
918 redecl_iterator tmp(*this);
919 ++(*this);
920 return tmp;
921 }
922
923 friend bool operator==(redecl_iterator x, redecl_iterator y) {
924 return x.Current == y.Current;
925 }
926
927 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
928 return x.Current != y.Current;
929 }
930 };
931
932 using redecl_range = llvm::iterator_range<redecl_iterator>;
933
934 /// \brief Returns an iterator range for all the redeclarations of the same
935 /// decl. It will iterate at least once (when this decl is the only one).
936 redecl_range redecls() const {
937 return redecl_range(redecls_begin(), redecls_end());
938 }
939
940 redecl_iterator redecls_begin() const {
941 return redecl_iterator(const_cast<Decl *>(this));
942 }
943
944 redecl_iterator redecls_end() const { return redecl_iterator(); }
945
946 /// \brief Retrieve the previous declaration that declares the same entity
947 /// as this declaration, or NULL if there is no previous declaration.
948 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
949
950 /// \brief Retrieve the most recent declaration that declares the same entity
951 /// as this declaration, or NULL if there is no previous declaration.
952 const Decl *getPreviousDecl() const {
953 return const_cast<Decl *>(this)->getPreviousDeclImpl();
954 }
955
956 /// \brief True if this is the first declaration in its redeclaration chain.
957 bool isFirstDecl() const {
958 return getPreviousDecl() == nullptr;
959 }
960
961 /// \brief Retrieve the most recent declaration that declares the same entity
962 /// as this declaration (which may be this declaration).
963 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
964
965 /// \brief Retrieve the most recent declaration that declares the same entity
966 /// as this declaration (which may be this declaration).
967 const Decl *getMostRecentDecl() const {
968 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
969 }
970
971 /// getBody - If this Decl represents a declaration for a body of code,
972 /// such as a function or method definition, this method returns the
973 /// top-level Stmt* of that body. Otherwise this method returns null.
974 virtual Stmt* getBody() const { return nullptr; }
975
976 /// \brief Returns true if this \c Decl represents a declaration for a body of
977 /// code, such as a function or method definition.
978 /// Note that \c hasBody can also return true if any redeclaration of this
979 /// \c Decl represents a declaration for a body of code.
980 virtual bool hasBody() const { return getBody() != nullptr; }
981
982 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
983 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
984 SourceLocation getBodyRBrace() const;
985
986 // global temp stats (until we have a per-module visitor)
987 static void add(Kind k);
988 static void EnableStatistics();
989 static void PrintStats();
990
991 /// isTemplateParameter - Determines whether this declaration is a
992 /// template parameter.
993 bool isTemplateParameter() const;
994
995 /// isTemplateParameter - Determines whether this declaration is a
996 /// template parameter pack.
997 bool isTemplateParameterPack() const;
998
999 /// \brief Whether this declaration is a parameter pack.
1000 bool isParameterPack() const;
1001
1002 /// \brief returns true if this declaration is a template
1003 bool isTemplateDecl() const;
1004
1005 /// \brief Whether this declaration is a function or function template.
1006 bool isFunctionOrFunctionTemplate() const {
1007 return (DeclKind >= Decl::firstFunction &&
1008 DeclKind <= Decl::lastFunction) ||
1009 DeclKind == FunctionTemplate;
1010 }
1011
1012 /// \brief If this is a declaration that describes some template, this
1013 /// method returns that template declaration.
1014 TemplateDecl *getDescribedTemplate() const;
1015
1016 /// \brief Returns the function itself, or the templated function if this is a
1017 /// function template.
1018 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1019
1020 const FunctionDecl *getAsFunction() const {
1021 return const_cast<Decl *>(this)->getAsFunction();
1022 }
1023
1024 /// \brief Changes the namespace of this declaration to reflect that it's
1025 /// a function-local extern declaration.
1026 ///
1027 /// These declarations appear in the lexical context of the extern
1028 /// declaration, but in the semantic context of the enclosing namespace
1029 /// scope.
1030 void setLocalExternDecl() {
1031 Decl *Prev = getPreviousDecl();
1032 IdentifierNamespace &= ~IDNS_Ordinary;
1033
1034 // It's OK for the declaration to still have the "invisible friend" flag or
1035 // the "conflicts with tag declarations in this scope" flag for the outer
1036 // scope.
1037 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1038, __extension__ __PRETTY_FUNCTION__))
1038 "namespace is not ordinary")(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1038, __extension__ __PRETTY_FUNCTION__))
;
1039
1040 IdentifierNamespace |= IDNS_LocalExtern;
1041 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1042 IdentifierNamespace |= IDNS_Ordinary;
1043 }
1044
1045 /// \brief Determine whether this is a block-scope declaration with linkage.
1046 /// This will either be a local variable declaration declared 'extern', or a
1047 /// local function declaration.
1048 bool isLocalExternDecl() {
1049 return IdentifierNamespace & IDNS_LocalExtern;
1050 }
1051
1052 /// \brief Changes the namespace of this declaration to reflect that it's
1053 /// the object of a friend declaration.
1054 ///
1055 /// These declarations appear in the lexical context of the friending
1056 /// class, but in the semantic context of the actual entity. This property
1057 /// applies only to a specific decl object; other redeclarations of the
1058 /// same entity may not (and probably don't) share this property.
1059 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1060 unsigned OldNS = IdentifierNamespace;
1061 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1064, __extension__ __PRETTY_FUNCTION__))
1062 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1064, __extension__ __PRETTY_FUNCTION__))
1063 IDNS_LocalExtern)) &&(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1064, __extension__ __PRETTY_FUNCTION__))
1064 "namespace includes neither ordinary nor tag")(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1064, __extension__ __PRETTY_FUNCTION__))
;
1065 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
1066 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
1067 IDNS_LocalExtern)) &&(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
1068 "namespace includes other than ordinary or tag")(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
;
1069
1070 Decl *Prev = getPreviousDecl();
1071 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1072
1073 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1074 IdentifierNamespace |= IDNS_TagFriend;
1075 if (PerformFriendInjection ||
1076 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1077 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1078 }
1079
1080 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
1081 IdentifierNamespace |= IDNS_OrdinaryFriend;
1082 if (PerformFriendInjection ||
1083 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1084 IdentifierNamespace |= IDNS_Ordinary;
1085 }
1086 }
1087
1088 enum FriendObjectKind {
1089 FOK_None, ///< Not a friend object.
1090 FOK_Declared, ///< A friend of a previously-declared entity.
1091 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1092 };
1093
1094 /// \brief Determines whether this declaration is the object of a
1095 /// friend declaration and, if so, what kind.
1096 ///
1097 /// There is currently no direct way to find the associated FriendDecl.
1098 FriendObjectKind getFriendObjectKind() const {
1099 unsigned mask =
1100 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1101 if (!mask) return FOK_None;
1102 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1103 : FOK_Undeclared);
1104 }
1105
1106 /// Specifies that this declaration is a C++ overloaded non-member.
1107 void setNonMemberOperator() {
1108 assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast <bool> (getKind() == Function || getKind()
== FunctionTemplate) ? void (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
;
1109 assert((IdentifierNamespace & IDNS_Ordinary) &&(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1110, __extension__ __PRETTY_FUNCTION__))
1110 "visible non-member operators should be in ordinary namespace")(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1110, __extension__ __PRETTY_FUNCTION__))
;
1111 IdentifierNamespace |= IDNS_NonMemberOperator;
1112 }
1113
1114 static bool classofKind(Kind K) { return true; }
1115 static DeclContext *castToDeclContext(const Decl *);
1116 static Decl *castFromDeclContext(const DeclContext *);
1117
1118 void print(raw_ostream &Out, unsigned Indentation = 0,
1119 bool PrintInstantiation = false) const;
1120 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1121 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1122 static void printGroup(Decl** Begin, unsigned NumDecls,
1123 raw_ostream &Out, const PrintingPolicy &Policy,
1124 unsigned Indentation = 0);
1125
1126 // Debuggers don't usually respect default arguments.
1127 void dump() const;
1128
1129 // Same as dump(), but forces color printing.
1130 void dumpColor() const;
1131
1132 void dump(raw_ostream &Out, bool Deserialize = false) const;
1133
1134 /// \brief Looks through the Decl's underlying type to extract a FunctionType
1135 /// when possible. Will return null if the type underlying the Decl does not
1136 /// have a FunctionType.
1137 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1138
1139private:
1140 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1141 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1142 ASTContext &Ctx);
1143
1144protected:
1145 ASTMutationListener *getASTMutationListener() const;
1146};
1147
1148/// \brief Determine whether two declarations declare the same entity.
1149inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1150 if (!D1 || !D2)
1151 return false;
1152
1153 if (D1 == D2)
1154 return true;
1155
1156 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1157}
1158
1159/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1160/// doing something to a specific decl.
1161class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1162 const Decl *TheDecl;
1163 SourceLocation Loc;
1164 SourceManager &SM;
1165 const char *Message;
1166
1167public:
1168 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1169 SourceManager &sm, const char *Msg)
1170 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1171
1172 void print(raw_ostream &OS) const override;
1173};
1174
1175/// \brief The results of name lookup within a DeclContext. This is either a
1176/// single result (with no stable storage) or a collection of results (with
1177/// stable storage provided by the lookup table).
1178class DeclContextLookupResult {
1179 using ResultTy = ArrayRef<NamedDecl *>;
1180
1181 ResultTy Result;
1182
1183 // If there is only one lookup result, it would be invalidated by
1184 // reallocations of the name table, so store it separately.
1185 NamedDecl *Single = nullptr;
1186
1187 static NamedDecl *const SingleElementDummyList;
1188
1189public:
1190 DeclContextLookupResult() = default;
1191 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1192 : Result(Result) {}
1193 DeclContextLookupResult(NamedDecl *Single)
1194 : Result(SingleElementDummyList), Single(Single) {}
1195
1196 class iterator;
1197
1198 using IteratorBase =
1199 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1200 std::random_access_iterator_tag,
1201 NamedDecl *const>;
1202
1203 class iterator : public IteratorBase {
1204 value_type SingleElement;
1205
1206 public:
1207 iterator() = default;
1208 explicit iterator(pointer Pos, value_type Single = nullptr)
1209 : IteratorBase(Pos), SingleElement(Single) {}
1210
1211 reference operator*() const {
1212 return SingleElement ? SingleElement : IteratorBase::operator*();
1213 }
1214 };
1215
1216 using const_iterator = iterator;
1217 using pointer = iterator::pointer;
1218 using reference = iterator::reference;
1219
1220 iterator begin() const { return iterator(Result.begin(), Single); }
1221 iterator end() const { return iterator(Result.end(), Single); }
1222
1223 bool empty() const { return Result.empty(); }
1224 pointer data() const { return Single ? &Single : Result.data(); }
1225 size_t size() const { return Single ? 1 : Result.size(); }
1226 reference front() const { return Single ? Single : Result.front(); }
1227 reference back() const { return Single ? Single : Result.back(); }
1228 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1229
1230 // FIXME: Remove this from the interface
1231 DeclContextLookupResult slice(size_t N) const {
1232 DeclContextLookupResult Sliced = Result.slice(N);
1233 Sliced.Single = Single;
1234 return Sliced;
1235 }
1236};
1237
1238/// DeclContext - This is used only as base class of specific decl types that
1239/// can act as declaration contexts. These decls are (only the top classes
1240/// that directly derive from DeclContext are mentioned, not their subclasses):
1241///
1242/// TranslationUnitDecl
1243/// NamespaceDecl
1244/// FunctionDecl
1245/// TagDecl
1246/// ObjCMethodDecl
1247/// ObjCContainerDecl
1248/// LinkageSpecDecl
1249/// ExportDecl
1250/// BlockDecl
1251/// OMPDeclareReductionDecl
1252class DeclContext {
1253 /// DeclKind - This indicates which class this is.
1254 unsigned DeclKind : 8;
1255
1256 /// \brief Whether this declaration context also has some external
1257 /// storage that contains additional declarations that are lexically
1258 /// part of this context.
1259 mutable bool ExternalLexicalStorage : 1;
1260
1261 /// \brief Whether this declaration context also has some external
1262 /// storage that contains additional declarations that are visible
1263 /// in this context.
1264 mutable bool ExternalVisibleStorage : 1;
1265
1266 /// \brief Whether this declaration context has had external visible
1267 /// storage added since the last lookup. In this case, \c LookupPtr's
1268 /// invariant may not hold and needs to be fixed before we perform
1269 /// another lookup.
1270 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1271
1272 /// \brief If \c true, this context may have local lexical declarations
1273 /// that are missing from the lookup table.
1274 mutable bool HasLazyLocalLexicalLookups : 1;
1275
1276 /// \brief If \c true, the external source may have lexical declarations
1277 /// that are missing from the lookup table.
1278 mutable bool HasLazyExternalLexicalLookups : 1;
1279
1280 /// \brief If \c true, lookups should only return identifier from
1281 /// DeclContext scope (for example TranslationUnit). Used in
1282 /// LookupQualifiedName()
1283 mutable bool UseQualifiedLookup : 1;
1284
1285 /// \brief Pointer to the data structure used to lookup declarations
1286 /// within this context (or a DependentStoredDeclsMap if this is a
1287 /// dependent context). We maintain the invariant that, if the map
1288 /// contains an entry for a DeclarationName (and we haven't lazily
1289 /// omitted anything), then it contains all relevant entries for that
1290 /// name (modulo the hasExternalDecls() flag).
1291 mutable StoredDeclsMap *LookupPtr = nullptr;
1292
1293protected:
1294 friend class ASTDeclReader;
1295 friend class ASTWriter;
1296 friend class ExternalASTSource;
1297
1298 /// FirstDecl - The first declaration stored within this declaration
1299 /// context.
1300 mutable Decl *FirstDecl = nullptr;
1301
1302 /// LastDecl - The last declaration stored within this declaration
1303 /// context. FIXME: We could probably cache this value somewhere
1304 /// outside of the DeclContext, to reduce the size of DeclContext by
1305 /// another pointer.
1306 mutable Decl *LastDecl = nullptr;
1307
1308 /// \brief Build up a chain of declarations.
1309 ///
1310 /// \returns the first/last pair of declarations.
1311 static std::pair<Decl *, Decl *>
1312 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1313
1314 DeclContext(Decl::Kind K)
1315 : DeclKind(K), ExternalLexicalStorage(false),
1316 ExternalVisibleStorage(false),
1317 NeedToReconcileExternalVisibleStorage(false),
1318 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1319 UseQualifiedLookup(false) {}
1320
1321public:
1322 ~DeclContext();
1323
1324 Decl::Kind getDeclKind() const {
1325 return static_cast<Decl::Kind>(DeclKind);
1326 }
1327
1328 const char *getDeclKindName() const;
1329
1330 /// getParent - Returns the containing DeclContext.
1331 DeclContext *getParent() {
1332 return cast<Decl>(this)->getDeclContext();
1333 }
1334 const DeclContext *getParent() const {
1335 return const_cast<DeclContext*>(this)->getParent();
1336 }
1337
1338 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1339 /// different from getParent, e.g.:
1340 ///
1341 /// namespace A {
1342 /// struct S;
1343 /// }
1344 /// struct A::S {}; // getParent() == namespace 'A'
1345 /// // getLexicalParent() == translation unit
1346 ///
1347 DeclContext *getLexicalParent() {
1348 return cast<Decl>(this)->getLexicalDeclContext();
1349 }
1350 const DeclContext *getLexicalParent() const {
1351 return const_cast<DeclContext*>(this)->getLexicalParent();
1352 }
1353
1354 DeclContext *getLookupParent();
1355
1356 const DeclContext *getLookupParent() const {
1357 return const_cast<DeclContext*>(this)->getLookupParent();
1358 }
1359
1360 ASTContext &getParentASTContext() const {
1361 return cast<Decl>(this)->getASTContext();
1362 }
1363
1364 bool isClosure() const {
1365 return DeclKind == Decl::Block;
1366 }
1367
1368 bool isObjCContainer() const {
1369 switch (DeclKind) {
1370 case Decl::ObjCCategory:
1371 case Decl::ObjCCategoryImpl:
1372 case Decl::ObjCImplementation:
1373 case Decl::ObjCInterface:
1374 case Decl::ObjCProtocol:
1375 return true;
1376 }
1377 return false;
1378 }
1379
1380 bool isFunctionOrMethod() const {
1381 switch (DeclKind) {
1382 case Decl::Block:
1383 case Decl::Captured:
1384 case Decl::ObjCMethod:
1385 return true;
1386 default:
1387 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1388 }
1389 }
1390
1391 /// \brief Test whether the context supports looking up names.
1392 bool isLookupContext() const {
1393 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
1394 DeclKind != Decl::Export;
1395 }
1396
1397 bool isFileContext() const {
1398 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1399 }
1400
1401 bool isTranslationUnit() const {
1402 return DeclKind == Decl::TranslationUnit;
1403 }
1404
1405 bool isRecord() const {
1406 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1407 }
1408
1409 bool isNamespace() const {
1410 return DeclKind == Decl::Namespace;
1411 }
1412
1413 bool isStdNamespace() const;
1414
1415 bool isInlineNamespace() const;
1416
1417 /// \brief Determines whether this context is dependent on a
1418 /// template parameter.
1419 bool isDependentContext() const;
1420
1421 /// isTransparentContext - Determines whether this context is a
1422 /// "transparent" context, meaning that the members declared in this
1423 /// context are semantically declared in the nearest enclosing
1424 /// non-transparent (opaque) context but are lexically declared in
1425 /// this context. For example, consider the enumerators of an
1426 /// enumeration type:
1427 /// @code
1428 /// enum E {
1429 /// Val1
1430 /// };
1431 /// @endcode
1432 /// Here, E is a transparent context, so its enumerator (Val1) will
1433 /// appear (semantically) that it is in the same context of E.
1434 /// Examples of transparent contexts include: enumerations (except for
1435 /// C++0x scoped enums), and C++ linkage specifications.
1436 bool isTransparentContext() const;
1437
1438 /// \brief Determines whether this context or some of its ancestors is a
1439 /// linkage specification context that specifies C linkage.
1440 bool isExternCContext() const;
1441
1442 /// \brief Retrieve the nearest enclosing C linkage specification context.
1443 const LinkageSpecDecl *getExternCContext() const;
1444
1445 /// \brief Determines whether this context or some of its ancestors is a
1446 /// linkage specification context that specifies C++ linkage.
1447 bool isExternCXXContext() const;
1448
1449 /// \brief Determine whether this declaration context is equivalent
1450 /// to the declaration context DC.
1451 bool Equals(const DeclContext *DC) const {
1452 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1453 }
1454
1455 /// \brief Determine whether this declaration context encloses the
1456 /// declaration context DC.
1457 bool Encloses(const DeclContext *DC) const;
1458
1459 /// \brief Find the nearest non-closure ancestor of this context,
1460 /// i.e. the innermost semantic parent of this context which is not
1461 /// a closure. A context may be its own non-closure ancestor.
1462 Decl *getNonClosureAncestor();
1463 const Decl *getNonClosureAncestor() const {
1464 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1465 }
1466
1467 /// getPrimaryContext - There may be many different
1468 /// declarations of the same entity (including forward declarations
1469 /// of classes, multiple definitions of namespaces, etc.), each with
1470 /// a different set of declarations. This routine returns the
1471 /// "primary" DeclContext structure, which will contain the
1472 /// information needed to perform name lookup into this context.
1473 DeclContext *getPrimaryContext();
1474 const DeclContext *getPrimaryContext() const {
1475 return const_cast<DeclContext*>(this)->getPrimaryContext();
1476 }
1477
1478 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1479 /// other entities of the same name, or where it is a redeclaration if the
1480 /// two entities are compatible. This skips through transparent contexts.
1481 DeclContext *getRedeclContext();
1482 const DeclContext *getRedeclContext() const {
1483 return const_cast<DeclContext *>(this)->getRedeclContext();
1484 }
1485
1486 /// \brief Retrieve the nearest enclosing namespace context.
1487 DeclContext *getEnclosingNamespaceContext();
1488 const DeclContext *getEnclosingNamespaceContext() const {
1489 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1490 }
1491
1492 /// \brief Retrieve the outermost lexically enclosing record context.
1493 RecordDecl *getOuterLexicalRecordContext();
1494 const RecordDecl *getOuterLexicalRecordContext() const {
1495 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1496 }
1497
1498 /// \brief Test if this context is part of the enclosing namespace set of
1499 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1500 /// isn't a namespace, this is equivalent to Equals().
1501 ///
1502 /// The enclosing namespace set of a namespace is the namespace and, if it is
1503 /// inline, its enclosing namespace, recursively.
1504 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1505
1506 /// \brief Collects all of the declaration contexts that are semantically
1507 /// connected to this declaration context.
1508 ///
1509 /// For declaration contexts that have multiple semantically connected but
1510 /// syntactically distinct contexts, such as C++ namespaces, this routine
1511 /// retrieves the complete set of such declaration contexts in source order.
1512 /// For example, given:
1513 ///
1514 /// \code
1515 /// namespace N {
1516 /// int x;
1517 /// }
1518 /// namespace N {
1519 /// int y;
1520 /// }
1521 /// \endcode
1522 ///
1523 /// The \c Contexts parameter will contain both definitions of N.
1524 ///
1525 /// \param Contexts Will be cleared and set to the set of declaration
1526 /// contexts that are semanticaly connected to this declaration context,
1527 /// in source order, including this context (which may be the only result,
1528 /// for non-namespace contexts).
1529 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1530
1531 /// decl_iterator - Iterates through the declarations stored
1532 /// within this context.
1533 class decl_iterator {
1534 /// Current - The current declaration.
1535 Decl *Current = nullptr;
1536
1537 public:
1538 using value_type = Decl *;
1539 using reference = const value_type &;
1540 using pointer = const value_type *;
1541 using iterator_category = std::forward_iterator_tag;
1542 using difference_type = std::ptrdiff_t;
1543
1544 decl_iterator() = default;
1545 explicit decl_iterator(Decl *C) : Current(C) {}
1546
1547 reference operator*() const { return Current; }
1548
1549 // This doesn't meet the iterator requirements, but it's convenient
1550 value_type operator->() const { return Current; }
1551
1552 decl_iterator& operator++() {
1553 Current = Current->getNextDeclInContext();
1554 return *this;
1555 }
1556
1557 decl_iterator operator++(int) {
1558 decl_iterator tmp(*this);
1559 ++(*this);
1560 return tmp;
1561 }
1562
1563 friend bool operator==(decl_iterator x, decl_iterator y) {
1564 return x.Current == y.Current;
1565 }
1566
1567 friend bool operator!=(decl_iterator x, decl_iterator y) {
1568 return x.Current != y.Current;
1569 }
1570 };
1571
1572 using decl_range = llvm::iterator_range<decl_iterator>;
1573
1574 /// decls_begin/decls_end - Iterate over the declarations stored in
1575 /// this context.
1576 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1577 decl_iterator decls_begin() const;
1578 decl_iterator decls_end() const { return decl_iterator(); }
1579 bool decls_empty() const;
1580
1581 /// noload_decls_begin/end - Iterate over the declarations stored in this
1582 /// context that are currently loaded; don't attempt to retrieve anything
1583 /// from an external source.
1584 decl_range noload_decls() const {
1585 return decl_range(noload_decls_begin(), noload_decls_end());
1586 }
1587 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1588 decl_iterator noload_decls_end() const { return decl_iterator(); }
1589
1590 /// specific_decl_iterator - Iterates over a subrange of
1591 /// declarations stored in a DeclContext, providing only those that
1592 /// are of type SpecificDecl (or a class derived from it). This
1593 /// iterator is used, for example, to provide iteration over just
1594 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1595 template<typename SpecificDecl>
1596 class specific_decl_iterator {
1597 /// Current - The current, underlying declaration iterator, which
1598 /// will either be NULL or will point to a declaration of
1599 /// type SpecificDecl.
1600 DeclContext::decl_iterator Current;
1601
1602 /// SkipToNextDecl - Advances the current position up to the next
1603 /// declaration of type SpecificDecl that also meets the criteria
1604 /// required by Acceptable.
1605 void SkipToNextDecl() {
1606 while (*Current && !isa<SpecificDecl>(*Current))
1607 ++Current;
1608 }
1609
1610 public:
1611 using value_type = SpecificDecl *;
1612 // TODO: Add reference and pointer types (with some appropriate proxy type)
1613 // if we ever have a need for them.
1614 using reference = void;
1615 using pointer = void;
1616 using difference_type =
1617 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
1618 using iterator_category = std::forward_iterator_tag;
1619
1620 specific_decl_iterator() = default;
1621
1622 /// specific_decl_iterator - Construct a new iterator over a
1623 /// subset of the declarations the range [C,
1624 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1625 /// member function of SpecificDecl that should return true for
1626 /// all of the SpecificDecl instances that will be in the subset
1627 /// of iterators. For example, if you want Objective-C instance
1628 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1629 /// &ObjCMethodDecl::isInstanceMethod.
1630 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1631 SkipToNextDecl();
1632 }
1633
1634 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1635
1636 // This doesn't meet the iterator requirements, but it's convenient
1637 value_type operator->() const { return **this; }
1638
1639 specific_decl_iterator& operator++() {
1640 ++Current;
1641 SkipToNextDecl();
1642 return *this;
1643 }
1644
1645 specific_decl_iterator operator++(int) {
1646 specific_decl_iterator tmp(*this);
1647 ++(*this);
1648 return tmp;
1649 }
1650
1651 friend bool operator==(const specific_decl_iterator& x,
1652 const specific_decl_iterator& y) {
1653 return x.Current == y.Current;
1654 }
1655
1656 friend bool operator!=(const specific_decl_iterator& x,
1657 const specific_decl_iterator& y) {
1658 return x.Current != y.Current;
1659 }
1660 };
1661
1662 /// \brief Iterates over a filtered subrange of declarations stored
1663 /// in a DeclContext.
1664 ///
1665 /// This iterator visits only those declarations that are of type
1666 /// SpecificDecl (or a class derived from it) and that meet some
1667 /// additional run-time criteria. This iterator is used, for
1668 /// example, to provide access to the instance methods within an
1669 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1670 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1671 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1672 class filtered_decl_iterator {
1673 /// Current - The current, underlying declaration iterator, which
1674 /// will either be NULL or will point to a declaration of
1675 /// type SpecificDecl.
1676 DeclContext::decl_iterator Current;
1677
1678 /// SkipToNextDecl - Advances the current position up to the next
1679 /// declaration of type SpecificDecl that also meets the criteria
1680 /// required by Acceptable.
1681 void SkipToNextDecl() {
1682 while (*Current &&
1683 (!isa<SpecificDecl>(*Current) ||
1684 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1685 ++Current;
1686 }
1687
1688 public:
1689 using value_type = SpecificDecl *;
1690 // TODO: Add reference and pointer types (with some appropriate proxy type)
1691 // if we ever have a need for them.
1692 using reference = void;
1693 using pointer = void;
1694 using difference_type =
1695 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
1696 using iterator_category = std::forward_iterator_tag;
1697
1698 filtered_decl_iterator() = default;
1699
1700 /// filtered_decl_iterator - Construct a new iterator over a
1701 /// subset of the declarations the range [C,
1702 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1703 /// member function of SpecificDecl that should return true for
1704 /// all of the SpecificDecl instances that will be in the subset
1705 /// of iterators. For example, if you want Objective-C instance
1706 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1707 /// &ObjCMethodDecl::isInstanceMethod.
1708 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1709 SkipToNextDecl();
1710 }
1711
1712 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1713 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1714
1715 filtered_decl_iterator& operator++() {
1716 ++Current;
1717 SkipToNextDecl();
1718 return *this;
1719 }
1720
1721 filtered_decl_iterator operator++(int) {
1722 filtered_decl_iterator tmp(*this);
1723 ++(*this);
1724 return tmp;
1725 }
1726
1727 friend bool operator==(const filtered_decl_iterator& x,
1728 const filtered_decl_iterator& y) {
1729 return x.Current == y.Current;
1730 }
1731
1732 friend bool operator!=(const filtered_decl_iterator& x,
1733 const filtered_decl_iterator& y) {
1734 return x.Current != y.Current;
1735 }
1736 };
1737
1738 /// @brief Add the declaration D into this context.
1739 ///
1740 /// This routine should be invoked when the declaration D has first
1741 /// been declared, to place D into the context where it was
1742 /// (lexically) defined. Every declaration must be added to one
1743 /// (and only one!) context, where it can be visited via
1744 /// [decls_begin(), decls_end()). Once a declaration has been added
1745 /// to its lexical context, the corresponding DeclContext owns the
1746 /// declaration.
1747 ///
1748 /// If D is also a NamedDecl, it will be made visible within its
1749 /// semantic context via makeDeclVisibleInContext.
1750 void addDecl(Decl *D);
1751
1752 /// @brief Add the declaration D into this context, but suppress
1753 /// searches for external declarations with the same name.
1754 ///
1755 /// Although analogous in function to addDecl, this removes an
1756 /// important check. This is only useful if the Decl is being
1757 /// added in response to an external search; in all other cases,
1758 /// addDecl() is the right function to use.
1759 /// See the ASTImporter for use cases.
1760 void addDeclInternal(Decl *D);
1761
1762 /// @brief Add the declaration D to this context without modifying
1763 /// any lookup tables.
1764 ///
1765 /// This is useful for some operations in dependent contexts where
1766 /// the semantic context might not be dependent; this basically
1767 /// only happens with friends.
1768 void addHiddenDecl(Decl *D);
1769
1770 /// @brief Removes a declaration from this context.
1771 void removeDecl(Decl *D);
1772
1773 /// @brief Checks whether a declaration is in this context.
1774 bool containsDecl(Decl *D) const;
1775
1776 using lookup_result = DeclContextLookupResult;
1777 using lookup_iterator = lookup_result::iterator;
1778
1779 /// lookup - Find the declarations (if any) with the given Name in
1780 /// this context. Returns a range of iterators that contains all of
1781 /// the declarations with this name, with object, function, member,
1782 /// and enumerator names preceding any tag name. Note that this
1783 /// routine will not look into parent contexts.
1784 lookup_result lookup(DeclarationName Name) const;
1785
1786 /// \brief Find the declarations with the given name that are visible
1787 /// within this context; don't attempt to retrieve anything from an
1788 /// external source.
1789 lookup_result noload_lookup(DeclarationName Name);
1790
1791 /// \brief A simplistic name lookup mechanism that performs name lookup
1792 /// into this declaration context without consulting the external source.
1793 ///
1794 /// This function should almost never be used, because it subverts the
1795 /// usual relationship between a DeclContext and the external source.
1796 /// See the ASTImporter for the (few, but important) use cases.
1797 ///
1798 /// FIXME: This is very inefficient; replace uses of it with uses of
1799 /// noload_lookup.
1800 void localUncachedLookup(DeclarationName Name,
1801 SmallVectorImpl<NamedDecl *> &Results);
1802
1803 /// @brief Makes a declaration visible within this context.
1804 ///
1805 /// This routine makes the declaration D visible to name lookup
1806 /// within this context and, if this is a transparent context,
1807 /// within its parent contexts up to the first enclosing
1808 /// non-transparent context. Making a declaration visible within a
1809 /// context does not transfer ownership of a declaration, and a
1810 /// declaration can be visible in many contexts that aren't its
1811 /// lexical context.
1812 ///
1813 /// If D is a redeclaration of an existing declaration that is
1814 /// visible from this context, as determined by
1815 /// NamedDecl::declarationReplaces, the previous declaration will be
1816 /// replaced with D.
1817 void makeDeclVisibleInContext(NamedDecl *D);
1818
1819 /// all_lookups_iterator - An iterator that provides a view over the results
1820 /// of looking up every possible name.
1821 class all_lookups_iterator;
1822
1823 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
1824
1825 lookups_range lookups() const;
1826 lookups_range noload_lookups() const;
1827
1828 /// \brief Iterators over all possible lookups within this context.
1829 all_lookups_iterator lookups_begin() const;
1830 all_lookups_iterator lookups_end() const;
1831
1832 /// \brief Iterators over all possible lookups within this context that are
1833 /// currently loaded; don't attempt to retrieve anything from an external
1834 /// source.
1835 all_lookups_iterator noload_lookups_begin() const;
1836 all_lookups_iterator noload_lookups_end() const;
1837
1838 struct udir_iterator;
1839
1840 using udir_iterator_base =
1841 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1842 std::random_access_iterator_tag,
1843 UsingDirectiveDecl *>;
1844
1845 struct udir_iterator : udir_iterator_base {
1846 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1847
1848 UsingDirectiveDecl *operator*() const;
1849 };
1850
1851 using udir_range = llvm::iterator_range<udir_iterator>;
1852
1853 udir_range using_directives() const;
1854
1855 // These are all defined in DependentDiagnostic.h.
1856 class ddiag_iterator;
1857
1858 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
1859
1860 inline ddiag_range ddiags() const;
1861
1862 // Low-level accessors
1863
1864 /// \brief Mark that there are external lexical declarations that we need
1865 /// to include in our lookup table (and that are not available as external
1866 /// visible lookups). These extra lookup results will be found by walking
1867 /// the lexical declarations of this context. This should be used only if
1868 /// setHasExternalLexicalStorage() has been called on any decl context for
1869 /// which this is the primary context.
1870 void setMustBuildLookupTable() {
1871 assert(this == getPrimaryContext() &&(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1872, __extension__ __PRETTY_FUNCTION__))
1872 "should only be called on primary context")(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/DeclBase.h"
, 1872, __extension__ __PRETTY_FUNCTION__))
;
1873 HasLazyExternalLexicalLookups = true;
1874 }
1875
1876 /// \brief Retrieve the internal representation of the lookup structure.
1877 /// This may omit some names if we are lazily building the structure.
1878 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1879
1880 /// \brief Ensure the lookup structure is fully-built and return it.
1881 StoredDeclsMap *buildLookup();
1882
1883 /// \brief Whether this DeclContext has external storage containing
1884 /// additional declarations that are lexically in this context.
1885 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1886
1887 /// \brief State whether this DeclContext has external storage for
1888 /// declarations lexically in this context.
1889 void setHasExternalLexicalStorage(bool ES = true) {
1890 ExternalLexicalStorage = ES;
1891 }
1892
1893 /// \brief Whether this DeclContext has external storage containing
1894 /// additional declarations that are visible in this context.
1895 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1896
1897 /// \brief State whether this DeclContext has external storage for
1898 /// declarations visible in this context.
1899 void setHasExternalVisibleStorage(bool ES = true) {
1900 ExternalVisibleStorage = ES;
1901 if (ES && LookupPtr)
1902 NeedToReconcileExternalVisibleStorage = true;
1903 }
1904
1905 /// \brief Determine whether the given declaration is stored in the list of
1906 /// declarations lexically within this context.
1907 bool isDeclInLexicalTraversal(const Decl *D) const {
1908 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1909 D == LastDecl);
1910 }
1911
1912 bool setUseQualifiedLookup(bool use = true) {
1913 bool old_value = UseQualifiedLookup;
1914 UseQualifiedLookup = use;
1915 return old_value;
1916 }
1917
1918 bool shouldUseQualifiedLookup() const {
1919 return UseQualifiedLookup;
1920 }
1921
1922 static bool classof(const Decl *D);
1923 static bool classof(const DeclContext *D) { return true; }
1924
1925 void dumpDeclContext() const;
1926 void dumpLookups() const;
1927 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
1928 bool Deserialize = false) const;
1929
1930private:
1931 friend class DependentDiagnostic;
1932
1933 void reconcileExternalVisibleStorage() const;
1934 bool LoadLexicalDeclsFromExternalStorage() const;
1935
1936 /// @brief Makes a declaration visible within this context, but
1937 /// suppresses searches for external declarations with the same
1938 /// name.
1939 ///
1940 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1941 /// use of addDeclInternal().
1942 void makeDeclVisibleInContextInternal(NamedDecl *D);
1943
1944 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1945
1946 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1947 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1948 bool Rediscoverable);
1949 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1950};
1951
1952inline bool Decl::isTemplateParameter() const {
1953 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1954 getKind() == TemplateTemplateParm;
1955}
1956
1957// Specialization selected when ToTy is not a known subclass of DeclContext.
1958template <class ToTy,
1959 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1960struct cast_convert_decl_context {
1961 static const ToTy *doit(const DeclContext *Val) {
1962 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1963 }
1964
1965 static ToTy *doit(DeclContext *Val) {
1966 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1967 }
1968};
1969
1970// Specialization selected when ToTy is a known subclass of DeclContext.
1971template <class ToTy>
1972struct cast_convert_decl_context<ToTy, true> {
1973 static const ToTy *doit(const DeclContext *Val) {
1974 return static_cast<const ToTy*>(Val);
1975 }
1976
1977 static ToTy *doit(DeclContext *Val) {
1978 return static_cast<ToTy*>(Val);
1979 }
1980};
1981
1982} // namespace clang
1983
1984namespace llvm {
1985
1986/// isa<T>(DeclContext*)
1987template <typename To>
1988struct isa_impl<To, ::clang::DeclContext> {
1989 static bool doit(const ::clang::DeclContext &Val) {
1990 return To::classofKind(Val.getDeclKind());
25
Calling 'DeclContext::getDeclKind'
26
Returning from 'DeclContext::getDeclKind'
27
Calling 'NamespaceDecl::classofKind'
29
Returning from 'NamespaceDecl::classofKind'
1991 }
1992};
1993
1994/// cast<T>(DeclContext*)
1995template<class ToTy>
1996struct cast_convert_val<ToTy,
1997 const ::clang::DeclContext,const ::clang::DeclContext> {
1998 static const ToTy &doit(const ::clang::DeclContext &Val) {
1999 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2000 }
2001};
2002
2003template<class ToTy>
2004struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2005 static ToTy &doit(::clang::DeclContext &Val) {
2006 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2007 }
2008};
2009
2010template<class ToTy>
2011struct cast_convert_val<ToTy,
2012 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2013 static const ToTy *doit(const ::clang::DeclContext *Val) {
2014 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
47
Calling 'cast_convert_decl_context::doit'
48
Returning from 'cast_convert_decl_context::doit'
2015 }
2016};
2017
2018template<class ToTy>
2019struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2020 static ToTy *doit(::clang::DeclContext *Val) {
2021 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2022 }
2023};
2024
2025/// Implement cast_convert_val for Decl -> DeclContext conversions.
2026template<class FromTy>
2027struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2028 static ::clang::DeclContext &doit(const FromTy &Val) {
2029 return *FromTy::castToDeclContext(&Val);
2030 }
2031};
2032
2033template<class FromTy>
2034struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2035 static ::clang::DeclContext *doit(const FromTy *Val) {
2036 return FromTy::castToDeclContext(Val);
2037 }
2038};
2039
2040template<class FromTy>
2041struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2042 static const ::clang::DeclContext &doit(const FromTy &Val) {
2043 return *FromTy::castToDeclContext(&Val);
2044 }
2045};
2046
2047template<class FromTy>
2048struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2049 static const ::clang::DeclContext *doit(const FromTy *Val) {
2050 return FromTy::castToDeclContext(Val);
2051 }
2052};
2053
2054} // namespace llvm
2055
2056#endif // LLVM_CLANG_AST_DECLBASE_H

/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// \brief A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// \brief Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// \brief Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// TranslationUnitDecl - The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// \brief Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// \brief Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// \brief Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// NamedDecl - This represents a decl with a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245class NamedDecl : public Decl {
246 /// Name - The name of this declaration, which is typically a normal
247 /// identifier but may also be a special kind of name (C++
248 /// constructor, Objective-C selector, etc.)
249 DeclarationName Name;
250
251 virtual void anchor();
252
253private:
254 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
255
256protected:
257 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
258 : Decl(DK, DC, L), Name(N) {}
259
260public:
261 /// getIdentifier - Get the identifier that names this declaration,
262 /// if there is one. This will return NULL if this declaration has
263 /// no name (e.g., for an unnamed class) or if the name is a special
264 /// name (C++ constructor, Objective-C selector, etc.).
265 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
266
267 /// getName - Get the name of identifier for this declaration as a StringRef.
268 /// This requires that the declaration have a name and that it be a simple
269 /// identifier.
270 StringRef getName() const {
271 assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 271, __extension__ __PRETTY_FUNCTION__))
;
272 return getIdentifier() ? getIdentifier()->getName() : "";
273 }
274
275 /// getNameAsString - Get a human-readable name for the declaration, even if
276 /// it is one of the special kinds of names (C++ constructor, Objective-C
277 /// selector, etc). Creating this name requires expensive string
278 /// manipulation, so it should be called only when performance doesn't matter.
279 /// For simple declarations, getNameAsCString() should suffice.
280 //
281 // FIXME: This function should be renamed to indicate that it is not just an
282 // alternate form of getName(), and clients should move as appropriate.
283 //
284 // FIXME: Deprecated, move clients to getName().
285 std::string getNameAsString() const { return Name.getAsString(); }
286
287 virtual void printName(raw_ostream &os) const;
288
289 /// getDeclName - Get the actual, stored name of the declaration,
290 /// which may be a special name.
291 DeclarationName getDeclName() const { return Name; }
292
293 /// \brief Set the name of this declaration.
294 void setDeclName(DeclarationName N) { Name = N; }
295
296 /// printQualifiedName - Returns human-readable qualified name for
297 /// declaration, like A::B::i, for i being member of namespace A::B.
298 /// If declaration is not member of context which can be named (record,
299 /// namespace), it will return same result as printName().
300 /// Creating this name is expensive, so it should be called only when
301 /// performance doesn't matter.
302 void printQualifiedName(raw_ostream &OS) const;
303 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
304
305 // FIXME: Remove string version.
306 std::string getQualifiedNameAsString() const;
307
308 /// getNameForDiagnostic - Appends a human-readable name for this
309 /// declaration into the given stream.
310 ///
311 /// This is the method invoked by Sema when displaying a NamedDecl
312 /// in a diagnostic. It does not necessarily produce the same
313 /// result as printName(); for example, class template
314 /// specializations are printed with their template arguments.
315 virtual void getNameForDiagnostic(raw_ostream &OS,
316 const PrintingPolicy &Policy,
317 bool Qualified) const;
318
319 /// \brief Determine whether this declaration, if
320 /// known to be well-formed within its context, will replace the
321 /// declaration OldD if introduced into scope. A declaration will
322 /// replace another declaration if, for example, it is a
323 /// redeclaration of the same variable or function, but not if it is
324 /// a declaration of a different kind (function vs. class) or an
325 /// overloaded function.
326 ///
327 /// \param IsKnownNewer \c true if this declaration is known to be newer
328 /// than \p OldD (for instance, if this declaration is newly-created).
329 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
330
331 /// \brief Determine whether this declaration has linkage.
332 bool hasLinkage() const;
333
334 using Decl::isModulePrivate;
335 using Decl::setModulePrivate;
336
337 /// \brief Determine whether this declaration is a C++ class member.
338 bool isCXXClassMember() const {
339 const DeclContext *DC = getDeclContext();
340
341 // C++0x [class.mem]p1:
342 // The enumerators of an unscoped enumeration defined in
343 // the class are members of the class.
344 if (isa<EnumDecl>(DC))
345 DC = DC->getRedeclContext();
346
347 return DC->isRecord();
348 }
349
350 /// \brief Determine whether the given declaration is an instance member of
351 /// a C++ class.
352 bool isCXXInstanceMember() const;
353
354 /// \brief Determine what kind of linkage this entity has.
355 /// This is not the linkage as defined by the standard or the codegen notion
356 /// of linkage. It is just an implementation detail that is used to compute
357 /// those.
358 Linkage getLinkageInternal() const;
359
360 /// \brief Get the linkage from a semantic point of view. Entities in
361 /// anonymous namespaces are external (in c++98).
362 Linkage getFormalLinkage() const {
363 return clang::getFormalLinkage(getLinkageInternal());
364 }
365
366 /// \brief True if this decl has external linkage.
367 bool hasExternalFormalLinkage() const {
368 return isExternalFormalLinkage(getLinkageInternal());
369 }
370
371 bool isExternallyVisible() const {
372 return clang::isExternallyVisible(getLinkageInternal());
373 }
374
375 /// Determine whether this declaration can be redeclared in a
376 /// different translation unit.
377 bool isExternallyDeclarable() const {
378 return isExternallyVisible() && !getOwningModuleForLinkage();
379 }
380
381 /// \brief Determines the visibility of this entity.
382 Visibility getVisibility() const {
383 return getLinkageAndVisibility().getVisibility();
384 }
385
386 /// \brief Determines the linkage and visibility of this entity.
387 LinkageInfo getLinkageAndVisibility() const;
388
389 /// Kinds of explicit visibility.
390 enum ExplicitVisibilityKind {
391 /// Do an LV computation for, ultimately, a type.
392 /// Visibility may be restricted by type visibility settings and
393 /// the visibility of template arguments.
394 VisibilityForType,
395
396 /// Do an LV computation for, ultimately, a non-type declaration.
397 /// Visibility may be restricted by value visibility settings and
398 /// the visibility of template arguments.
399 VisibilityForValue
400 };
401
402 /// \brief If visibility was explicitly specified for this
403 /// declaration, return that visibility.
404 Optional<Visibility>
405 getExplicitVisibility(ExplicitVisibilityKind kind) const;
406
407 /// \brief True if the computed linkage is valid. Used for consistency
408 /// checking. Should always return true.
409 bool isLinkageValid() const;
410
411 /// \brief True if something has required us to compute the linkage
412 /// of this declaration.
413 ///
414 /// Language features which can retroactively change linkage (like a
415 /// typedef name for linkage purposes) may need to consider this,
416 /// but hopefully only in transitory ways during parsing.
417 bool hasLinkageBeenComputed() const {
418 return hasCachedLinkage();
419 }
420
421 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
422 /// the underlying named decl.
423 NamedDecl *getUnderlyingDecl() {
424 // Fast-path the common case.
425 if (this->getKind() != UsingShadow &&
426 this->getKind() != ConstructorUsingShadow &&
427 this->getKind() != ObjCCompatibleAlias &&
428 this->getKind() != NamespaceAlias)
429 return this;
430
431 return getUnderlyingDeclImpl();
432 }
433 const NamedDecl *getUnderlyingDecl() const {
434 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
435 }
436
437 NamedDecl *getMostRecentDecl() {
438 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
439 }
440 const NamedDecl *getMostRecentDecl() const {
441 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
442 }
443
444 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
445
446 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
447 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
448};
449
450inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
451 ND.printName(OS);
452 return OS;
453}
454
455/// LabelDecl - Represents the declaration of a label. Labels also have a
456/// corresponding LabelStmt, which indicates the position that the label was
457/// defined at. For normal labels, the location of the decl is the same as the
458/// location of the statement. For GNU local labels (__label__), the decl
459/// location is where the __label__ is.
460class LabelDecl : public NamedDecl {
461 LabelStmt *TheStmt;
462 StringRef MSAsmName;
463 bool MSAsmNameResolved = false;
464
465 /// LocStart - For normal labels, this is the same as the main declaration
466 /// label, i.e., the location of the identifier; for GNU local labels,
467 /// this is the location of the __label__ keyword.
468 SourceLocation LocStart;
469
470 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
471 LabelStmt *S, SourceLocation StartL)
472 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
473
474 void anchor() override;
475
476public:
477 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
478 SourceLocation IdentL, IdentifierInfo *II);
479 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
480 SourceLocation IdentL, IdentifierInfo *II,
481 SourceLocation GnuLabelL);
482 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
483
484 LabelStmt *getStmt() const { return TheStmt; }
485 void setStmt(LabelStmt *T) { TheStmt = T; }
486
487 bool isGnuLocal() const { return LocStart != getLocation(); }
488 void setLocStart(SourceLocation L) { LocStart = L; }
489
490 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
491 return SourceRange(LocStart, getLocation());
492 }
493
494 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
495 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
496 void setMSAsmLabel(StringRef Name);
497 StringRef getMSAsmLabel() const { return MSAsmName; }
498 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
499
500 // Implement isa/cast/dyncast/etc.
501 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
502 static bool classofKind(Kind K) { return K == Label; }
503};
504
505/// NamespaceDecl - Represent a C++ namespace.
506class NamespaceDecl : public NamedDecl, public DeclContext,
507 public Redeclarable<NamespaceDecl>
508{
509 /// LocStart - The starting location of the source range, pointing
510 /// to either the namespace or the inline keyword.
511 SourceLocation LocStart;
512
513 /// RBraceLoc - The ending location of the source range.
514 SourceLocation RBraceLoc;
515
516 /// \brief A pointer to either the anonymous namespace that lives just inside
517 /// this namespace or to the first namespace in the chain (the latter case
518 /// only when this is not the first in the chain), along with a
519 /// boolean value indicating whether this is an inline namespace.
520 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
521
522 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
523 SourceLocation StartLoc, SourceLocation IdLoc,
524 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
525
526 using redeclarable_base = Redeclarable<NamespaceDecl>;
527
528 NamespaceDecl *getNextRedeclarationImpl() override;
529 NamespaceDecl *getPreviousDeclImpl() override;
530 NamespaceDecl *getMostRecentDeclImpl() override;
531
532public:
533 friend class ASTDeclReader;
534 friend class ASTDeclWriter;
535
536 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
537 bool Inline, SourceLocation StartLoc,
538 SourceLocation IdLoc, IdentifierInfo *Id,
539 NamespaceDecl *PrevDecl);
540
541 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
542
543 using redecl_range = redeclarable_base::redecl_range;
544 using redecl_iterator = redeclarable_base::redecl_iterator;
545
546 using redeclarable_base::redecls_begin;
547 using redeclarable_base::redecls_end;
548 using redeclarable_base::redecls;
549 using redeclarable_base::getPreviousDecl;
550 using redeclarable_base::getMostRecentDecl;
551 using redeclarable_base::isFirstDecl;
552
553 /// \brief Returns true if this is an anonymous namespace declaration.
554 ///
555 /// For example:
556 /// \code
557 /// namespace {
558 /// ...
559 /// };
560 /// \endcode
561 /// q.v. C++ [namespace.unnamed]
562 bool isAnonymousNamespace() const {
563 return !getIdentifier();
564 }
565
566 /// \brief Returns true if this is an inline namespace declaration.
567 bool isInline() const {
568 return AnonOrFirstNamespaceAndInline.getInt();
569 }
570
571 /// \brief Set whether this is an inline namespace declaration.
572 void setInline(bool Inline) {
573 AnonOrFirstNamespaceAndInline.setInt(Inline);
574 }
575
576 /// \brief Get the original (first) namespace declaration.
577 NamespaceDecl *getOriginalNamespace();
578
579 /// \brief Get the original (first) namespace declaration.
580 const NamespaceDecl *getOriginalNamespace() const;
581
582 /// \brief Return true if this declaration is an original (first) declaration
583 /// of the namespace. This is false for non-original (subsequent) namespace
584 /// declarations and anonymous namespaces.
585 bool isOriginalNamespace() const;
586
587 /// \brief Retrieve the anonymous namespace nested inside this namespace,
588 /// if any.
589 NamespaceDecl *getAnonymousNamespace() const {
590 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
591 }
592
593 void setAnonymousNamespace(NamespaceDecl *D) {
594 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
595 }
596
597 /// Retrieves the canonical declaration of this namespace.
598 NamespaceDecl *getCanonicalDecl() override {
599 return getOriginalNamespace();
600 }
601 const NamespaceDecl *getCanonicalDecl() const {
602 return getOriginalNamespace();
603 }
604
605 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
606 return SourceRange(LocStart, RBraceLoc);
607 }
608
609 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
610 SourceLocation getRBraceLoc() const { return RBraceLoc; }
611 void setLocStart(SourceLocation L) { LocStart = L; }
612 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
613
614 // Implement isa/cast/dyncast/etc.
615 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
616 static bool classofKind(Kind K) { return K == Namespace; }
28
Assuming 'K' is equal to Namespace
617 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
618 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
619 }
620 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
621 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
622 }
623};
624
625/// ValueDecl - Represent the declaration of a variable (in which case it is
626/// an lvalue) a function (in which case it is a function designator) or
627/// an enum constant.
628class ValueDecl : public NamedDecl {
629 QualType DeclType;
630
631 void anchor() override;
632
633protected:
634 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
635 DeclarationName N, QualType T)
636 : NamedDecl(DK, DC, L, N), DeclType(T) {}
637
638public:
639 QualType getType() const { return DeclType; }
640 void setType(QualType newType) { DeclType = newType; }
641
642 /// \brief Determine whether this symbol is weakly-imported,
643 /// or declared with the weak or weak-ref attr.
644 bool isWeak() const;
645
646 // Implement isa/cast/dyncast/etc.
647 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
648 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
649};
650
651/// QualifierInfo - A struct with extended info about a syntactic
652/// name qualifier, to be used for the case of out-of-line declarations.
653struct QualifierInfo {
654 NestedNameSpecifierLoc QualifierLoc;
655
656 /// NumTemplParamLists - The number of "outer" template parameter lists.
657 /// The count includes all of the template parameter lists that were matched
658 /// against the template-ids occurring into the NNS and possibly (in the
659 /// case of an explicit specialization) a final "template <>".
660 unsigned NumTemplParamLists = 0;
661
662 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
663 /// containing pointers to the "outer" template parameter lists.
664 /// It includes all of the template parameter lists that were matched
665 /// against the template-ids occurring into the NNS and possibly (in the
666 /// case of an explicit specialization) a final "template <>".
667 TemplateParameterList** TemplParamLists = nullptr;
668
669 QualifierInfo() = default;
670 QualifierInfo(const QualifierInfo &) = delete;
671 QualifierInfo& operator=(const QualifierInfo &) = delete;
672
673 /// setTemplateParameterListsInfo - Sets info about "outer" template
674 /// parameter lists.
675 void setTemplateParameterListsInfo(ASTContext &Context,
676 ArrayRef<TemplateParameterList *> TPLists);
677};
678
679/// \brief Represents a ValueDecl that came out of a declarator.
680/// Contains type source information through TypeSourceInfo.
681class DeclaratorDecl : public ValueDecl {
682 // A struct representing both a TInfo and a syntactic qualifier,
683 // to be used for the (uncommon) case of out-of-line declarations.
684 struct ExtInfo : public QualifierInfo {
685 TypeSourceInfo *TInfo;
686 };
687
688 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
689
690 /// InnerLocStart - The start of the source range for this declaration,
691 /// ignoring outer template declarations.
692 SourceLocation InnerLocStart;
693
694 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
695 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
696 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
697
698protected:
699 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
700 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
701 SourceLocation StartL)
702 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
703
704public:
705 friend class ASTDeclReader;
706 friend class ASTDeclWriter;
707
708 TypeSourceInfo *getTypeSourceInfo() const {
709 return hasExtInfo()
710 ? getExtInfo()->TInfo
711 : DeclInfo.get<TypeSourceInfo*>();
712 }
713
714 void setTypeSourceInfo(TypeSourceInfo *TI) {
715 if (hasExtInfo())
716 getExtInfo()->TInfo = TI;
717 else
718 DeclInfo = TI;
719 }
720
721 /// getInnerLocStart - Return SourceLocation representing start of source
722 /// range ignoring outer template declarations.
723 SourceLocation getInnerLocStart() const { return InnerLocStart; }
724 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
725
726 /// getOuterLocStart - Return SourceLocation representing start of source
727 /// range taking into account any outer template declarations.
728 SourceLocation getOuterLocStart() const;
729
730 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
731
732 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
733 return getOuterLocStart();
734 }
735
736 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
737 /// declaration, if it was present in the source.
738 NestedNameSpecifier *getQualifier() const {
739 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
740 : nullptr;
741 }
742
743 /// \brief Retrieve the nested-name-specifier (with source-location
744 /// information) that qualifies the name of this declaration, if it was
745 /// present in the source.
746 NestedNameSpecifierLoc getQualifierLoc() const {
747 return hasExtInfo() ? getExtInfo()->QualifierLoc
748 : NestedNameSpecifierLoc();
749 }
750
751 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
752
753 unsigned getNumTemplateParameterLists() const {
754 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
755 }
756
757 TemplateParameterList *getTemplateParameterList(unsigned index) const {
758 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759 return getExtInfo()->TemplParamLists[index];
760 }
761
762 void setTemplateParameterListsInfo(ASTContext &Context,
763 ArrayRef<TemplateParameterList *> TPLists);
764
765 SourceLocation getTypeSpecStartLoc() const;
766
767 // Implement isa/cast/dyncast/etc.
768 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
769 static bool classofKind(Kind K) {
770 return K >= firstDeclarator && K <= lastDeclarator;
771 }
772};
773
774/// \brief Structure used to store a statement, the constant value to
775/// which it was evaluated (if any), and whether or not the statement
776/// is an integral constant expression (if known).
777struct EvaluatedStmt {
778 /// \brief Whether this statement was already evaluated.
779 bool WasEvaluated : 1;
780
781 /// \brief Whether this statement is being evaluated.
782 bool IsEvaluating : 1;
783
784 /// \brief Whether we already checked whether this statement was an
785 /// integral constant expression.
786 bool CheckedICE : 1;
787
788 /// \brief Whether we are checking whether this statement is an
789 /// integral constant expression.
790 bool CheckingICE : 1;
791
792 /// \brief Whether this statement is an integral constant expression,
793 /// or in C++11, whether the statement is a constant expression. Only
794 /// valid if CheckedICE is true.
795 bool IsICE : 1;
796
797 Stmt *Value;
798 APValue Evaluated;
799
800 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
801 CheckingICE(false), IsICE(false) {}
802
803};
804
805/// VarDecl - An instance of this class is created to represent a variable
806/// declaration or definition.
807class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
808public:
809 /// \brief Initialization styles.
810 enum InitializationStyle {
811 /// C-style initialization with assignment
812 CInit,
813
814 /// Call-style initialization (C++98)
815 CallInit,
816
817 /// Direct list-initialization (C++11)
818 ListInit
819 };
820
821 /// \brief Kinds of thread-local storage.
822 enum TLSKind {
823 /// Not a TLS variable.
824 TLS_None,
825
826 /// TLS with a known-constant initializer.
827 TLS_Static,
828
829 /// TLS with a dynamic initializer.
830 TLS_Dynamic
831 };
832
833 /// getStorageClassSpecifierString - Return the string used to
834 /// specify the storage class \p SC.
835 ///
836 /// It is illegal to call this function with SC == None.
837 static const char *getStorageClassSpecifierString(StorageClass SC);
838
839protected:
840 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
841 // have allocated the auxiliary struct of information there.
842 //
843 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
844 // this as *many* VarDecls are ParmVarDecls that don't have default
845 // arguments. We could save some space by moving this pointer union to be
846 // allocated in trailing space when necessary.
847 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
848
849 /// \brief The initializer for this variable or, for a ParmVarDecl, the
850 /// C++ default argument.
851 mutable InitType Init;
852
853private:
854 friend class ASTDeclReader;
855 friend class ASTNodeImporter;
856 friend class StmtIteratorBase;
857
858 class VarDeclBitfields {
859 friend class ASTDeclReader;
860 friend class VarDecl;
861
862 unsigned SClass : 3;
863 unsigned TSCSpec : 2;
864 unsigned InitStyle : 2;
865 };
866 enum { NumVarDeclBits = 7 };
867
868protected:
869 enum { NumParameterIndexBits = 8 };
870
871 enum DefaultArgKind {
872 DAK_None,
873 DAK_Unparsed,
874 DAK_Uninstantiated,
875 DAK_Normal
876 };
877
878 class ParmVarDeclBitfields {
879 friend class ASTDeclReader;
880 friend class ParmVarDecl;
881
882 unsigned : NumVarDeclBits;
883
884 /// Whether this parameter inherits a default argument from a
885 /// prior declaration.
886 unsigned HasInheritedDefaultArg : 1;
887
888 /// Describes the kind of default argument for this parameter. By default
889 /// this is none. If this is normal, then the default argument is stored in
890 /// the \c VarDecl initializer expression unless we were unable to parse
891 /// (even an invalid) expression for the default argument.
892 unsigned DefaultArgKind : 2;
893
894 /// Whether this parameter undergoes K&R argument promotion.
895 unsigned IsKNRPromoted : 1;
896
897 /// Whether this parameter is an ObjC method parameter or not.
898 unsigned IsObjCMethodParam : 1;
899
900 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
901 /// Otherwise, the number of function parameter scopes enclosing
902 /// the function parameter scope in which this parameter was
903 /// declared.
904 unsigned ScopeDepthOrObjCQuals : 7;
905
906 /// The number of parameters preceding this parameter in the
907 /// function parameter scope in which it was declared.
908 unsigned ParameterIndex : NumParameterIndexBits;
909 };
910
911 class NonParmVarDeclBitfields {
912 friend class ASTDeclReader;
913 friend class ImplicitParamDecl;
914 friend class VarDecl;
915
916 unsigned : NumVarDeclBits;
917
918 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
919 /// \brief Whether this variable is a definition which was demoted due to
920 /// module merge.
921 unsigned IsThisDeclarationADemotedDefinition : 1;
922
923 /// \brief Whether this variable is the exception variable in a C++ catch
924 /// or an Objective-C @catch statement.
925 unsigned ExceptionVar : 1;
926
927 /// \brief Whether this local variable could be allocated in the return
928 /// slot of its function, enabling the named return value optimization
929 /// (NRVO).
930 unsigned NRVOVariable : 1;
931
932 /// \brief Whether this variable is the for-range-declaration in a C++0x
933 /// for-range statement.
934 unsigned CXXForRangeDecl : 1;
935
936 /// \brief Whether this variable is an ARC pseudo-__strong
937 /// variable; see isARCPseudoStrong() for details.
938 unsigned ARCPseudoStrong : 1;
939
940 /// \brief Whether this variable is (C++1z) inline.
941 unsigned IsInline : 1;
942
943 /// \brief Whether this variable has (C++1z) inline explicitly specified.
944 unsigned IsInlineSpecified : 1;
945
946 /// \brief Whether this variable is (C++0x) constexpr.
947 unsigned IsConstexpr : 1;
948
949 /// \brief Whether this variable is the implicit variable for a lambda
950 /// init-capture.
951 unsigned IsInitCapture : 1;
952
953 /// \brief Whether this local extern variable's previous declaration was
954 /// declared in the same block scope. This controls whether we should merge
955 /// the type of this declaration with its previous declaration.
956 unsigned PreviousDeclInSameBlockScope : 1;
957
958 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
959 /// something else.
960 unsigned ImplicitParamKind : 3;
961 };
962
963 union {
964 unsigned AllBits;
965 VarDeclBitfields VarDeclBits;
966 ParmVarDeclBitfields ParmVarDeclBits;
967 NonParmVarDeclBitfields NonParmVarDeclBits;
968 };
969
970 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
971 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
972 TypeSourceInfo *TInfo, StorageClass SC);
973
974 using redeclarable_base = Redeclarable<VarDecl>;
975
976 VarDecl *getNextRedeclarationImpl() override {
977 return getNextRedeclaration();
978 }
979
980 VarDecl *getPreviousDeclImpl() override {
981 return getPreviousDecl();
982 }
983
984 VarDecl *getMostRecentDeclImpl() override {
985 return getMostRecentDecl();
986 }
987
988public:
989 using redecl_range = redeclarable_base::redecl_range;
990 using redecl_iterator = redeclarable_base::redecl_iterator;
991
992 using redeclarable_base::redecls_begin;
993 using redeclarable_base::redecls_end;
994 using redeclarable_base::redecls;
995 using redeclarable_base::getPreviousDecl;
996 using redeclarable_base::getMostRecentDecl;
997 using redeclarable_base::isFirstDecl;
998
999 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1000 SourceLocation StartLoc, SourceLocation IdLoc,
1001 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1002 StorageClass S);
1003
1004 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1005
1006 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1007
1008 /// \brief Returns the storage class as written in the source. For the
1009 /// computed linkage of symbol, see getLinkage.
1010 StorageClass getStorageClass() const {
1011 return (StorageClass) VarDeclBits.SClass;
1012 }
1013 void setStorageClass(StorageClass SC);
1014
1015 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1016 VarDeclBits.TSCSpec = TSC;
1017 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1017, __extension__ __PRETTY_FUNCTION__))
;
1018 }
1019 ThreadStorageClassSpecifier getTSCSpec() const {
1020 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1021 }
1022 TLSKind getTLSKind() const;
1023
1024 /// hasLocalStorage - Returns true if a variable with function scope
1025 /// is a non-static local variable.
1026 bool hasLocalStorage() const {
1027 if (getStorageClass() == SC_None) {
1028 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1029 // used to describe variables allocated in global memory and which are
1030 // accessed inside a kernel(s) as read-only variables. As such, variables
1031 // in constant address space cannot have local storage.
1032 if (getType().getAddressSpace() == LangAS::opencl_constant)
1033 return false;
1034 // Second check is for C++11 [dcl.stc]p4.
1035 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1036 }
1037
1038 // Global Named Register (GNU extension)
1039 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1040 return false;
1041
1042 // Return true for: Auto, Register.
1043 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1044
1045 return getStorageClass() >= SC_Auto;
1046 }
1047
1048 /// isStaticLocal - Returns true if a variable with function scope is a
1049 /// static local variable.
1050 bool isStaticLocal() const {
1051 return (getStorageClass() == SC_Static ||
1052 // C++11 [dcl.stc]p4
1053 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1054 && !isFileVarDecl();
1055 }
1056
1057 /// \brief Returns true if a variable has extern or __private_extern__
1058 /// storage.
1059 bool hasExternalStorage() const {
1060 return getStorageClass() == SC_Extern ||
1061 getStorageClass() == SC_PrivateExtern;
1062 }
1063
1064 /// \brief Returns true for all variables that do not have local storage.
1065 ///
1066 /// This includes all global variables as well as static variables declared
1067 /// within a function.
1068 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1069
1070 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1071 StorageDuration getStorageDuration() const {
1072 return hasLocalStorage() ? SD_Automatic :
1073 getTSCSpec() ? SD_Thread : SD_Static;
1074 }
1075
1076 /// \brief Compute the language linkage.
1077 LanguageLinkage getLanguageLinkage() const;
1078
1079 /// \brief Determines whether this variable is a variable with
1080 /// external, C linkage.
1081 bool isExternC() const;
1082
1083 /// \brief Determines whether this variable's context is, or is nested within,
1084 /// a C++ extern "C" linkage spec.
1085 bool isInExternCContext() const;
1086
1087 /// \brief Determines whether this variable's context is, or is nested within,
1088 /// a C++ extern "C++" linkage spec.
1089 bool isInExternCXXContext() const;
1090
1091 /// isLocalVarDecl - Returns true for local variable declarations
1092 /// other than parameters. Note that this includes static variables
1093 /// inside of functions. It also includes variables inside blocks.
1094 ///
1095 /// void foo() { int x; static int y; extern int z; }
1096 bool isLocalVarDecl() const {
1097 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1098 return false;
1099 if (const DeclContext *DC = getLexicalDeclContext())
1100 return DC->getRedeclContext()->isFunctionOrMethod();
1101 return false;
1102 }
1103
1104 /// \brief Similar to isLocalVarDecl but also includes parameters.
1105 bool isLocalVarDeclOrParm() const {
1106 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1107 }
1108
1109 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1110 /// excludes variables declared in blocks.
1111 bool isFunctionOrMethodVarDecl() const {
1112 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1113 return false;
1114 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1115 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1116 }
1117
1118 /// \brief Determines whether this is a static data member.
1119 ///
1120 /// This will only be true in C++, and applies to, e.g., the
1121 /// variable 'x' in:
1122 /// \code
1123 /// struct S {
1124 /// static int x;
1125 /// };
1126 /// \endcode
1127 bool isStaticDataMember() const {
1128 // If it wasn't static, it would be a FieldDecl.
1129 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1130 }
1131
1132 VarDecl *getCanonicalDecl() override;
1133 const VarDecl *getCanonicalDecl() const {
1134 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1135 }
1136
1137 enum DefinitionKind {
1138 /// This declaration is only a declaration.
1139 DeclarationOnly,
1140
1141 /// This declaration is a tentative definition.
1142 TentativeDefinition,
1143
1144 /// This declaration is definitely a definition.
1145 Definition
1146 };
1147
1148 /// \brief Check whether this declaration is a definition. If this could be
1149 /// a tentative definition (in C), don't check whether there's an overriding
1150 /// definition.
1151 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1152 DefinitionKind isThisDeclarationADefinition() const {
1153 return isThisDeclarationADefinition(getASTContext());
1154 }
1155
1156 /// \brief Check whether this variable is defined in this
1157 /// translation unit.
1158 DefinitionKind hasDefinition(ASTContext &) const;
1159 DefinitionKind hasDefinition() const {
1160 return hasDefinition(getASTContext());
1161 }
1162
1163 /// \brief Get the tentative definition that acts as the real definition in
1164 /// a TU. Returns null if there is a proper definition available.
1165 VarDecl *getActingDefinition();
1166 const VarDecl *getActingDefinition() const {
1167 return const_cast<VarDecl*>(this)->getActingDefinition();
1168 }
1169
1170 /// \brief Get the real (not just tentative) definition for this declaration.
1171 VarDecl *getDefinition(ASTContext &);
1172 const VarDecl *getDefinition(ASTContext &C) const {
1173 return const_cast<VarDecl*>(this)->getDefinition(C);
1174 }
1175 VarDecl *getDefinition() {
1176 return getDefinition(getASTContext());
1177 }
1178 const VarDecl *getDefinition() const {
1179 return const_cast<VarDecl*>(this)->getDefinition();
1180 }
1181
1182 /// \brief Determine whether this is or was instantiated from an out-of-line
1183 /// definition of a static data member.
1184 bool isOutOfLine() const override;
1185
1186 /// isFileVarDecl - Returns true for file scoped variable declaration.
1187 bool isFileVarDecl() const {
1188 Kind K = getKind();
1189 if (K == ParmVar || K == ImplicitParam)
1190 return false;
1191
1192 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1193 return true;
1194
1195 if (isStaticDataMember())
1196 return true;
1197
1198 return false;
1199 }
1200
1201 /// getAnyInitializer - Get the initializer for this variable, no matter which
1202 /// declaration it is attached to.
1203 const Expr *getAnyInitializer() const {
1204 const VarDecl *D;
1205 return getAnyInitializer(D);
1206 }
1207
1208 /// getAnyInitializer - Get the initializer for this variable, no matter which
1209 /// declaration it is attached to. Also get that declaration.
1210 const Expr *getAnyInitializer(const VarDecl *&D) const;
1211
1212 bool hasInit() const;
1213 const Expr *getInit() const {
1214 return const_cast<VarDecl *>(this)->getInit();
1215 }
1216 Expr *getInit();
1217
1218 /// \brief Retrieve the address of the initializer expression.
1219 Stmt **getInitAddress();
1220
1221 void setInit(Expr *I);
1222
1223 /// \brief Determine whether this variable's value can be used in a
1224 /// constant expression, according to the relevant language standard.
1225 /// This only checks properties of the declaration, and does not check
1226 /// whether the initializer is in fact a constant expression.
1227 bool isUsableInConstantExpressions(ASTContext &C) const;
1228
1229 EvaluatedStmt *ensureEvaluatedStmt() const;
1230
1231 /// \brief Attempt to evaluate the value of the initializer attached to this
1232 /// declaration, and produce notes explaining why it cannot be evaluated or is
1233 /// not a constant expression. Returns a pointer to the value if evaluation
1234 /// succeeded, 0 otherwise.
1235 APValue *evaluateValue() const;
1236 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1237
1238 /// \brief Return the already-evaluated value of this variable's
1239 /// initializer, or NULL if the value is not yet known. Returns pointer
1240 /// to untyped APValue if the value could not be evaluated.
1241 APValue *getEvaluatedValue() const;
1242
1243 /// \brief Determines whether it is already known whether the
1244 /// initializer is an integral constant expression or not.
1245 bool isInitKnownICE() const;
1246
1247 /// \brief Determines whether the initializer is an integral constant
1248 /// expression, or in C++11, whether the initializer is a constant
1249 /// expression.
1250 ///
1251 /// \pre isInitKnownICE()
1252 bool isInitICE() const;
1253
1254 /// \brief Determine whether the value of the initializer attached to this
1255 /// declaration is an integral constant expression.
1256 bool checkInitIsICE() const;
1257
1258 void setInitStyle(InitializationStyle Style) {
1259 VarDeclBits.InitStyle = Style;
1260 }
1261
1262 /// \brief The style of initialization for this declaration.
1263 ///
1264 /// C-style initialization is "int x = 1;". Call-style initialization is
1265 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1266 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1267 /// expression for class types. List-style initialization is C++11 syntax,
1268 /// e.g. "int x{1};". Clients can distinguish between different forms of
1269 /// initialization by checking this value. In particular, "int x = {1};" is
1270 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1271 /// Init expression in all three cases is an InitListExpr.
1272 InitializationStyle getInitStyle() const {
1273 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1274 }
1275
1276 /// \brief Whether the initializer is a direct-initializer (list or call).
1277 bool isDirectInit() const {
1278 return getInitStyle() != CInit;
1279 }
1280
1281 /// \brief If this definition should pretend to be a declaration.
1282 bool isThisDeclarationADemotedDefinition() const {
1283 return isa<ParmVarDecl>(this) ? false :
1284 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1285 }
1286
1287 /// \brief This is a definition which should be demoted to a declaration.
1288 ///
1289 /// In some cases (mostly module merging) we can end up with two visible
1290 /// definitions one of which needs to be demoted to a declaration to keep
1291 /// the AST invariants.
1292 void demoteThisDefinitionToDeclaration() {
1293 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1293, __extension__ __PRETTY_FUNCTION__))
;
1294 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) &&
"Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1296 }
1297
1298 /// \brief Determine whether this variable is the exception variable in a
1299 /// C++ catch statememt or an Objective-C \@catch statement.
1300 bool isExceptionVariable() const {
1301 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1302 }
1303 void setExceptionVariable(bool EV) {
1304 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1304, __extension__ __PRETTY_FUNCTION__))
;
1305 NonParmVarDeclBits.ExceptionVar = EV;
1306 }
1307
1308 /// \brief Determine whether this local variable can be used with the named
1309 /// return value optimization (NRVO).
1310 ///
1311 /// The named return value optimization (NRVO) works by marking certain
1312 /// non-volatile local variables of class type as NRVO objects. These
1313 /// locals can be allocated within the return slot of their containing
1314 /// function, in which case there is no need to copy the object to the
1315 /// return slot when returning from the function. Within the function body,
1316 /// each return that returns the NRVO object will have this variable as its
1317 /// NRVO candidate.
1318 bool isNRVOVariable() const {
1319 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1320 }
1321 void setNRVOVariable(bool NRVO) {
1322 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1322, __extension__ __PRETTY_FUNCTION__))
;
1323 NonParmVarDeclBits.NRVOVariable = NRVO;
1324 }
1325
1326 /// \brief Determine whether this variable is the for-range-declaration in
1327 /// a C++0x for-range statement.
1328 bool isCXXForRangeDecl() const {
1329 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1330 }
1331 void setCXXForRangeDecl(bool FRD) {
1332 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1332, __extension__ __PRETTY_FUNCTION__))
;
1333 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1334 }
1335
1336 /// \brief Determine whether this variable is an ARC pseudo-__strong
1337 /// variable. A pseudo-__strong variable has a __strong-qualified
1338 /// type but does not actually retain the object written into it.
1339 /// Generally such variables are also 'const' for safety.
1340 bool isARCPseudoStrong() const {
1341 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1342 }
1343 void setARCPseudoStrong(bool ps) {
1344 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1344, __extension__ __PRETTY_FUNCTION__))
;
1345 NonParmVarDeclBits.ARCPseudoStrong = ps;
1346 }
1347
1348 /// Whether this variable is (C++1z) inline.
1349 bool isInline() const {
1350 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1351 }
1352 bool isInlineSpecified() const {
1353 return isa<ParmVarDecl>(this) ? false
1354 : NonParmVarDeclBits.IsInlineSpecified;
1355 }
1356 void setInlineSpecified() {
1357 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1357, __extension__ __PRETTY_FUNCTION__))
;
1358 NonParmVarDeclBits.IsInline = true;
1359 NonParmVarDeclBits.IsInlineSpecified = true;
1360 }
1361 void setImplicitlyInline() {
1362 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1362, __extension__ __PRETTY_FUNCTION__))
;
1363 NonParmVarDeclBits.IsInline = true;
1364 }
1365
1366 /// Whether this variable is (C++11) constexpr.
1367 bool isConstexpr() const {
1368 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1369 }
1370 void setConstexpr(bool IC) {
1371 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1371, __extension__ __PRETTY_FUNCTION__))
;
1372 NonParmVarDeclBits.IsConstexpr = IC;
1373 }
1374
1375 /// Whether this variable is the implicit variable for a lambda init-capture.
1376 bool isInitCapture() const {
1377 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1378 }
1379 void setInitCapture(bool IC) {
1380 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1380, __extension__ __PRETTY_FUNCTION__))
;
1381 NonParmVarDeclBits.IsInitCapture = IC;
1382 }
1383
1384 /// Whether this local extern variable declaration's previous declaration
1385 /// was declared in the same block scope. Only correct in C++.
1386 bool isPreviousDeclInSameBlockScope() const {
1387 return isa<ParmVarDecl>(this)
1388 ? false
1389 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1390 }
1391 void setPreviousDeclInSameBlockScope(bool Same) {
1392 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1392, __extension__ __PRETTY_FUNCTION__))
;
1393 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1394 }
1395
1396 /// \brief Retrieve the variable declaration from which this variable could
1397 /// be instantiated, if it is an instantiation (rather than a non-template).
1398 VarDecl *getTemplateInstantiationPattern() const;
1399
1400 /// \brief If this variable is an instantiated static data member of a
1401 /// class template specialization, returns the templated static data member
1402 /// from which it was instantiated.
1403 VarDecl *getInstantiatedFromStaticDataMember() const;
1404
1405 /// \brief If this variable is an instantiation of a variable template or a
1406 /// static data member of a class template, determine what kind of
1407 /// template specialization or instantiation this is.
1408 TemplateSpecializationKind getTemplateSpecializationKind() const;
1409
1410 /// \brief If this variable is an instantiation of a variable template or a
1411 /// static data member of a class template, determine its point of
1412 /// instantiation.
1413 SourceLocation getPointOfInstantiation() const;
1414
1415 /// \brief If this variable is an instantiation of a static data member of a
1416 /// class template specialization, retrieves the member specialization
1417 /// information.
1418 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1419
1420 /// \brief For a static data member that was instantiated from a static
1421 /// data member of a class template, set the template specialiation kind.
1422 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1423 SourceLocation PointOfInstantiation = SourceLocation());
1424
1425 /// \brief Specify that this variable is an instantiation of the
1426 /// static data member VD.
1427 void setInstantiationOfStaticDataMember(VarDecl *VD,
1428 TemplateSpecializationKind TSK);
1429
1430 /// \brief Retrieves the variable template that is described by this
1431 /// variable declaration.
1432 ///
1433 /// Every variable template is represented as a VarTemplateDecl and a
1434 /// VarDecl. The former contains template properties (such as
1435 /// the template parameter lists) while the latter contains the
1436 /// actual description of the template's
1437 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1438 /// VarDecl that from a VarTemplateDecl, while
1439 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1440 /// a VarDecl.
1441 VarTemplateDecl *getDescribedVarTemplate() const;
1442
1443 void setDescribedVarTemplate(VarTemplateDecl *Template);
1444
1445 // Implement isa/cast/dyncast/etc.
1446 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1447 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1448};
1449
1450class ImplicitParamDecl : public VarDecl {
1451 void anchor() override;
1452
1453public:
1454 /// Defines the kind of the implicit parameter: is this an implicit parameter
1455 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1456 /// context or something else.
1457 enum ImplicitParamKind : unsigned {
1458 /// Parameter for Objective-C 'self' argument
1459 ObjCSelf,
1460
1461 /// Parameter for Objective-C '_cmd' argument
1462 ObjCCmd,
1463
1464 /// Parameter for C++ 'this' argument
1465 CXXThis,
1466
1467 /// Parameter for C++ virtual table pointers
1468 CXXVTT,
1469
1470 /// Parameter for captured context
1471 CapturedContext,
1472
1473 /// Other implicit parameter
1474 Other,
1475 };
1476
1477 /// Create implicit parameter.
1478 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1479 SourceLocation IdLoc, IdentifierInfo *Id,
1480 QualType T, ImplicitParamKind ParamKind);
1481 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1482 ImplicitParamKind ParamKind);
1483
1484 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1485
1486 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1487 IdentifierInfo *Id, QualType Type,
1488 ImplicitParamKind ParamKind)
1489 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1490 /*TInfo=*/nullptr, SC_None) {
1491 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1492 setImplicit();
1493 }
1494
1495 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1496 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1497 SourceLocation(), /*Id=*/nullptr, Type,
1498 /*TInfo=*/nullptr, SC_None) {
1499 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1500 setImplicit();
1501 }
1502
1503 /// Returns the implicit parameter kind.
1504 ImplicitParamKind getParameterKind() const {
1505 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1506 }
1507
1508 // Implement isa/cast/dyncast/etc.
1509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1510 static bool classofKind(Kind K) { return K == ImplicitParam; }
1511};
1512
1513/// ParmVarDecl - Represents a parameter to a function.
1514class ParmVarDecl : public VarDecl {
1515public:
1516 enum { MaxFunctionScopeDepth = 255 };
1517 enum { MaxFunctionScopeIndex = 255 };
1518
1519protected:
1520 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1521 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1522 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1523 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1524 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1524, __extension__ __PRETTY_FUNCTION__))
;
1525 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1525, __extension__ __PRETTY_FUNCTION__))
;
1526 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1526, __extension__ __PRETTY_FUNCTION__))
;
1527 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1527, __extension__ __PRETTY_FUNCTION__))
;
1528 setDefaultArg(DefArg);
1529 }
1530
1531public:
1532 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1533 SourceLocation StartLoc,
1534 SourceLocation IdLoc, IdentifierInfo *Id,
1535 QualType T, TypeSourceInfo *TInfo,
1536 StorageClass S, Expr *DefArg);
1537
1538 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1539
1540 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1541
1542 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1543 ParmVarDeclBits.IsObjCMethodParam = true;
1544 setParameterIndex(parameterIndex);
1545 }
1546
1547 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1548 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1548, __extension__ __PRETTY_FUNCTION__))
;
1549
1550 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1551 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1552, __extension__ __PRETTY_FUNCTION__))
1552 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1552, __extension__ __PRETTY_FUNCTION__))
;
1553
1554 setParameterIndex(parameterIndex);
1555 }
1556
1557 bool isObjCMethodParameter() const {
1558 return ParmVarDeclBits.IsObjCMethodParam;
1559 }
1560
1561 unsigned getFunctionScopeDepth() const {
1562 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1563 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1564 }
1565
1566 /// Returns the index of this parameter in its prototype or method scope.
1567 unsigned getFunctionScopeIndex() const {
1568 return getParameterIndex();
1569 }
1570
1571 ObjCDeclQualifier getObjCDeclQualifier() const {
1572 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1573 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1574 }
1575 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1576 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1576, __extension__ __PRETTY_FUNCTION__))
;
1577 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1578 }
1579
1580 /// True if the value passed to this parameter must undergo
1581 /// K&R-style default argument promotion:
1582 ///
1583 /// C99 6.5.2.2.
1584 /// If the expression that denotes the called function has a type
1585 /// that does not include a prototype, the integer promotions are
1586 /// performed on each argument, and arguments that have type float
1587 /// are promoted to double.
1588 bool isKNRPromoted() const {
1589 return ParmVarDeclBits.IsKNRPromoted;
1590 }
1591 void setKNRPromoted(bool promoted) {
1592 ParmVarDeclBits.IsKNRPromoted = promoted;
1593 }
1594
1595 Expr *getDefaultArg();
1596 const Expr *getDefaultArg() const {
1597 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1598 }
1599
1600 void setDefaultArg(Expr *defarg);
1601
1602 /// \brief Retrieve the source range that covers the entire default
1603 /// argument.
1604 SourceRange getDefaultArgRange() const;
1605 void setUninstantiatedDefaultArg(Expr *arg);
1606 Expr *getUninstantiatedDefaultArg();
1607 const Expr *getUninstantiatedDefaultArg() const {
1608 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1609 }
1610
1611 /// hasDefaultArg - Determines whether this parameter has a default argument,
1612 /// either parsed or not.
1613 bool hasDefaultArg() const;
1614
1615 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1616 /// default argument that has not yet been parsed. This will occur
1617 /// during the processing of a C++ class whose member functions have
1618 /// default arguments, e.g.,
1619 /// @code
1620 /// class X {
1621 /// public:
1622 /// void f(int x = 17); // x has an unparsed default argument now
1623 /// }; // x has a regular default argument now
1624 /// @endcode
1625 bool hasUnparsedDefaultArg() const {
1626 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1627 }
1628
1629 bool hasUninstantiatedDefaultArg() const {
1630 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1631 }
1632
1633 /// setUnparsedDefaultArg - Specify that this parameter has an
1634 /// unparsed default argument. The argument will be replaced with a
1635 /// real default argument via setDefaultArg when the class
1636 /// definition enclosing the function declaration that owns this
1637 /// default argument is completed.
1638 void setUnparsedDefaultArg() {
1639 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1640 }
1641
1642 bool hasInheritedDefaultArg() const {
1643 return ParmVarDeclBits.HasInheritedDefaultArg;
1644 }
1645
1646 void setHasInheritedDefaultArg(bool I = true) {
1647 ParmVarDeclBits.HasInheritedDefaultArg = I;
1648 }
1649
1650 QualType getOriginalType() const;
1651
1652 /// \brief Determine whether this parameter is actually a function
1653 /// parameter pack.
1654 bool isParameterPack() const;
1655
1656 /// setOwningFunction - Sets the function declaration that owns this
1657 /// ParmVarDecl. Since ParmVarDecls are often created before the
1658 /// FunctionDecls that own them, this routine is required to update
1659 /// the DeclContext appropriately.
1660 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1661
1662 // Implement isa/cast/dyncast/etc.
1663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1664 static bool classofKind(Kind K) { return K == ParmVar; }
1665
1666private:
1667 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1668
1669 void setParameterIndex(unsigned parameterIndex) {
1670 if (parameterIndex >= ParameterIndexSentinel) {
1671 setParameterIndexLarge(parameterIndex);
1672 return;
1673 }
1674
1675 ParmVarDeclBits.ParameterIndex = parameterIndex;
1676 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 1676, __extension__ __PRETTY_FUNCTION__))
;
1677 }
1678 unsigned getParameterIndex() const {
1679 unsigned d = ParmVarDeclBits.ParameterIndex;
1680 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1681 }
1682
1683 void setParameterIndexLarge(unsigned parameterIndex);
1684 unsigned getParameterIndexLarge() const;
1685};
1686
1687/// FunctionDecl - An instance of this class is created to represent a
1688/// function declaration or definition.
1689///
1690/// Since a given function can be declared several times in a program,
1691/// there may be several FunctionDecls that correspond to that
1692/// function. Only one of those FunctionDecls will be found when
1693/// traversing the list of declarations in the context of the
1694/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1695/// contains all of the information known about the function. Other,
1696/// previous declarations of the function are available via the
1697/// getPreviousDecl() chain.
1698class FunctionDecl : public DeclaratorDecl, public DeclContext,
1699 public Redeclarable<FunctionDecl> {
1700public:
1701 /// \brief The kind of templated function a FunctionDecl can be.
1702 enum TemplatedKind {
1703 TK_NonTemplate,
1704 TK_FunctionTemplate,
1705 TK_MemberSpecialization,
1706 TK_FunctionTemplateSpecialization,
1707 TK_DependentFunctionTemplateSpecialization
1708 };
1709
1710private:
1711 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1712 /// parameters of this function. This is null if a prototype or if there are
1713 /// no formals.
1714 ParmVarDecl **ParamInfo = nullptr;
1715
1716 LazyDeclStmtPtr Body;
1717
1718 // FIXME: This can be packed into the bitfields in DeclContext.
1719 // NOTE: VC++ packs bitfields poorly if the types differ.
1720 unsigned SClass : 3;
1721 unsigned IsInline : 1;
1722 unsigned IsInlineSpecified : 1;
1723
1724protected:
1725 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1726 // CXXDeductionGuideDecl.
1727 unsigned IsExplicitSpecified : 1;
1728
1729private:
1730 unsigned IsVirtualAsWritten : 1;
1731 unsigned IsPure : 1;
1732 unsigned HasInheritedPrototype : 1;
1733 unsigned HasWrittenPrototype : 1;
1734 unsigned IsDeleted : 1;
1735 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1736 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1737 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1738 unsigned HasImplicitReturnZero : 1;
1739 unsigned IsLateTemplateParsed : 1;
1740 unsigned IsConstexpr : 1;
1741 unsigned InstantiationIsPending : 1;
1742
1743 /// \brief Indicates if the function uses __try.
1744 unsigned UsesSEHTry : 1;
1745
1746 /// \brief Indicates if the function was a definition but its body was
1747 /// skipped.
1748 unsigned HasSkippedBody : 1;
1749
1750 /// Indicates if the function declaration will have a body, once we're done
1751 /// parsing it.
1752 unsigned WillHaveBody : 1;
1753
1754protected:
1755 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1756 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1757 /// int as opposed to adding a single bit to FunctionDecl.
1758 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1759 /// deduction candidate' (is used during overload resolution).
1760 unsigned IsCopyDeductionCandidate : 1;
1761
1762private:
1763 /// \brief End part of this FunctionDecl's source range.
1764 ///
1765 /// We could compute the full range in getSourceRange(). However, when we're
1766 /// dealing with a function definition deserialized from a PCH/AST file,
1767 /// we can only compute the full range once the function body has been
1768 /// de-serialized, so it's far better to have the (sometimes-redundant)
1769 /// EndRangeLoc.
1770 SourceLocation EndRangeLoc;
1771
1772 /// \brief The template or declaration that this declaration
1773 /// describes or was instantiated from, respectively.
1774 ///
1775 /// For non-templates, this value will be NULL. For function
1776 /// declarations that describe a function template, this will be a
1777 /// pointer to a FunctionTemplateDecl. For member functions
1778 /// of class template specializations, this will be a MemberSpecializationInfo
1779 /// pointer containing information about the specialization.
1780 /// For function template specializations, this will be a
1781 /// FunctionTemplateSpecializationInfo, which contains information about
1782 /// the template being specialized and the template arguments involved in
1783 /// that specialization.
1784 llvm::PointerUnion4<FunctionTemplateDecl *,
1785 MemberSpecializationInfo *,
1786 FunctionTemplateSpecializationInfo *,
1787 DependentFunctionTemplateSpecializationInfo *>
1788 TemplateOrSpecialization;
1789
1790 /// DNLoc - Provides source/type location info for the
1791 /// declaration name embedded in the DeclaratorDecl base class.
1792 DeclarationNameLoc DNLoc;
1793
1794 /// \brief Specify that this function declaration is actually a function
1795 /// template specialization.
1796 ///
1797 /// \param C the ASTContext.
1798 ///
1799 /// \param Template the function template that this function template
1800 /// specialization specializes.
1801 ///
1802 /// \param TemplateArgs the template arguments that produced this
1803 /// function template specialization from the template.
1804 ///
1805 /// \param InsertPos If non-NULL, the position in the function template
1806 /// specialization set where the function template specialization data will
1807 /// be inserted.
1808 ///
1809 /// \param TSK the kind of template specialization this is.
1810 ///
1811 /// \param TemplateArgsAsWritten location info of template arguments.
1812 ///
1813 /// \param PointOfInstantiation point at which the function template
1814 /// specialization was first instantiated.
1815 void setFunctionTemplateSpecialization(ASTContext &C,
1816 FunctionTemplateDecl *Template,
1817 const TemplateArgumentList *TemplateArgs,
1818 void *InsertPos,
1819 TemplateSpecializationKind TSK,
1820 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1821 SourceLocation PointOfInstantiation);
1822
1823 /// \brief Specify that this record is an instantiation of the
1824 /// member function FD.
1825 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1826 TemplateSpecializationKind TSK);
1827
1828 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1829
1830protected:
1831 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1832 const DeclarationNameInfo &NameInfo, QualType T,
1833 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1834 bool isConstexprSpecified)
1835 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1836 StartLoc),
1837 DeclContext(DK), redeclarable_base(C), SClass(S),
1838 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1839 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1840 HasInheritedPrototype(false), HasWrittenPrototype(true),
1841 IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1842 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1843 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1844 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1845 WillHaveBody(false), IsCopyDeductionCandidate(false),
1846 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1847
1848 using redeclarable_base = Redeclarable<FunctionDecl>;
1849
1850 FunctionDecl *getNextRedeclarationImpl() override {
1851 return getNextRedeclaration();
1852 }
1853
1854 FunctionDecl *getPreviousDeclImpl() override {
1855 return getPreviousDecl();
1856 }
1857
1858 FunctionDecl *getMostRecentDeclImpl() override {
1859 return getMostRecentDecl();
1860 }
1861
1862public:
1863 friend class ASTDeclReader;
1864 friend class ASTDeclWriter;
1865
1866 using redecl_range = redeclarable_base::redecl_range;
1867 using redecl_iterator = redeclarable_base::redecl_iterator;
1868
1869 using redeclarable_base::redecls_begin;
1870 using redeclarable_base::redecls_end;
1871 using redeclarable_base::redecls;
1872 using redeclarable_base::getPreviousDecl;
1873 using redeclarable_base::getMostRecentDecl;
1874 using redeclarable_base::isFirstDecl;
1875
1876 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1877 SourceLocation StartLoc, SourceLocation NLoc,
1878 DeclarationName N, QualType T,
1879 TypeSourceInfo *TInfo,
1880 StorageClass SC,
1881 bool isInlineSpecified = false,
1882 bool hasWrittenPrototype = true,
1883 bool isConstexprSpecified = false) {
1884 DeclarationNameInfo NameInfo(N, NLoc);
1885 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1886 SC,
1887 isInlineSpecified, hasWrittenPrototype,
1888 isConstexprSpecified);
1889 }
1890
1891 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1892 SourceLocation StartLoc,
1893 const DeclarationNameInfo &NameInfo,
1894 QualType T, TypeSourceInfo *TInfo,
1895 StorageClass SC,
1896 bool isInlineSpecified,
1897 bool hasWrittenPrototype,
1898 bool isConstexprSpecified = false);
1899
1900 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1901
1902 DeclarationNameInfo getNameInfo() const {
1903 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1904 }
1905
1906 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1907 bool Qualified) const override;
1908
1909 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1910
1911 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1912
1913 /// \brief Returns true if the function has a body (definition). The
1914 /// function body might be in any of the (re-)declarations of this
1915 /// function. The variant that accepts a FunctionDecl pointer will
1916 /// set that function declaration to the actual declaration
1917 /// containing the body (if there is one).
1918 bool hasBody(const FunctionDecl *&Definition) const;
1919
1920 bool hasBody() const override {
1921 const FunctionDecl* Definition;
1922 return hasBody(Definition);
1923 }
1924
1925 /// hasTrivialBody - Returns whether the function has a trivial body that does
1926 /// not require any specific codegen.
1927 bool hasTrivialBody() const;
1928
1929 /// isDefined - Returns true if the function is defined at all, including
1930 /// a deleted definition. Except for the behavior when the function is
1931 /// deleted, behaves like hasBody.
1932 bool isDefined(const FunctionDecl *&Definition) const;
1933
1934 virtual bool isDefined() const {
1935 const FunctionDecl* Definition;
1936 return isDefined(Definition);
1937 }
1938
1939 /// \brief Get the definition for this declaration.
1940 FunctionDecl *getDefinition() {
1941 const FunctionDecl *Definition;
1942 if (isDefined(Definition))
1943 return const_cast<FunctionDecl *>(Definition);
1944 return nullptr;
1945 }
1946 const FunctionDecl *getDefinition() const {
1947 return const_cast<FunctionDecl *>(this)->getDefinition();
1948 }
1949
1950 /// getBody - Retrieve the body (definition) of the function. The
1951 /// function body might be in any of the (re-)declarations of this
1952 /// function. The variant that accepts a FunctionDecl pointer will
1953 /// set that function declaration to the actual declaration
1954 /// containing the body (if there is one).
1955 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1956 /// unnecessary AST de-serialization of the body.
1957 Stmt *getBody(const FunctionDecl *&Definition) const;
1958
1959 Stmt *getBody() const override {
1960 const FunctionDecl* Definition;
1961 return getBody(Definition);
1962 }
1963
1964 /// Returns whether this specific declaration of the function is also a
1965 /// definition that does not contain uninstantiated body.
1966 ///
1967 /// This does not determine whether the function has been defined (e.g., in a
1968 /// previous definition); for that information, use isDefined.
1969 bool isThisDeclarationADefinition() const {
1970 return IsDeleted || IsDefaulted || Body || IsLateTemplateParsed ||
1971 WillHaveBody || hasDefiningAttr();
1972 }
1973
1974 /// doesThisDeclarationHaveABody - Returns whether this specific
1975 /// declaration of the function has a body - that is, if it is a non-
1976 /// deleted definition.
1977 bool doesThisDeclarationHaveABody() const {
1978 return Body || IsLateTemplateParsed;
1979 }
1980
1981 void setBody(Stmt *B);
1982 void setLazyBody(uint64_t Offset) { Body = Offset; }
1983
1984 /// Whether this function is variadic.
1985 bool isVariadic() const;
1986
1987 /// Whether this function is marked as virtual explicitly.
1988 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1989 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1990
1991 /// Whether this virtual function is pure, i.e. makes the containing class
1992 /// abstract.
1993 bool isPure() const { return IsPure; }
1994 void setPure(bool P = true);
1995
1996 /// Whether this templated function will be late parsed.
1997 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1998 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1999
2000 /// Whether this function is "trivial" in some specialized C++ senses.
2001 /// Can only be true for default constructors, copy constructors,
2002 /// copy assignment operators, and destructors. Not meaningful until
2003 /// the class has been fully built by Sema.
2004 bool isTrivial() const { return IsTrivial; }
2005 void setTrivial(bool IT) { IsTrivial = IT; }
2006
2007 /// Whether this function is defaulted per C++0x. Only valid for
2008 /// special member functions.
2009 bool isDefaulted() const { return IsDefaulted; }
2010 void setDefaulted(bool D = true) { IsDefaulted = D; }
2011
2012 /// Whether this function is explicitly defaulted per C++0x. Only valid
2013 /// for special member functions.
2014 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2015 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2016
2017 /// Whether falling off this function implicitly returns null/zero.
2018 /// If a more specific implicit return value is required, front-ends
2019 /// should synthesize the appropriate return statements.
2020 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2021 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2022
2023 /// \brief Whether this function has a prototype, either because one
2024 /// was explicitly written or because it was "inherited" by merging
2025 /// a declaration without a prototype with a declaration that has a
2026 /// prototype.
2027 bool hasPrototype() const {
2028 return HasWrittenPrototype || HasInheritedPrototype;
2029 }
2030
2031 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2032
2033 /// \brief Whether this function inherited its prototype from a
2034 /// previous declaration.
2035 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2036 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2037
2038 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2039 bool isConstexpr() const { return IsConstexpr; }
2040 void setConstexpr(bool IC) { IsConstexpr = IC; }
2041
2042 /// \brief Whether the instantiation of this function is pending.
2043 /// This bit is set when the decision to instantiate this function is made
2044 /// and unset if and when the function body is created. That leaves out
2045 /// cases where instantiation did not happen because the template definition
2046 /// was not seen in this TU. This bit remains set in those cases, under the
2047 /// assumption that the instantiation will happen in some other TU.
2048 bool instantiationIsPending() const { return InstantiationIsPending; }
2049 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2050
2051 /// \brief Indicates the function uses __try.
2052 bool usesSEHTry() const { return UsesSEHTry; }
2053 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2054
2055 /// \brief Whether this function has been deleted.
2056 ///
2057 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2058 /// acts like a normal function, except that it cannot actually be
2059 /// called or have its address taken. Deleted functions are
2060 /// typically used in C++ overload resolution to attract arguments
2061 /// whose type or lvalue/rvalue-ness would permit the use of a
2062 /// different overload that would behave incorrectly. For example,
2063 /// one might use deleted functions to ban implicit conversion from
2064 /// a floating-point number to an Integer type:
2065 ///
2066 /// @code
2067 /// struct Integer {
2068 /// Integer(long); // construct from a long
2069 /// Integer(double) = delete; // no construction from float or double
2070 /// Integer(long double) = delete; // no construction from long double
2071 /// };
2072 /// @endcode
2073 // If a function is deleted, its first declaration must be.
2074 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2075 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2076 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2077
2078 /// \brief Determines whether this function is "main", which is the
2079 /// entry point into an executable program.
2080 bool isMain() const;
2081
2082 /// \brief Determines whether this function is a MSVCRT user defined entry
2083 /// point.
2084 bool isMSVCRTEntryPoint() const;
2085
2086 /// \brief Determines whether this operator new or delete is one
2087 /// of the reserved global placement operators:
2088 /// void *operator new(size_t, void *);
2089 /// void *operator new[](size_t, void *);
2090 /// void operator delete(void *, void *);
2091 /// void operator delete[](void *, void *);
2092 /// These functions have special behavior under [new.delete.placement]:
2093 /// These functions are reserved, a C++ program may not define
2094 /// functions that displace the versions in the Standard C++ library.
2095 /// The provisions of [basic.stc.dynamic] do not apply to these
2096 /// reserved placement forms of operator new and operator delete.
2097 ///
2098 /// This function must be an allocation or deallocation function.
2099 bool isReservedGlobalPlacementOperator() const;
2100
2101 /// \brief Determines whether this function is one of the replaceable
2102 /// global allocation functions:
2103 /// void *operator new(size_t);
2104 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2105 /// void *operator new[](size_t);
2106 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2107 /// void operator delete(void *) noexcept;
2108 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2109 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2110 /// void operator delete[](void *) noexcept;
2111 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2112 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2113 /// These functions have special behavior under C++1y [expr.new]:
2114 /// An implementation is allowed to omit a call to a replaceable global
2115 /// allocation function. [...]
2116 ///
2117 /// If this function is an aligned allocation/deallocation function, return
2118 /// true through IsAligned.
2119 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2120
2121 /// \brief Determine whether this is a destroying operator delete.
2122 bool isDestroyingOperatorDelete() const;
2123
2124 /// Compute the language linkage.
2125 LanguageLinkage getLanguageLinkage() const;
2126
2127 /// \brief Determines whether this function is a function with
2128 /// external, C linkage.
2129 bool isExternC() const;
2130
2131 /// \brief Determines whether this function's context is, or is nested within,
2132 /// a C++ extern "C" linkage spec.
2133 bool isInExternCContext() const;
2134
2135 /// \brief Determines whether this function's context is, or is nested within,
2136 /// a C++ extern "C++" linkage spec.
2137 bool isInExternCXXContext() const;
2138
2139 /// \brief Determines whether this is a global function.
2140 bool isGlobal() const;
2141
2142 /// \brief Determines whether this function is known to be 'noreturn', through
2143 /// an attribute on its declaration or its type.
2144 bool isNoReturn() const;
2145
2146 /// \brief True if the function was a definition but its body was skipped.
2147 bool hasSkippedBody() const { return HasSkippedBody; }
2148 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2149
2150 /// True if this function will eventually have a body, once it's fully parsed.
2151 bool willHaveBody() const { return WillHaveBody; }
2152 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2153
2154 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2155
2156 FunctionDecl *getCanonicalDecl() override;
2157 const FunctionDecl *getCanonicalDecl() const {
2158 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2159 }
2160
2161 unsigned getBuiltinID() const;
2162
2163 // ArrayRef interface to parameters.
2164 ArrayRef<ParmVarDecl *> parameters() const {
2165 return {ParamInfo, getNumParams()};
2166 }
2167 MutableArrayRef<ParmVarDecl *> parameters() {
2168 return {ParamInfo, getNumParams()};
2169 }
2170
2171 // Iterator access to formal parameters.
2172 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2173 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2174
2175 bool param_empty() const { return parameters().empty(); }
2176 param_iterator param_begin() { return parameters().begin(); }
2177 param_iterator param_end() { return parameters().end(); }
2178 param_const_iterator param_begin() const { return parameters().begin(); }
2179 param_const_iterator param_end() const { return parameters().end(); }
2180 size_t param_size() const { return parameters().size(); }
2181
2182 /// getNumParams - Return the number of parameters this function must have
2183 /// based on its FunctionType. This is the length of the ParamInfo array
2184 /// after it has been created.
2185 unsigned getNumParams() const;
2186
2187 const ParmVarDecl *getParamDecl(unsigned i) const {
2188 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2188, __extension__ __PRETTY_FUNCTION__))
;
2189 return ParamInfo[i];
2190 }
2191 ParmVarDecl *getParamDecl(unsigned i) {
2192 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2192, __extension__ __PRETTY_FUNCTION__))
;
2193 return ParamInfo[i];
2194 }
2195 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2196 setParams(getASTContext(), NewParamInfo);
2197 }
2198
2199 /// getMinRequiredArguments - Returns the minimum number of arguments
2200 /// needed to call this function. This may be fewer than the number of
2201 /// function parameters, if some of the parameters have default
2202 /// arguments (in C++).
2203 unsigned getMinRequiredArguments() const;
2204
2205 QualType getReturnType() const {
2206 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2206, __extension__ __PRETTY_FUNCTION__))
;
2207 return getType()->getAs<FunctionType>()->getReturnType();
2208 }
2209
2210 /// \brief Attempt to compute an informative source range covering the
2211 /// function return type. This may omit qualifiers and other information with
2212 /// limited representation in the AST.
2213 SourceRange getReturnTypeSourceRange() const;
2214
2215 /// \brief Attempt to compute an informative source range covering the
2216 /// function exception specification, if any.
2217 SourceRange getExceptionSpecSourceRange() const;
2218
2219 /// \brief Determine the type of an expression that calls this function.
2220 QualType getCallResultType() const {
2221 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2221, __extension__ __PRETTY_FUNCTION__))
;
2222 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2223 }
2224
2225 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2226 /// function, or its return type declaration.
2227 const Attr *getUnusedResultAttr() const;
2228
2229 /// \brief Returns true if this function or its return type has the
2230 /// warn_unused_result attribute.
2231 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2232
2233 /// \brief Returns the storage class as written in the source. For the
2234 /// computed linkage of symbol, see getLinkage.
2235 StorageClass getStorageClass() const { return StorageClass(SClass); }
2236
2237 /// \brief Determine whether the "inline" keyword was specified for this
2238 /// function.
2239 bool isInlineSpecified() const { return IsInlineSpecified; }
2240
2241 /// Set whether the "inline" keyword was specified for this function.
2242 void setInlineSpecified(bool I) {
2243 IsInlineSpecified = I;
2244 IsInline = I;
2245 }
2246
2247 /// Flag that this function is implicitly inline.
2248 void setImplicitlyInline() {
2249 IsInline = true;
2250 }
2251
2252 /// \brief Determine whether this function should be inlined, because it is
2253 /// either marked "inline" or "constexpr" or is a member function of a class
2254 /// that was defined in the class body.
2255 bool isInlined() const { return IsInline; }
2256
2257 bool isInlineDefinitionExternallyVisible() const;
2258
2259 bool isMSExternInline() const;
2260
2261 bool doesDeclarationForceExternallyVisibleDefinition() const;
2262
2263 /// isOverloadedOperator - Whether this function declaration
2264 /// represents an C++ overloaded operator, e.g., "operator+".
2265 bool isOverloadedOperator() const {
2266 return getOverloadedOperator() != OO_None;
2267 }
2268
2269 OverloadedOperatorKind getOverloadedOperator() const;
2270
2271 const IdentifierInfo *getLiteralIdentifier() const;
2272
2273 /// \brief If this function is an instantiation of a member function
2274 /// of a class template specialization, retrieves the function from
2275 /// which it was instantiated.
2276 ///
2277 /// This routine will return non-NULL for (non-templated) member
2278 /// functions of class templates and for instantiations of function
2279 /// templates. For example, given:
2280 ///
2281 /// \code
2282 /// template<typename T>
2283 /// struct X {
2284 /// void f(T);
2285 /// };
2286 /// \endcode
2287 ///
2288 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2289 /// whose parent is the class template specialization X<int>. For
2290 /// this declaration, getInstantiatedFromFunction() will return
2291 /// the FunctionDecl X<T>::A. When a complete definition of
2292 /// X<int>::A is required, it will be instantiated from the
2293 /// declaration returned by getInstantiatedFromMemberFunction().
2294 FunctionDecl *getInstantiatedFromMemberFunction() const;
2295
2296 /// \brief What kind of templated function this is.
2297 TemplatedKind getTemplatedKind() const;
2298
2299 /// \brief If this function is an instantiation of a member function of a
2300 /// class template specialization, retrieves the member specialization
2301 /// information.
2302 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2303
2304 /// \brief Specify that this record is an instantiation of the
2305 /// member function FD.
2306 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2307 TemplateSpecializationKind TSK) {
2308 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2309 }
2310
2311 /// \brief Retrieves the function template that is described by this
2312 /// function declaration.
2313 ///
2314 /// Every function template is represented as a FunctionTemplateDecl
2315 /// and a FunctionDecl (or something derived from FunctionDecl). The
2316 /// former contains template properties (such as the template
2317 /// parameter lists) while the latter contains the actual
2318 /// description of the template's
2319 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2320 /// FunctionDecl that describes the function template,
2321 /// getDescribedFunctionTemplate() retrieves the
2322 /// FunctionTemplateDecl from a FunctionDecl.
2323 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2324
2325 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2326
2327 /// \brief Determine whether this function is a function template
2328 /// specialization.
2329 bool isFunctionTemplateSpecialization() const {
2330 return getPrimaryTemplate() != nullptr;
2331 }
2332
2333 /// \brief Retrieve the class scope template pattern that this function
2334 /// template specialization is instantiated from.
2335 FunctionDecl *getClassScopeSpecializationPattern() const;
2336
2337 /// \brief If this function is actually a function template specialization,
2338 /// retrieve information about this function template specialization.
2339 /// Otherwise, returns NULL.
2340 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2341
2342 /// \brief Determines whether this function is a function template
2343 /// specialization or a member of a class template specialization that can
2344 /// be implicitly instantiated.
2345 bool isImplicitlyInstantiable() const;
2346
2347 /// \brief Determines if the given function was instantiated from a
2348 /// function template.
2349 bool isTemplateInstantiation() const;
2350
2351 /// \brief Retrieve the function declaration from which this function could
2352 /// be instantiated, if it is an instantiation (rather than a non-template
2353 /// or a specialization, for example).
2354 FunctionDecl *getTemplateInstantiationPattern() const;
2355
2356 /// \brief Retrieve the primary template that this function template
2357 /// specialization either specializes or was instantiated from.
2358 ///
2359 /// If this function declaration is not a function template specialization,
2360 /// returns NULL.
2361 FunctionTemplateDecl *getPrimaryTemplate() const;
2362
2363 /// \brief Retrieve the template arguments used to produce this function
2364 /// template specialization from the primary template.
2365 ///
2366 /// If this function declaration is not a function template specialization,
2367 /// returns NULL.
2368 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2369
2370 /// \brief Retrieve the template argument list as written in the sources,
2371 /// if any.
2372 ///
2373 /// If this function declaration is not a function template specialization
2374 /// or if it had no explicit template argument list, returns NULL.
2375 /// Note that it an explicit template argument list may be written empty,
2376 /// e.g., template<> void foo<>(char* s);
2377 const ASTTemplateArgumentListInfo*
2378 getTemplateSpecializationArgsAsWritten() const;
2379
2380 /// \brief Specify that this function declaration is actually a function
2381 /// template specialization.
2382 ///
2383 /// \param Template the function template that this function template
2384 /// specialization specializes.
2385 ///
2386 /// \param TemplateArgs the template arguments that produced this
2387 /// function template specialization from the template.
2388 ///
2389 /// \param InsertPos If non-NULL, the position in the function template
2390 /// specialization set where the function template specialization data will
2391 /// be inserted.
2392 ///
2393 /// \param TSK the kind of template specialization this is.
2394 ///
2395 /// \param TemplateArgsAsWritten location info of template arguments.
2396 ///
2397 /// \param PointOfInstantiation point at which the function template
2398 /// specialization was first instantiated.
2399 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2400 const TemplateArgumentList *TemplateArgs,
2401 void *InsertPos,
2402 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2403 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2404 SourceLocation PointOfInstantiation = SourceLocation()) {
2405 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2406 InsertPos, TSK, TemplateArgsAsWritten,
2407 PointOfInstantiation);
2408 }
2409
2410 /// \brief Specifies that this function declaration is actually a
2411 /// dependent function template specialization.
2412 void setDependentTemplateSpecialization(ASTContext &Context,
2413 const UnresolvedSetImpl &Templates,
2414 const TemplateArgumentListInfo &TemplateArgs);
2415
2416 DependentFunctionTemplateSpecializationInfo *
2417 getDependentSpecializationInfo() const;
2418
2419 /// \brief Determine what kind of template instantiation this function
2420 /// represents.
2421 TemplateSpecializationKind getTemplateSpecializationKind() const;
2422
2423 /// \brief Determine what kind of template instantiation this function
2424 /// represents.
2425 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2426 SourceLocation PointOfInstantiation = SourceLocation());
2427
2428 /// \brief Retrieve the (first) point of instantiation of a function template
2429 /// specialization or a member of a class template specialization.
2430 ///
2431 /// \returns the first point of instantiation, if this function was
2432 /// instantiated from a template; otherwise, returns an invalid source
2433 /// location.
2434 SourceLocation getPointOfInstantiation() const;
2435
2436 /// \brief Determine whether this is or was instantiated from an out-of-line
2437 /// definition of a member function.
2438 bool isOutOfLine() const override;
2439
2440 /// \brief Identify a memory copying or setting function.
2441 /// If the given function is a memory copy or setting function, returns
2442 /// the corresponding Builtin ID. If the function is not a memory function,
2443 /// returns 0.
2444 unsigned getMemoryFunctionKind() const;
2445
2446 // Implement isa/cast/dyncast/etc.
2447 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2448 static bool classofKind(Kind K) {
2449 return K >= firstFunction && K <= lastFunction;
2450 }
2451 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2452 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2453 }
2454 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2455 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2456 }
2457};
2458
2459/// FieldDecl - An instance of this class is created by Sema::ActOnField to
2460/// represent a member of a struct/union/class.
2461class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2462 unsigned BitField : 1;
2463 unsigned Mutable : 1;
2464 mutable unsigned CachedFieldIndex : 30;
2465
2466 /// The kinds of value we can store in InitializerOrBitWidth.
2467 ///
2468 /// Note that this is compatible with InClassInitStyle except for
2469 /// ISK_CapturedVLAType.
2470 enum InitStorageKind {
2471 /// If the pointer is null, there's nothing special. Otherwise,
2472 /// this is a bitfield and the pointer is the Expr* storing the
2473 /// bit-width.
2474 ISK_NoInit = (unsigned) ICIS_NoInit,
2475
2476 /// The pointer is an (optional due to delayed parsing) Expr*
2477 /// holding the copy-initializer.
2478 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2479
2480 /// The pointer is an (optional due to delayed parsing) Expr*
2481 /// holding the list-initializer.
2482 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2483
2484 /// The pointer is a VariableArrayType* that's been captured;
2485 /// the enclosing context is a lambda or captured statement.
2486 ISK_CapturedVLAType,
2487 };
2488
2489 /// If this is a bitfield with a default member initializer, this
2490 /// structure is used to represent the two expressions.
2491 struct InitAndBitWidth {
2492 Expr *Init;
2493 Expr *BitWidth;
2494 };
2495
2496 /// \brief Storage for either the bit-width, the in-class initializer, or
2497 /// both (via InitAndBitWidth), or the captured variable length array bound.
2498 ///
2499 /// If the storage kind is ISK_InClassCopyInit or
2500 /// ISK_InClassListInit, but the initializer is null, then this
2501 /// field has an in-class initializer that has not yet been parsed
2502 /// and attached.
2503 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2504 // overwhelmingly common case that we have none of these things.
2505 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2506
2507protected:
2508 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2509 SourceLocation IdLoc, IdentifierInfo *Id,
2510 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2511 InClassInitStyle InitStyle)
2512 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2513 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2514 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2515 if (BW)
2516 setBitWidth(BW);
2517 }
2518
2519public:
2520 friend class ASTDeclReader;
2521 friend class ASTDeclWriter;
2522
2523 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2524 SourceLocation StartLoc, SourceLocation IdLoc,
2525 IdentifierInfo *Id, QualType T,
2526 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2527 InClassInitStyle InitStyle);
2528
2529 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2530
2531 /// getFieldIndex - Returns the index of this field within its record,
2532 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2533 unsigned getFieldIndex() const;
2534
2535 /// isMutable - Determines whether this field is mutable (C++ only).
2536 bool isMutable() const { return Mutable; }
2537
2538 /// \brief Determines whether this field is a bitfield.
2539 bool isBitField() const { return BitField; }
2540
2541 /// @brief Determines whether this is an unnamed bitfield.
2542 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2543
2544 /// isAnonymousStructOrUnion - Determines whether this field is a
2545 /// representative for an anonymous struct or union. Such fields are
2546 /// unnamed and are implicitly generated by the implementation to
2547 /// store the data for the anonymous union or struct.
2548 bool isAnonymousStructOrUnion() const;
2549
2550 Expr *getBitWidth() const {
2551 if (!BitField)
2552 return nullptr;
2553 void *Ptr = InitStorage.getPointer();
2554 if (getInClassInitStyle())
2555 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2556 return static_cast<Expr*>(Ptr);
2557 }
2558
2559 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2560
2561 /// setBitWidth - Set the bit-field width for this member.
2562 // Note: used by some clients (i.e., do not remove it).
2563 void setBitWidth(Expr *Width) {
2564 assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2565, __extension__ __PRETTY_FUNCTION__))
2565 "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2565, __extension__ __PRETTY_FUNCTION__))
;
2566 assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified"
) ? void (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2566, __extension__ __PRETTY_FUNCTION__))
;
2567 InitStorage.setPointer(
2568 InitStorage.getInt()
2569 ? new (getASTContext())
2570 InitAndBitWidth{getInClassInitializer(), Width}
2571 : static_cast<void*>(Width));
2572 BitField = true;
2573 }
2574
2575 /// removeBitWidth - Remove the bit-field width from this member.
2576 // Note: used by some clients (i.e., do not remove it).
2577 void removeBitWidth() {
2578 assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove"
) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2578, __extension__ __PRETTY_FUNCTION__))
;
2579 InitStorage.setPointer(getInClassInitializer());
2580 BitField = false;
2581 }
2582
2583 /// Get the kind of (C++11) default member initializer that this field has.
2584 InClassInitStyle getInClassInitStyle() const {
2585 InitStorageKind storageKind = InitStorage.getInt();
2586 return (storageKind == ISK_CapturedVLAType
2587 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2588 }
2589
2590 /// Determine whether this member has a C++11 default member initializer.
2591 bool hasInClassInitializer() const {
2592 return getInClassInitStyle() != ICIS_NoInit;
2593 }
2594
2595 /// Get the C++11 default member initializer for this member, or null if one
2596 /// has not been set. If a valid declaration has a default member initializer,
2597 /// but this returns null, then we have not parsed and attached it yet.
2598 Expr *getInClassInitializer() const {
2599 if (!hasInClassInitializer())
2600 return nullptr;
2601 void *Ptr = InitStorage.getPointer();
2602 if (BitField)
2603 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2604 return static_cast<Expr*>(Ptr);
2605 }
2606
2607 /// setInClassInitializer - Set the C++11 in-class initializer for this
2608 /// member.
2609 void setInClassInitializer(Expr *Init) {
2610 assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() &&
!getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2610, __extension__ __PRETTY_FUNCTION__))
;
2611 if (BitField)
2612 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2613 else
2614 InitStorage.setPointer(Init);
2615 }
2616
2617 /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2618 /// member.
2619 void removeInClassInitializer() {
2620 assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() &&
"no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2620, __extension__ __PRETTY_FUNCTION__))
;
2621 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2622 }
2623
2624 /// \brief Determine whether this member captures the variable length array
2625 /// type.
2626 bool hasCapturedVLAType() const {
2627 return InitStorage.getInt() == ISK_CapturedVLAType;
2628 }
2629
2630 /// \brief Get the captured variable length array type.
2631 const VariableArrayType *getCapturedVLAType() const {
2632 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2633 InitStorage.getPointer())
2634 : nullptr;
2635 }
2636
2637 /// \brief Set the captured variable length array type for this field.
2638 void setCapturedVLAType(const VariableArrayType *VLAType);
2639
2640 /// getParent - Returns the parent of this field declaration, which
2641 /// is the struct in which this field is defined.
2642 const RecordDecl *getParent() const {
2643 return cast<RecordDecl>(getDeclContext());
2644 }
2645
2646 RecordDecl *getParent() {
2647 return cast<RecordDecl>(getDeclContext());
2648 }
2649
2650 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2651
2652 /// Retrieves the canonical declaration of this field.
2653 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2654 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2655
2656 // Implement isa/cast/dyncast/etc.
2657 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2658 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2659};
2660
2661/// EnumConstantDecl - An instance of this object exists for each enum constant
2662/// that is defined. For example, in "enum X {a,b}", each of a/b are
2663/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2664/// TagType for the X EnumDecl.
2665class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2666 Stmt *Init; // an integer constant expression
2667 llvm::APSInt Val; // The value.
2668
2669protected:
2670 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2671 IdentifierInfo *Id, QualType T, Expr *E,
2672 const llvm::APSInt &V)
2673 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2674
2675public:
2676 friend class StmtIteratorBase;
2677
2678 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2679 SourceLocation L, IdentifierInfo *Id,
2680 QualType T, Expr *E,
2681 const llvm::APSInt &V);
2682 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2683
2684 const Expr *getInitExpr() const { return (const Expr*) Init; }
2685 Expr *getInitExpr() { return (Expr*) Init; }
2686 const llvm::APSInt &getInitVal() const { return Val; }
2687
2688 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2689 void setInitVal(const llvm::APSInt &V) { Val = V; }
2690
2691 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2692
2693 /// Retrieves the canonical declaration of this enumerator.
2694 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2695 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2696
2697 // Implement isa/cast/dyncast/etc.
2698 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2699 static bool classofKind(Kind K) { return K == EnumConstant; }
2700};
2701
2702/// IndirectFieldDecl - An instance of this class is created to represent a
2703/// field injected from an anonymous union/struct into the parent scope.
2704/// IndirectFieldDecl are always implicit.
2705class IndirectFieldDecl : public ValueDecl,
2706 public Mergeable<IndirectFieldDecl> {
2707 NamedDecl **Chaining;
2708 unsigned ChainingSize;
2709
2710 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2711 DeclarationName N, QualType T,
2712 MutableArrayRef<NamedDecl *> CH);
2713
2714 void anchor() override;
2715
2716public:
2717 friend class ASTDeclReader;
2718
2719 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2720 SourceLocation L, IdentifierInfo *Id,
2721 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2722
2723 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2724
2725 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2726
2727 ArrayRef<NamedDecl *> chain() const {
2728 return llvm::makeArrayRef(Chaining, ChainingSize);
2729 }
2730 chain_iterator chain_begin() const { return chain().begin(); }
2731 chain_iterator chain_end() const { return chain().end(); }
2732
2733 unsigned getChainingSize() const { return ChainingSize; }
2734
2735 FieldDecl *getAnonField() const {
2736 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2736, __extension__ __PRETTY_FUNCTION__))
;
2737 return cast<FieldDecl>(chain().back());
2738 }
2739
2740 VarDecl *getVarDecl() const {
2741 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 2741, __extension__ __PRETTY_FUNCTION__))
;
2742 return dyn_cast<VarDecl>(chain().front());
2743 }
2744
2745 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2746 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2747
2748 // Implement isa/cast/dyncast/etc.
2749 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2750 static bool classofKind(Kind K) { return K == IndirectField; }
2751};
2752
2753/// TypeDecl - Represents a declaration of a type.
2754class TypeDecl : public NamedDecl {
2755 friend class ASTContext;
2756
2757 /// TypeForDecl - This indicates the Type object that represents
2758 /// this TypeDecl. It is a cache maintained by
2759 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2760 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2761 mutable const Type *TypeForDecl = nullptr;
2762
2763 /// LocStart - The start of the source range for this declaration.
2764 SourceLocation LocStart;
2765
2766 void anchor() override;
2767
2768protected:
2769 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2770 SourceLocation StartL = SourceLocation())
2771 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2772
2773public:
2774 // Low-level accessor. If you just want the type defined by this node,
2775 // check out ASTContext::getTypeDeclType or one of
2776 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2777 // already know the specific kind of node this is.
2778 const Type *getTypeForDecl() const { return TypeForDecl; }
2779 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2780
2781 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2782 void setLocStart(SourceLocation L) { LocStart = L; }
2783 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2784 if (LocStart.isValid())
2785 return SourceRange(LocStart, getLocation());
2786 else
2787 return SourceRange(getLocation());
2788 }
2789
2790 // Implement isa/cast/dyncast/etc.
2791 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2792 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2793};
2794
2795/// Base class for declarations which introduce a typedef-name.
2796class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2797 using ModedTInfo = std::pair<TypeSourceInfo *, QualType>;
2798 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *> MaybeModedTInfo;
2799
2800 // FIXME: This can be packed into the bitfields in Decl.
2801 /// If 0, we have not computed IsTransparentTag.
2802 /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
2803 mutable unsigned CacheIsTransparentTag : 2;
2804
2805 void anchor() override;
2806
2807protected:
2808 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2809 SourceLocation StartLoc, SourceLocation IdLoc,
2810 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2811 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2812 MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
2813
2814 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2815
2816 TypedefNameDecl *getNextRedeclarationImpl() override {
2817 return getNextRedeclaration();
2818 }
2819
2820 TypedefNameDecl *getPreviousDeclImpl() override {
2821 return getPreviousDecl();
2822 }
2823
2824 TypedefNameDecl *getMostRecentDeclImpl() override {
2825 return getMostRecentDecl();
2826 }
2827
2828public:
2829 using redecl_range = redeclarable_base::redecl_range;
2830 using redecl_iterator = redeclarable_base::redecl_iterator;
2831
2832 using redeclarable_base::redecls_begin;
2833 using redeclarable_base::redecls_end;
2834 using redeclarable_base::redecls;
2835 using redeclarable_base::getPreviousDecl;
2836 using redeclarable_base::getMostRecentDecl;
2837 using redeclarable_base::isFirstDecl;
2838
2839 bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2840
2841 TypeSourceInfo *getTypeSourceInfo() const {
2842 return isModed()
2843 ? MaybeModedTInfo.get<ModedTInfo*>()->first
2844 : MaybeModedTInfo.get<TypeSourceInfo*>();
2845 }
2846
2847 QualType getUnderlyingType() const {
2848 return isModed()
2849 ? MaybeModedTInfo.get<ModedTInfo*>()->second
2850 : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2851 }
2852
2853 void setTypeSourceInfo(TypeSourceInfo *newType) {
2854 MaybeModedTInfo = newType;
2855 }
2856
2857 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2858 MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2859 }
2860
2861 /// Retrieves the canonical declaration of this typedef-name.
2862 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2863 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2864
2865 /// Retrieves the tag declaration for which this is the typedef name for
2866 /// linkage purposes, if any.
2867 ///
2868 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2869 /// this typedef declaration.
2870 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2871
2872 /// Determines if this typedef shares a name and spelling location with its
2873 /// underlying tag type, as is the case with the NS_ENUM macro.
2874 bool isTransparentTag() const {
2875 if (CacheIsTransparentTag)
2876 return CacheIsTransparentTag & 0x2;
2877 return isTransparentTagSlow();
2878 }
2879
2880 // Implement isa/cast/dyncast/etc.
2881 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2882 static bool classofKind(Kind K) {
2883 return K >= firstTypedefName && K <= lastTypedefName;
2884 }
2885
2886private:
2887 bool isTransparentTagSlow() const;
2888};
2889
2890/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2891/// type specifier.
2892class TypedefDecl : public TypedefNameDecl {
2893 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2894 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2895 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2896
2897public:
2898 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2899 SourceLocation StartLoc, SourceLocation IdLoc,
2900 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2901 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2902
2903 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2904
2905 // Implement isa/cast/dyncast/etc.
2906 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2907 static bool classofKind(Kind K) { return K == Typedef; }
2908};
2909
2910/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2911/// alias-declaration.
2912class TypeAliasDecl : public TypedefNameDecl {
2913 /// The template for which this is the pattern, if any.
2914 TypeAliasTemplateDecl *Template;
2915
2916 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2917 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2918 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2919 Template(nullptr) {}
2920
2921public:
2922 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2923 SourceLocation StartLoc, SourceLocation IdLoc,
2924 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2925 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2926
2927 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2928
2929 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2930 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2931
2932 // Implement isa/cast/dyncast/etc.
2933 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2934 static bool classofKind(Kind K) { return K == TypeAlias; }
2935};
2936
2937/// TagDecl - Represents the declaration of a struct/union/class/enum.
2938class TagDecl
2939 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2940public:
2941 // This is really ugly.
2942 using TagKind = TagTypeKind;
2943
2944private:
2945 // FIXME: This can be packed into the bitfields in Decl.
2946 /// TagDeclKind - The TagKind enum.
2947 unsigned TagDeclKind : 3;
2948
2949 /// IsCompleteDefinition - True if this is a definition ("struct foo
2950 /// {};"), false if it is a declaration ("struct foo;"). It is not
2951 /// a definition until the definition has been fully processed.
2952 unsigned IsCompleteDefinition : 1;
2953
2954protected:
2955 /// IsBeingDefined - True if this is currently being defined.
2956 unsigned IsBeingDefined : 1;
2957
2958private:
2959 /// IsEmbeddedInDeclarator - True if this tag declaration is
2960 /// "embedded" (i.e., defined or declared for the very first time)
2961 /// in the syntax of a declarator.
2962 unsigned IsEmbeddedInDeclarator : 1;
2963
2964 /// \brief True if this tag is free standing, e.g. "struct foo;".
2965 unsigned IsFreeStanding : 1;
2966
2967protected:
2968 // These are used by (and only defined for) EnumDecl.
2969 unsigned NumPositiveBits : 8;
2970 unsigned NumNegativeBits : 8;
2971
2972 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2973 /// possible in C++11 mode.
2974 unsigned IsScoped : 1;
2975
2976 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2977 /// then this is true if the scoped enum was declared using the class
2978 /// tag, false if it was declared with the struct tag. No meaning is
2979 /// associated if this tag declaration is not a scoped enum.
2980 unsigned IsScopedUsingClassTag : 1;
2981
2982 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2983 /// possible in C++11, Microsoft extensions, or Objective C mode.
2984 unsigned IsFixed : 1;
2985
2986 /// \brief Indicates whether it is possible for declarations of this kind
2987 /// to have an out-of-date definition.
2988 ///
2989 /// This option is only enabled when modules are enabled.
2990 unsigned MayHaveOutOfDateDef : 1;
2991
2992 /// Has the full definition of this type been required by a use somewhere in
2993 /// the TU.
2994 unsigned IsCompleteDefinitionRequired : 1;
2995
2996private:
2997 SourceRange BraceRange;
2998
2999 // A struct representing syntactic qualifier info,
3000 // to be used for the (uncommon) case of out-of-line declarations.
3001 using ExtInfo = QualifierInfo;
3002
3003 /// \brief If the (out-of-line) tag declaration name
3004 /// is qualified, it points to the qualifier info (nns and range);
3005 /// otherwise, if the tag declaration is anonymous and it is part of
3006 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3007 /// otherwise, if the tag declaration is anonymous and it is used as a
3008 /// declaration specifier for variables, it points to the first VarDecl (used
3009 /// for mangling);
3010 /// otherwise, it is a null (TypedefNameDecl) pointer.
3011 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3012
3013 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3014 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3015 const ExtInfo *getExtInfo() const {
3016 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3017 }
3018
3019protected:
3020 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3021 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3022 SourceLocation StartL)
3023 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3024 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
3025 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
3026 IsCompleteDefinitionRequired(false),
3027 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3028 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\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3029, __extension__ __PRETTY_FUNCTION__))
3029 "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\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3029, __extension__ __PRETTY_FUNCTION__))
;
3030 setPreviousDecl(PrevDecl);
3031 }
3032
3033 using redeclarable_base = Redeclarable<TagDecl>;
3034
3035 TagDecl *getNextRedeclarationImpl() override {
3036 return getNextRedeclaration();
3037 }
3038
3039 TagDecl *getPreviousDeclImpl() override {
3040 return getPreviousDecl();
3041 }
3042
3043 TagDecl *getMostRecentDeclImpl() override {
3044 return getMostRecentDecl();
3045 }
3046
3047 /// @brief Completes the definition of this tag declaration.
3048 ///
3049 /// This is a helper function for derived classes.
3050 void completeDefinition();
3051
3052public:
3053 friend class ASTDeclReader;
3054 friend class ASTDeclWriter;
3055
3056 using redecl_range = redeclarable_base::redecl_range;
3057 using redecl_iterator = redeclarable_base::redecl_iterator;
3058
3059 using redeclarable_base::redecls_begin;
3060 using redeclarable_base::redecls_end;
3061 using redeclarable_base::redecls;
3062 using redeclarable_base::getPreviousDecl;
3063 using redeclarable_base::getMostRecentDecl;
3064 using redeclarable_base::isFirstDecl;
3065
3066 SourceRange getBraceRange() const { return BraceRange; }
3067 void setBraceRange(SourceRange R) { BraceRange = R; }
3068
3069 /// getInnerLocStart - Return SourceLocation representing start of source
3070 /// range ignoring outer template declarations.
3071 SourceLocation getInnerLocStart() const { return getLocStart(); }
3072
3073 /// getOuterLocStart - Return SourceLocation representing start of source
3074 /// range taking into account any outer template declarations.
3075 SourceLocation getOuterLocStart() const;
3076 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3077
3078 TagDecl *getCanonicalDecl() override;
3079 const TagDecl *getCanonicalDecl() const {
3080 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3081 }
3082
3083 /// isThisDeclarationADefinition() - Return true if this declaration
3084 /// is a completion definition of the type. Provided for consistency.
3085 bool isThisDeclarationADefinition() const {
3086 return isCompleteDefinition();
3087 }
3088
3089 /// isCompleteDefinition - Return true if this decl has its body
3090 /// fully specified.
3091 bool isCompleteDefinition() const {
3092 return IsCompleteDefinition;
3093 }
3094
3095 /// \brief Return true if this complete decl is
3096 /// required to be complete for some existing use.
3097 bool isCompleteDefinitionRequired() const {
3098 return IsCompleteDefinitionRequired;
3099 }
3100
3101 /// isBeingDefined - Return true if this decl is currently being defined.
3102 bool isBeingDefined() const {
3103 return IsBeingDefined;
3104 }
3105
3106 bool isEmbeddedInDeclarator() const {
3107 return IsEmbeddedInDeclarator;
3108 }
3109 void setEmbeddedInDeclarator(bool isInDeclarator) {
3110 IsEmbeddedInDeclarator = isInDeclarator;
3111 }
3112
3113 bool isFreeStanding() const { return IsFreeStanding; }
3114 void setFreeStanding(bool isFreeStanding = true) {
3115 IsFreeStanding = isFreeStanding;
3116 }
3117
3118 /// \brief Whether this declaration declares a type that is
3119 /// dependent, i.e., a type that somehow depends on template
3120 /// parameters.
3121 bool isDependentType() const { return isDependentContext(); }
3122
3123 /// @brief Starts the definition of this tag declaration.
3124 ///
3125 /// This method should be invoked at the beginning of the definition
3126 /// of this tag declaration. It will set the tag type into a state
3127 /// where it is in the process of being defined.
3128 void startDefinition();
3129
3130 /// getDefinition - Returns the TagDecl that actually defines this
3131 /// struct/union/class/enum. When determining whether or not a
3132 /// struct/union/class/enum has a definition, one should use this
3133 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3134 /// whether or not a specific TagDecl is defining declaration, not
3135 /// whether or not the struct/union/class/enum type is defined.
3136 /// This method returns NULL if there is no TagDecl that defines
3137 /// the struct/union/class/enum.
3138 TagDecl *getDefinition() const;
3139
3140 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
3141
3142 void setCompleteDefinitionRequired(bool V = true) {
3143 IsCompleteDefinitionRequired = V;
3144 }
3145
3146 StringRef getKindName() const {
3147 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3148 }
3149
3150 TagKind getTagKind() const {
3151 return TagKind(TagDeclKind);
3152 }
3153
3154 void setTagKind(TagKind TK) { TagDeclKind = TK; }
3155
3156 bool isStruct() const { return getTagKind() == TTK_Struct; }
3157 bool isInterface() const { return getTagKind() == TTK_Interface; }
3158 bool isClass() const { return getTagKind() == TTK_Class; }
3159 bool isUnion() const { return getTagKind() == TTK_Union; }
3160 bool isEnum() const { return getTagKind() == TTK_Enum; }
3161
3162 /// Is this tag type named, either directly or via being defined in
3163 /// a typedef of this type?
3164 ///
3165 /// C++11 [basic.link]p8:
3166 /// A type is said to have linkage if and only if:
3167 /// - it is a class or enumeration type that is named (or has a
3168 /// name for linkage purposes) and the name has linkage; ...
3169 /// C++11 [dcl.typedef]p9:
3170 /// If the typedef declaration defines an unnamed class (or enum),
3171 /// the first typedef-name declared by the declaration to be that
3172 /// class type (or enum type) is used to denote the class type (or
3173 /// enum type) for linkage purposes only.
3174 ///
3175 /// C does not have an analogous rule, but the same concept is
3176 /// nonetheless useful in some places.
3177 bool hasNameForLinkage() const {
3178 return (getDeclName() || getTypedefNameForAnonDecl());
3179 }
3180
3181 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3182 return hasExtInfo() ? nullptr
3183 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3184 }
3185
3186 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3187
3188 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3189 /// declaration, if it was present in the source.
3190 NestedNameSpecifier *getQualifier() const {
3191 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3192 : nullptr;
3193 }
3194
3195 /// \brief Retrieve the nested-name-specifier (with source-location
3196 /// information) that qualifies the name of this declaration, if it was
3197 /// present in the source.
3198 NestedNameSpecifierLoc getQualifierLoc() const {
3199 return hasExtInfo() ? getExtInfo()->QualifierLoc
3200 : NestedNameSpecifierLoc();
3201 }
3202
3203 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3204
3205 unsigned getNumTemplateParameterLists() const {
3206 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3207 }
3208
3209 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3210 assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3210, __extension__ __PRETTY_FUNCTION__))
;
3211 return getExtInfo()->TemplParamLists[i];
3212 }
3213
3214 void setTemplateParameterListsInfo(ASTContext &Context,
3215 ArrayRef<TemplateParameterList *> TPLists);
3216
3217 // Implement isa/cast/dyncast/etc.
3218 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3219 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3220
3221 static DeclContext *castToDeclContext(const TagDecl *D) {
3222 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3223 }
3224
3225 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3226 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3227 }
3228};
3229
3230/// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
3231/// with a fixed underlying type, and in C we allow them to be forward-declared
3232/// with no underlying type as an extension.
3233class EnumDecl : public TagDecl {
3234 /// IntegerType - This represent the integer type that the enum corresponds
3235 /// to for code generation purposes. Note that the enumerator constants may
3236 /// have a different type than this does.
3237 ///
3238 /// If the underlying integer type was explicitly stated in the source
3239 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3240 /// was automatically deduced somehow, and this is a Type*.
3241 ///
3242 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3243 /// some cases it won't.
3244 ///
3245 /// The underlying type of an enumeration never has any qualifiers, so
3246 /// we can get away with just storing a raw Type*, and thus save an
3247 /// extra pointer when TypeSourceInfo is needed.
3248 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3249
3250 /// PromotionType - The integer type that values of this type should
3251 /// promote to. In C, enumerators are generally of an integer type
3252 /// directly, but gcc-style large enumerators (and all enumerators
3253 /// in C++) are of the enum type instead.
3254 QualType PromotionType;
3255
3256 /// \brief If this enumeration is an instantiation of a member enumeration
3257 /// of a class template specialization, this is the member specialization
3258 /// information.
3259 MemberSpecializationInfo *SpecializationInfo = nullptr;
3260
3261 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3262 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3263 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3264 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3265 assert(Scoped || !ScopedUsingClassTag)(static_cast <bool> (Scoped || !ScopedUsingClassTag) ? void
(0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3265, __extension__ __PRETTY_FUNCTION__))
;
3266 IntegerType = (const Type *)nullptr;
3267 NumNegativeBits = 0;
3268 NumPositiveBits = 0;
3269 IsScoped = Scoped;
3270 IsScopedUsingClassTag = ScopedUsingClassTag;
3271 IsFixed = Fixed;
3272 }
3273
3274 void anchor() override;
3275
3276 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3277 TemplateSpecializationKind TSK);
3278public:
3279 friend class ASTDeclReader;
3280
3281 EnumDecl *getCanonicalDecl() override {
3282 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3283 }
3284 const EnumDecl *getCanonicalDecl() const {
3285 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3286 }
3287
3288 EnumDecl *getPreviousDecl() {
3289 return cast_or_null<EnumDecl>(
3290 static_cast<TagDecl *>(this)->getPreviousDecl());
3291 }
3292 const EnumDecl *getPreviousDecl() const {
3293 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3294 }
3295
3296 EnumDecl *getMostRecentDecl() {
3297 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3298 }
3299 const EnumDecl *getMostRecentDecl() const {
3300 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3301 }
3302
3303 EnumDecl *getDefinition() const {
3304 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3305 }
3306
3307 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3308 SourceLocation StartLoc, SourceLocation IdLoc,
3309 IdentifierInfo *Id, EnumDecl *PrevDecl,
3310 bool IsScoped, bool IsScopedUsingClassTag,
3311 bool IsFixed);
3312 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3313
3314 /// completeDefinition - When created, the EnumDecl corresponds to a
3315 /// forward-declared enum. This method is used to mark the
3316 /// declaration as being defined; it's enumerators have already been
3317 /// added (via DeclContext::addDecl). NewType is the new underlying
3318 /// type of the enumeration type.
3319 void completeDefinition(QualType NewType,
3320 QualType PromotionType,
3321 unsigned NumPositiveBits,
3322 unsigned NumNegativeBits);
3323
3324 // enumerator_iterator - Iterates through the enumerators of this
3325 // enumeration.
3326 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3327 using enumerator_range =
3328 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3329
3330 enumerator_range enumerators() const {
3331 return enumerator_range(enumerator_begin(), enumerator_end());
3332 }
3333
3334 enumerator_iterator enumerator_begin() const {
3335 const EnumDecl *E = getDefinition();
3336 if (!E)
3337 E = this;
3338 return enumerator_iterator(E->decls_begin());
3339 }
3340
3341 enumerator_iterator enumerator_end() const {
3342 const EnumDecl *E = getDefinition();
3343 if (!E)
3344 E = this;
3345 return enumerator_iterator(E->decls_end());
3346 }
3347
3348 /// getPromotionType - Return the integer type that enumerators
3349 /// should promote to.
3350 QualType getPromotionType() const { return PromotionType; }
3351
3352 /// \brief Set the promotion type.
3353 void setPromotionType(QualType T) { PromotionType = T; }
3354
3355 /// getIntegerType - Return the integer type this enum decl corresponds to.
3356 /// This returns a null QualType for an enum forward definition with no fixed
3357 /// underlying type.
3358 QualType getIntegerType() const {
3359 if (!IntegerType)
3360 return QualType();
3361 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3362 return QualType(T, 0);
3363 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3364 }
3365
3366 /// \brief Set the underlying integer type.
3367 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3368
3369 /// \brief Set the underlying integer type source info.
3370 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3371
3372 /// \brief Return the type source info for the underlying integer type,
3373 /// if no type source info exists, return 0.
3374 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3375 return IntegerType.dyn_cast<TypeSourceInfo*>();
3376 }
3377
3378 /// \brief Retrieve the source range that covers the underlying type if
3379 /// specified.
3380 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3381
3382 /// \brief Returns the width in bits required to store all the
3383 /// non-negative enumerators of this enum.
3384 unsigned getNumPositiveBits() const {
3385 return NumPositiveBits;
3386 }
3387 void setNumPositiveBits(unsigned Num) {
3388 NumPositiveBits = Num;
3389 assert(NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (NumPositiveBits == Num && "can't store this bitcount"
) ? void (0) : __assert_fail ("NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3389, __extension__ __PRETTY_FUNCTION__))
;
3390 }
3391
3392 /// \brief Returns the width in bits required to store all the
3393 /// negative enumerators of this enum. These widths include
3394 /// the rightmost leading 1; that is:
3395 ///
3396 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3397 /// ------------------------ ------- -----------------
3398 /// -1 1111111 1
3399 /// -10 1110110 5
3400 /// -101 1001011 8
3401 unsigned getNumNegativeBits() const {
3402 return NumNegativeBits;
3403 }
3404 void setNumNegativeBits(unsigned Num) {
3405 NumNegativeBits = Num;
3406 }
3407
3408 /// \brief Returns true if this is a C++11 scoped enumeration.
3409 bool isScoped() const {
3410 return IsScoped;
3411 }
3412
3413 /// \brief Returns true if this is a C++11 scoped enumeration.
3414 bool isScopedUsingClassTag() const {
3415 return IsScopedUsingClassTag;
3416 }
3417
3418 /// \brief Returns true if this is an Objective-C, C++11, or
3419 /// Microsoft-style enumeration with a fixed underlying type.
3420 bool isFixed() const {
3421 return IsFixed;
3422 }
3423
3424 /// \brief Returns true if this can be considered a complete type.
3425 bool isComplete() const {
3426 return isCompleteDefinition() || isFixed();
3427 }
3428
3429 /// Returns true if this enum is either annotated with
3430 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3431 bool isClosed() const;
3432
3433 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3434 /// with enum_extensibility(open).
3435 bool isClosedFlag() const;
3436
3437 /// Returns true if this enum is annotated with neither flag_enum nor
3438 /// enum_extensibility(open).
3439 bool isClosedNonFlag() const;
3440
3441 /// \brief Retrieve the enum definition from which this enumeration could
3442 /// be instantiated, if it is an instantiation (rather than a non-template).
3443 EnumDecl *getTemplateInstantiationPattern() const;
3444
3445 /// \brief Returns the enumeration (declared within the template)
3446 /// from which this enumeration type was instantiated, or NULL if
3447 /// this enumeration was not instantiated from any template.
3448 EnumDecl *getInstantiatedFromMemberEnum() const;
3449
3450 /// \brief If this enumeration is a member of a specialization of a
3451 /// templated class, determine what kind of template specialization
3452 /// or instantiation this is.
3453 TemplateSpecializationKind getTemplateSpecializationKind() const;
3454
3455 /// \brief For an enumeration member that was instantiated from a member
3456 /// enumeration of a templated class, set the template specialiation kind.
3457 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3458 SourceLocation PointOfInstantiation = SourceLocation());
3459
3460 /// \brief If this enumeration is an instantiation of a member enumeration of
3461 /// a class template specialization, retrieves the member specialization
3462 /// information.
3463 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3464 return SpecializationInfo;
3465 }
3466
3467 /// \brief Specify that this enumeration is an instantiation of the
3468 /// member enumeration ED.
3469 void setInstantiationOfMemberEnum(EnumDecl *ED,
3470 TemplateSpecializationKind TSK) {
3471 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3472 }
3473
3474 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3475 static bool classofKind(Kind K) { return K == Enum; }
3476};
3477
3478/// RecordDecl - Represents a struct/union/class. For example:
3479/// struct X; // Forward declaration, no "body".
3480/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3481/// This decl will be marked invalid if *any* members are invalid.
3482class RecordDecl : public TagDecl {
3483 friend class DeclContext;
3484
3485 // FIXME: This can be packed into the bitfields in Decl.
3486 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3487 /// array member (e.g. int X[]) or if this union contains a struct that does.
3488 /// If so, this cannot be contained in arrays or other structs as a member.
3489 bool HasFlexibleArrayMember : 1;
3490
3491 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3492 /// or union.
3493 bool AnonymousStructOrUnion : 1;
3494
3495 /// HasObjectMember - This is true if this struct has at least one member
3496 /// containing an Objective-C object pointer type.
3497 bool HasObjectMember : 1;
3498
3499 /// HasVolatileMember - This is true if struct has at least one member of
3500 /// 'volatile' type.
3501 bool HasVolatileMember : 1;
3502
3503 /// \brief Whether the field declarations of this record have been loaded
3504 /// from external storage. To avoid unnecessary deserialization of
3505 /// methods/nested types we allow deserialization of just the fields
3506 /// when needed.
3507 mutable bool LoadedFieldsFromExternalStorage : 1;
3508
3509protected:
3510 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3511 SourceLocation StartLoc, SourceLocation IdLoc,
3512 IdentifierInfo *Id, RecordDecl *PrevDecl);
3513
3514public:
3515 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3516 SourceLocation StartLoc, SourceLocation IdLoc,
3517 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3518 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3519
3520 RecordDecl *getPreviousDecl() {
3521 return cast_or_null<RecordDecl>(
3522 static_cast<TagDecl *>(this)->getPreviousDecl());
3523 }
3524 const RecordDecl *getPreviousDecl() const {
3525 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3526 }
3527
3528 RecordDecl *getMostRecentDecl() {
3529 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3530 }
3531 const RecordDecl *getMostRecentDecl() const {
3532 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3533 }
3534
3535 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3536 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3537
3538 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3539 /// or union. To be an anonymous struct or union, it must have been
3540 /// declared without a name and there must be no objects of this
3541 /// type declared, e.g.,
3542 /// @code
3543 /// union { int i; float f; };
3544 /// @endcode
3545 /// is an anonymous union but neither of the following are:
3546 /// @code
3547 /// union X { int i; float f; };
3548 /// union { int i; float f; } obj;
3549 /// @endcode
3550 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3551 void setAnonymousStructOrUnion(bool Anon) {
3552 AnonymousStructOrUnion = Anon;
3553 }
3554
3555 bool hasObjectMember() const { return HasObjectMember; }
3556 void setHasObjectMember (bool val) { HasObjectMember = val; }
3557
3558 bool hasVolatileMember() const { return HasVolatileMember; }
3559 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3560
3561 bool hasLoadedFieldsFromExternalStorage() const {
3562 return LoadedFieldsFromExternalStorage;
3563 }
3564 void setHasLoadedFieldsFromExternalStorage(bool val) {
3565 LoadedFieldsFromExternalStorage = val;
3566 }
3567
3568 /// \brief Determines whether this declaration represents the
3569 /// injected class name.
3570 ///
3571 /// The injected class name in C++ is the name of the class that
3572 /// appears inside the class itself. For example:
3573 ///
3574 /// \code
3575 /// struct C {
3576 /// // C is implicitly declared here as a synonym for the class name.
3577 /// };
3578 ///
3579 /// C::C c; // same as "C c;"
3580 /// \endcode
3581 bool isInjectedClassName() const;
3582
3583 /// \brief Determine whether this record is a class describing a lambda
3584 /// function object.
3585 bool isLambda() const;
3586
3587 /// \brief Determine whether this record is a record for captured variables in
3588 /// CapturedStmt construct.
3589 bool isCapturedRecord() const;
3590
3591 /// \brief Mark the record as a record for captured variables in CapturedStmt
3592 /// construct.
3593 void setCapturedRecord();
3594
3595 /// getDefinition - Returns the RecordDecl that actually defines
3596 /// this struct/union/class. When determining whether or not a
3597 /// struct/union/class is completely defined, one should use this
3598 /// method as opposed to 'isCompleteDefinition'.
3599 /// 'isCompleteDefinition' indicates whether or not a specific
3600 /// RecordDecl is a completed definition, not whether or not the
3601 /// record type is defined. This method returns NULL if there is
3602 /// no RecordDecl that defines the struct/union/tag.
3603 RecordDecl *getDefinition() const {
3604 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3605 }
3606
3607 // Iterator access to field members. The field iterator only visits
3608 // the non-static data members of this class, ignoring any static
3609 // data members, functions, constructors, destructors, etc.
3610 using field_iterator = specific_decl_iterator<FieldDecl>;
3611 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3612
3613 field_range fields() const { return field_range(field_begin(), field_end()); }
3614 field_iterator field_begin() const;
3615
3616 field_iterator field_end() const {
3617 return field_iterator(decl_iterator());
3618 }
3619
3620 // field_empty - Whether there are any fields (non-static data
3621 // members) in this record.
3622 bool field_empty() const {
3623 return field_begin() == field_end();
3624 }
3625
3626 /// completeDefinition - Notes that the definition of this type is
3627 /// now complete.
3628 virtual void completeDefinition();
3629
3630 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3631 static bool classofKind(Kind K) {
3632 return K >= firstRecord && K <= lastRecord;
3633 }
3634
3635 /// \brief Get whether or not this is an ms_struct which can
3636 /// be turned on with an attribute, pragma, or -mms-bitfields
3637 /// commandline option.
3638 bool isMsStruct(const ASTContext &C) const;
3639
3640 /// \brief Whether we are allowed to insert extra padding between fields.
3641 /// These padding are added to help AddressSanitizer detect
3642 /// intra-object-overflow bugs.
3643 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3644
3645 /// Finds the first data member which has a name.
3646 /// nullptr is returned if no named data member exists.
3647 const FieldDecl *findFirstNamedDataMember() const;
3648
3649private:
3650 /// \brief Deserialize just the fields.
3651 void LoadFieldsFromExternalStorage() const;
3652};
3653
3654class FileScopeAsmDecl : public Decl {
3655 StringLiteral *AsmString;
3656 SourceLocation RParenLoc;
3657
3658 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3659 SourceLocation StartL, SourceLocation EndL)
3660 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3661
3662 virtual void anchor();
3663
3664public:
3665 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3666 StringLiteral *Str, SourceLocation AsmLoc,
3667 SourceLocation RParenLoc);
3668
3669 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3670
3671 SourceLocation getAsmLoc() const { return getLocation(); }
3672 SourceLocation getRParenLoc() const { return RParenLoc; }
3673 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3674 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3675 return SourceRange(getAsmLoc(), getRParenLoc());
3676 }
3677
3678 const StringLiteral *getAsmString() const { return AsmString; }
3679 StringLiteral *getAsmString() { return AsmString; }
3680 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3681
3682 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3683 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3684};
3685
3686/// BlockDecl - This represents a block literal declaration, which is like an
3687/// unnamed FunctionDecl. For example:
3688/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3689class BlockDecl : public Decl, public DeclContext {
3690public:
3691 /// A class which contains all the information about a particular
3692 /// captured value.
3693 class Capture {
3694 enum {
3695 flag_isByRef = 0x1,
3696 flag_isNested = 0x2
3697 };
3698
3699 /// The variable being captured.
3700 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3701
3702 /// The copy expression, expressed in terms of a DeclRef (or
3703 /// BlockDeclRef) to the captured variable. Only required if the
3704 /// variable has a C++ class type.
3705 Expr *CopyExpr;
3706
3707 public:
3708 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3709 : VariableAndFlags(variable,
3710 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3711 CopyExpr(copy) {}
3712
3713 /// The variable being captured.
3714 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3715
3716 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3717 /// variable.
3718 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3719
3720 /// Whether this is a nested capture, i.e. the variable captured
3721 /// is not from outside the immediately enclosing function/block.
3722 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3723
3724 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3725 Expr *getCopyExpr() const { return CopyExpr; }
3726 void setCopyExpr(Expr *e) { CopyExpr = e; }
3727 };
3728
3729private:
3730 // FIXME: This can be packed into the bitfields in Decl.
3731 bool IsVariadic : 1;
3732 bool CapturesCXXThis : 1;
3733 bool BlockMissingReturnType : 1;
3734 bool IsConversionFromLambda : 1;
3735
3736 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3737 /// parameters of this function. This is null if a prototype or if there are
3738 /// no formals.
3739 ParmVarDecl **ParamInfo = nullptr;
3740 unsigned NumParams = 0;
3741
3742 Stmt *Body = nullptr;
3743 TypeSourceInfo *SignatureAsWritten = nullptr;
3744
3745 const Capture *Captures = nullptr;
3746 unsigned NumCaptures = 0;
3747
3748 unsigned ManglingNumber = 0;
3749 Decl *ManglingContextDecl = nullptr;
3750
3751protected:
3752 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3753 : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false),
3754 CapturesCXXThis(false), BlockMissingReturnType(true),
3755 IsConversionFromLambda(false) {}
3756
3757public:
3758 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3759 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3760
3761 SourceLocation getCaretLocation() const { return getLocation(); }
3762
3763 bool isVariadic() const { return IsVariadic; }
3764 void setIsVariadic(bool value) { IsVariadic = value; }
3765
3766 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3767 Stmt *getBody() const override { return (Stmt*) Body; }
3768 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3769
3770 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3771 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3772
3773 // ArrayRef access to formal parameters.
3774 ArrayRef<ParmVarDecl *> parameters() const {
3775 return {ParamInfo, getNumParams()};
3776 }
3777 MutableArrayRef<ParmVarDecl *> parameters() {
3778 return {ParamInfo, getNumParams()};
3779 }
3780
3781 // Iterator access to formal parameters.
3782 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3783 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3784
3785 bool param_empty() const { return parameters().empty(); }
3786 param_iterator param_begin() { return parameters().begin(); }
3787 param_iterator param_end() { return parameters().end(); }
3788 param_const_iterator param_begin() const { return parameters().begin(); }
3789 param_const_iterator param_end() const { return parameters().end(); }
3790 size_t param_size() const { return parameters().size(); }
3791
3792 unsigned getNumParams() const { return NumParams; }
3793
3794 const ParmVarDecl *getParamDecl(unsigned i) const {
3795 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3795, __extension__ __PRETTY_FUNCTION__))
;
3796 return ParamInfo[i];
3797 }
3798 ParmVarDecl *getParamDecl(unsigned i) {
3799 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3799, __extension__ __PRETTY_FUNCTION__))
;
3800 return ParamInfo[i];
3801 }
3802
3803 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3804
3805 /// hasCaptures - True if this block (or its nested blocks) captures
3806 /// anything of local storage from its enclosing scopes.
3807 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3808
3809 /// getNumCaptures - Returns the number of captured variables.
3810 /// Does not include an entry for 'this'.
3811 unsigned getNumCaptures() const { return NumCaptures; }
3812
3813 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3814
3815 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3816
3817 capture_const_iterator capture_begin() const { return captures().begin(); }
3818 capture_const_iterator capture_end() const { return captures().end(); }
3819
3820 bool capturesCXXThis() const { return CapturesCXXThis; }
3821 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3822 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3823
3824 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3825 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3826
3827 bool capturesVariable(const VarDecl *var) const;
3828
3829 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3830 bool CapturesCXXThis);
3831
3832 unsigned getBlockManglingNumber() const {
3833 return ManglingNumber;
3834 }
3835
3836 Decl *getBlockManglingContextDecl() const {
3837 return ManglingContextDecl;
3838 }
3839
3840 void setBlockMangling(unsigned Number, Decl *Ctx) {
3841 ManglingNumber = Number;
3842 ManglingContextDecl = Ctx;
3843 }
3844
3845 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3846
3847 // Implement isa/cast/dyncast/etc.
3848 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3849 static bool classofKind(Kind K) { return K == Block; }
3850 static DeclContext *castToDeclContext(const BlockDecl *D) {
3851 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3852 }
3853 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3854 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3855 }
3856};
3857
3858/// \brief This represents the body of a CapturedStmt, and serves as its
3859/// DeclContext.
3860class CapturedDecl final
3861 : public Decl,
3862 public DeclContext,
3863 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3864protected:
3865 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3866 return NumParams;
3867 }
3868
3869private:
3870 /// \brief The number of parameters to the outlined function.
3871 unsigned NumParams;
3872
3873 /// \brief The position of context parameter in list of parameters.
3874 unsigned ContextParam;
3875
3876 /// \brief The body of the outlined function.
3877 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3878
3879 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3880
3881 ImplicitParamDecl *const *getParams() const {
3882 return getTrailingObjects<ImplicitParamDecl *>();
3883 }
3884
3885 ImplicitParamDecl **getParams() {
3886 return getTrailingObjects<ImplicitParamDecl *>();
3887 }
3888
3889public:
3890 friend class ASTDeclReader;
3891 friend class ASTDeclWriter;
3892 friend TrailingObjects;
3893
3894 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3895 unsigned NumParams);
3896 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3897 unsigned NumParams);
3898
3899 Stmt *getBody() const override;
3900 void setBody(Stmt *B);
3901
3902 bool isNothrow() const;
3903 void setNothrow(bool Nothrow = true);
3904
3905 unsigned getNumParams() const { return NumParams; }
3906
3907 ImplicitParamDecl *getParam(unsigned i) const {
3908 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3908, __extension__ __PRETTY_FUNCTION__))
;
3909 return getParams()[i];
3910 }
3911 void setParam(unsigned i, ImplicitParamDecl *P) {
3912 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3912, __extension__ __PRETTY_FUNCTION__))
;
3913 getParams()[i] = P;
3914 }
3915
3916 // ArrayRef interface to parameters.
3917 ArrayRef<ImplicitParamDecl *> parameters() const {
3918 return {getParams(), getNumParams()};
3919 }
3920 MutableArrayRef<ImplicitParamDecl *> parameters() {
3921 return {getParams(), getNumParams()};
3922 }
3923
3924 /// \brief Retrieve the parameter containing captured variables.
3925 ImplicitParamDecl *getContextParam() const {
3926 assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void
(0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3926, __extension__ __PRETTY_FUNCTION__))
;
3927 return getParam(ContextParam);
3928 }
3929 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3930 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 3930, __extension__ __PRETTY_FUNCTION__))
;
3931 ContextParam = i;
3932 setParam(i, P);
3933 }
3934 unsigned getContextParamPosition() const { return ContextParam; }
3935
3936 using param_iterator = ImplicitParamDecl *const *;
3937 using param_range = llvm::iterator_range<param_iterator>;
3938
3939 /// \brief Retrieve an iterator pointing to the first parameter decl.
3940 param_iterator param_begin() const { return getParams(); }
3941 /// \brief Retrieve an iterator one past the last parameter decl.
3942 param_iterator param_end() const { return getParams() + NumParams; }
3943
3944 // Implement isa/cast/dyncast/etc.
3945 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3946 static bool classofKind(Kind K) { return K == Captured; }
3947 static DeclContext *castToDeclContext(const CapturedDecl *D) {
3948 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3949 }
3950 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3951 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3952 }
3953};
3954
3955/// \brief Describes a module import declaration, which makes the contents
3956/// of the named module visible in the current translation unit.
3957///
3958/// An import declaration imports the named module (or submodule). For example:
3959/// \code
3960/// @import std.vector;
3961/// \endcode
3962///
3963/// Import declarations can also be implicitly generated from
3964/// \#include/\#import directives.
3965class ImportDecl final : public Decl,
3966 llvm::TrailingObjects<ImportDecl, SourceLocation> {
3967 friend class ASTContext;
3968 friend class ASTDeclReader;
3969 friend class ASTReader;
3970 friend TrailingObjects;
3971
3972 /// \brief The imported module, along with a bit that indicates whether
3973 /// we have source-location information for each identifier in the module
3974 /// name.
3975 ///
3976 /// When the bit is false, we only have a single source location for the
3977 /// end of the import declaration.
3978 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3979
3980 /// \brief The next import in the list of imports local to the translation
3981 /// unit being parsed (not loaded from an AST file).
3982 ImportDecl *NextLocalImport = nullptr;
3983
3984 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3985 ArrayRef<SourceLocation> IdentifierLocs);
3986
3987 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3988 SourceLocation EndLoc);
3989
3990 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
3991
3992public:
3993 /// \brief Create a new module import declaration.
3994 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3995 SourceLocation StartLoc, Module *Imported,
3996 ArrayRef<SourceLocation> IdentifierLocs);
3997
3998 /// \brief Create a new module import declaration for an implicitly-generated
3999 /// import.
4000 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4001 SourceLocation StartLoc, Module *Imported,
4002 SourceLocation EndLoc);
4003
4004 /// \brief Create a new, deserialized module import declaration.
4005 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4006 unsigned NumLocations);
4007
4008 /// \brief Retrieve the module that was imported by the import declaration.
4009 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4010
4011 /// \brief Retrieves the locations of each of the identifiers that make up
4012 /// the complete module name in the import declaration.
4013 ///
4014 /// This will return an empty array if the locations of the individual
4015 /// identifiers aren't available.
4016 ArrayRef<SourceLocation> getIdentifierLocs() const;
4017
4018 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4019
4020 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4021 static bool classofKind(Kind K) { return K == Import; }
4022};
4023
4024/// \brief Represents a C++ Modules TS module export declaration.
4025///
4026/// For example:
4027/// \code
4028/// export void foo();
4029/// \endcode
4030class ExportDecl final : public Decl, public DeclContext {
4031 virtual void anchor();
4032
4033private:
4034 friend class ASTDeclReader;
4035
4036 /// \brief The source location for the right brace (if valid).
4037 SourceLocation RBraceLoc;
4038
4039 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4040 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4041 RBraceLoc(SourceLocation()) {}
4042
4043public:
4044 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4045 SourceLocation ExportLoc);
4046 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4047
4048 SourceLocation getExportLoc() const { return getLocation(); }
4049 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4050 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4051
4052 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
4053 if (RBraceLoc.isValid())
4054 return RBraceLoc;
4055 // No braces: get the end location of the (only) declaration in context
4056 // (if present).
4057 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
4058 }
4059
4060 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4061 return SourceRange(getLocation(), getLocEnd());
4062 }
4063
4064 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4065 static bool classofKind(Kind K) { return K == Export; }
4066 static DeclContext *castToDeclContext(const ExportDecl *D) {
4067 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4068 }
4069 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4070 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4071 }
4072};
4073
4074/// \brief Represents an empty-declaration.
4075class EmptyDecl : public Decl {
4076 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4077
4078 virtual void anchor();
4079
4080public:
4081 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4082 SourceLocation L);
4083 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4084
4085 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4086 static bool classofKind(Kind K) { return K == Empty; }
4087};
4088
4089/// Insertion operator for diagnostics. This allows sending NamedDecl's
4090/// into a diagnostic with <<.
4091inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4092 const NamedDecl* ND) {
4093 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4094 DiagnosticsEngine::ak_nameddecl);
4095 return DB;
4096}
4097inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4098 const NamedDecl* ND) {
4099 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4100 DiagnosticsEngine::ak_nameddecl);
4101 return PD;
4102}
4103
4104template<typename decl_type>
4105void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4106 // Note: This routine is implemented here because we need both NamedDecl
4107 // and Redeclarable to be defined.
4108 assert(RedeclLink.NextIsLatest() &&(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 4109, __extension__ __PRETTY_FUNCTION__))
4109 "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 4109, __extension__ __PRETTY_FUNCTION__))
;
4110
4111 if (PrevDecl) {
4112 // Point to previous. Make sure that this is actually the most recent
4113 // redeclaration, or we can build invalid chains. If the most recent
4114 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4115 First = PrevDecl->getFirstDecl();
4116 assert(First->RedeclLink.NextIsLatest() && "Expected first")(static_cast <bool> (First->RedeclLink.NextIsLatest(
) && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.NextIsLatest() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 4116, __extension__ __PRETTY_FUNCTION__))
;
4117 decl_type *MostRecent = First->getNextRedeclaration();
4118 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4119
4120 // If the declaration was previously visible, a redeclaration of it remains
4121 // visible even if it wouldn't be visible by itself.
4122 static_cast<decl_type*>(this)->IdentifierNamespace |=
4123 MostRecent->getIdentifierNamespace() &
4124 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4125 } else {
4126 // Make this first.
4127 First = static_cast<decl_type*>(this);
4128 }
4129
4130 // First one will point to this one as latest.
4131 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4132
4133 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 4134, __extension__ __PRETTY_FUNCTION__))
4134 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-6.0~svn318801/tools/clang/include/clang/AST/Decl.h"
, 4134, __extension__ __PRETTY_FUNCTION__))
;
4135}
4136
4137// Inline function definitions.
4138
4139/// \brief Check if the given decl is complete.
4140///
4141/// We use this function to break a cycle between the inline definitions in
4142/// Type.h and Decl.h.
4143inline bool IsEnumDeclComplete(EnumDecl *ED) {
4144 return ED->isComplete();
4145}
4146
4147/// \brief Check if the given decl is scoped.
4148///
4149/// We use this function to break a cycle between the inline definitions in
4150/// Type.h and Decl.h.
4151inline bool IsEnumDeclScoped(EnumDecl *ED) {
4152 return ED->isScoped();
4153}
4154
4155} // namespace clang
4156
4157#endif // LLVM_CLANG_AST_DECL_H