DeclBase.h 98 KB

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