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