DeclBase.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  1. //===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Decl and DeclContext classes.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/DeclBase.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclContextInternals.h"
  20. #include "clang/AST/DeclFriend.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/DependentDiagnostic.h"
  24. #include "clang/AST/ExternalASTSource.h"
  25. #include "clang/AST/Stmt.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/AST/Type.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "llvm/ADT/DenseMap.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <algorithm>
  32. using namespace clang;
  33. //===----------------------------------------------------------------------===//
  34. // Statistics
  35. //===----------------------------------------------------------------------===//
  36. #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
  37. #define ABSTRACT_DECL(DECL)
  38. #include "clang/AST/DeclNodes.inc"
  39. void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
  40. unsigned ID,
  41. unsigned Size) {
  42. // Allocate an extra 8 bytes worth of storage, which ensures that the
  43. // resulting pointer will still be 8-byte aligned.
  44. void *Start = Context.Allocate(Size + 8);
  45. void *Result = (char*)Start + 8;
  46. unsigned *PrefixPtr = (unsigned *)Result - 2;
  47. // Zero out the first 4 bytes; this is used to store the owning module ID.
  48. PrefixPtr[0] = 0;
  49. // Store the global declaration ID in the second 4 bytes.
  50. PrefixPtr[1] = ID;
  51. return Result;
  52. }
  53. Module *Decl::getOwningModuleSlow() const {
  54. assert(isFromASTFile() && "Not from AST file?");
  55. return getASTContext().getExternalSource()->getModule(getOwningModuleID());
  56. }
  57. const char *Decl::getDeclKindName() const {
  58. switch (DeclKind) {
  59. default: llvm_unreachable("Declaration not in DeclNodes.inc!");
  60. #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
  61. #define ABSTRACT_DECL(DECL)
  62. #include "clang/AST/DeclNodes.inc"
  63. }
  64. }
  65. void Decl::setInvalidDecl(bool Invalid) {
  66. InvalidDecl = Invalid;
  67. if (Invalid && !isa<ParmVarDecl>(this)) {
  68. // Defensive maneuver for ill-formed code: we're likely not to make it to
  69. // a point where we set the access specifier, so default it to "public"
  70. // to avoid triggering asserts elsewhere in the front end.
  71. setAccess(AS_public);
  72. }
  73. }
  74. const char *DeclContext::getDeclKindName() const {
  75. switch (DeclKind) {
  76. default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
  77. #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
  78. #define ABSTRACT_DECL(DECL)
  79. #include "clang/AST/DeclNodes.inc"
  80. }
  81. }
  82. bool Decl::StatisticsEnabled = false;
  83. void Decl::EnableStatistics() {
  84. StatisticsEnabled = true;
  85. }
  86. void Decl::PrintStats() {
  87. llvm::errs() << "\n*** Decl Stats:\n";
  88. int totalDecls = 0;
  89. #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
  90. #define ABSTRACT_DECL(DECL)
  91. #include "clang/AST/DeclNodes.inc"
  92. llvm::errs() << " " << totalDecls << " decls total.\n";
  93. int totalBytes = 0;
  94. #define DECL(DERIVED, BASE) \
  95. if (n##DERIVED##s > 0) { \
  96. totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
  97. llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
  98. << sizeof(DERIVED##Decl) << " each (" \
  99. << n##DERIVED##s * sizeof(DERIVED##Decl) \
  100. << " bytes)\n"; \
  101. }
  102. #define ABSTRACT_DECL(DECL)
  103. #include "clang/AST/DeclNodes.inc"
  104. llvm::errs() << "Total bytes = " << totalBytes << "\n";
  105. }
  106. void Decl::add(Kind k) {
  107. switch (k) {
  108. #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
  109. #define ABSTRACT_DECL(DECL)
  110. #include "clang/AST/DeclNodes.inc"
  111. }
  112. }
  113. bool Decl::isTemplateParameterPack() const {
  114. if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
  115. return TTP->isParameterPack();
  116. if (const NonTypeTemplateParmDecl *NTTP
  117. = dyn_cast<NonTypeTemplateParmDecl>(this))
  118. return NTTP->isParameterPack();
  119. if (const TemplateTemplateParmDecl *TTP
  120. = dyn_cast<TemplateTemplateParmDecl>(this))
  121. return TTP->isParameterPack();
  122. return false;
  123. }
  124. bool Decl::isParameterPack() const {
  125. if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
  126. return Parm->isParameterPack();
  127. return isTemplateParameterPack();
  128. }
  129. bool Decl::isFunctionOrFunctionTemplate() const {
  130. if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
  131. return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
  132. return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
  133. }
  134. bool Decl::isTemplateDecl() const {
  135. return isa<TemplateDecl>(this);
  136. }
  137. const DeclContext *Decl::getParentFunctionOrMethod() const {
  138. for (const DeclContext *DC = getDeclContext();
  139. DC && !DC->isTranslationUnit() && !DC->isNamespace();
  140. DC = DC->getParent())
  141. if (DC->isFunctionOrMethod())
  142. return DC;
  143. return 0;
  144. }
  145. //===----------------------------------------------------------------------===//
  146. // PrettyStackTraceDecl Implementation
  147. //===----------------------------------------------------------------------===//
  148. void PrettyStackTraceDecl::print(raw_ostream &OS) const {
  149. SourceLocation TheLoc = Loc;
  150. if (TheLoc.isInvalid() && TheDecl)
  151. TheLoc = TheDecl->getLocation();
  152. if (TheLoc.isValid()) {
  153. TheLoc.print(OS, SM);
  154. OS << ": ";
  155. }
  156. OS << Message;
  157. if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
  158. OS << " '" << DN->getQualifiedNameAsString() << '\'';
  159. OS << '\n';
  160. }
  161. //===----------------------------------------------------------------------===//
  162. // Decl Implementation
  163. //===----------------------------------------------------------------------===//
  164. // Out-of-line virtual method providing a home for Decl.
  165. Decl::~Decl() { }
  166. void Decl::setDeclContext(DeclContext *DC) {
  167. DeclCtx = DC;
  168. }
  169. void Decl::setLexicalDeclContext(DeclContext *DC) {
  170. if (DC == getLexicalDeclContext())
  171. return;
  172. if (isInSemaDC()) {
  173. setDeclContextsImpl(getDeclContext(), DC, getASTContext());
  174. } else {
  175. getMultipleDC()->LexicalDC = DC;
  176. }
  177. }
  178. void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
  179. ASTContext &Ctx) {
  180. if (SemaDC == LexicalDC) {
  181. DeclCtx = SemaDC;
  182. } else {
  183. Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
  184. MDC->SemanticDC = SemaDC;
  185. MDC->LexicalDC = LexicalDC;
  186. DeclCtx = MDC;
  187. }
  188. }
  189. bool Decl::isInAnonymousNamespace() const {
  190. const DeclContext *DC = getDeclContext();
  191. do {
  192. if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
  193. if (ND->isAnonymousNamespace())
  194. return true;
  195. } while ((DC = DC->getParent()));
  196. return false;
  197. }
  198. TranslationUnitDecl *Decl::getTranslationUnitDecl() {
  199. if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
  200. return TUD;
  201. DeclContext *DC = getDeclContext();
  202. assert(DC && "This decl is not contained in a translation unit!");
  203. while (!DC->isTranslationUnit()) {
  204. DC = DC->getParent();
  205. assert(DC && "This decl is not contained in a translation unit!");
  206. }
  207. return cast<TranslationUnitDecl>(DC);
  208. }
  209. ASTContext &Decl::getASTContext() const {
  210. return getTranslationUnitDecl()->getASTContext();
  211. }
  212. ASTMutationListener *Decl::getASTMutationListener() const {
  213. return getASTContext().getASTMutationListener();
  214. }
  215. unsigned Decl::getMaxAlignment() const {
  216. if (!hasAttrs())
  217. return 0;
  218. unsigned Align = 0;
  219. const AttrVec &V = getAttrs();
  220. ASTContext &Ctx = getASTContext();
  221. specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
  222. for (; I != E; ++I)
  223. Align = std::max(Align, I->getAlignment(Ctx));
  224. return Align;
  225. }
  226. bool Decl::isUsed(bool CheckUsedAttr) const {
  227. if (Used)
  228. return true;
  229. // Check for used attribute.
  230. if (CheckUsedAttr && hasAttr<UsedAttr>())
  231. return true;
  232. return false;
  233. }
  234. bool Decl::isReferenced() const {
  235. if (Referenced)
  236. return true;
  237. // Check redeclarations.
  238. for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
  239. if (I->Referenced)
  240. return true;
  241. return false;
  242. }
  243. /// \brief Determine the availability of the given declaration based on
  244. /// the target platform.
  245. ///
  246. /// When it returns an availability result other than \c AR_Available,
  247. /// if the \p Message parameter is non-NULL, it will be set to a
  248. /// string describing why the entity is unavailable.
  249. ///
  250. /// FIXME: Make these strings localizable, since they end up in
  251. /// diagnostics.
  252. static AvailabilityResult CheckAvailability(ASTContext &Context,
  253. const AvailabilityAttr *A,
  254. std::string *Message) {
  255. StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
  256. StringRef PrettyPlatformName
  257. = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
  258. if (PrettyPlatformName.empty())
  259. PrettyPlatformName = TargetPlatform;
  260. VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
  261. if (TargetMinVersion.empty())
  262. return AR_Available;
  263. // Match the platform name.
  264. if (A->getPlatform()->getName() != TargetPlatform)
  265. return AR_Available;
  266. std::string HintMessage;
  267. if (!A->getMessage().empty()) {
  268. HintMessage = " - ";
  269. HintMessage += A->getMessage();
  270. }
  271. // Make sure that this declaration has not been marked 'unavailable'.
  272. if (A->getUnavailable()) {
  273. if (Message) {
  274. Message->clear();
  275. llvm::raw_string_ostream Out(*Message);
  276. Out << "not available on " << PrettyPlatformName
  277. << HintMessage;
  278. }
  279. return AR_Unavailable;
  280. }
  281. // Make sure that this declaration has already been introduced.
  282. if (!A->getIntroduced().empty() &&
  283. TargetMinVersion < A->getIntroduced()) {
  284. if (Message) {
  285. Message->clear();
  286. llvm::raw_string_ostream Out(*Message);
  287. Out << "introduced in " << PrettyPlatformName << ' '
  288. << A->getIntroduced() << HintMessage;
  289. }
  290. return AR_NotYetIntroduced;
  291. }
  292. // Make sure that this declaration hasn't been obsoleted.
  293. if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
  294. if (Message) {
  295. Message->clear();
  296. llvm::raw_string_ostream Out(*Message);
  297. Out << "obsoleted in " << PrettyPlatformName << ' '
  298. << A->getObsoleted() << HintMessage;
  299. }
  300. return AR_Unavailable;
  301. }
  302. // Make sure that this declaration hasn't been deprecated.
  303. if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
  304. if (Message) {
  305. Message->clear();
  306. llvm::raw_string_ostream Out(*Message);
  307. Out << "first deprecated in " << PrettyPlatformName << ' '
  308. << A->getDeprecated() << HintMessage;
  309. }
  310. return AR_Deprecated;
  311. }
  312. return AR_Available;
  313. }
  314. AvailabilityResult Decl::getAvailability(std::string *Message) const {
  315. AvailabilityResult Result = AR_Available;
  316. std::string ResultMessage;
  317. for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
  318. if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
  319. if (Result >= AR_Deprecated)
  320. continue;
  321. if (Message)
  322. ResultMessage = Deprecated->getMessage();
  323. Result = AR_Deprecated;
  324. continue;
  325. }
  326. if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
  327. if (Message)
  328. *Message = Unavailable->getMessage();
  329. return AR_Unavailable;
  330. }
  331. if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
  332. AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
  333. Message);
  334. if (AR == AR_Unavailable)
  335. return AR_Unavailable;
  336. if (AR > Result) {
  337. Result = AR;
  338. if (Message)
  339. ResultMessage.swap(*Message);
  340. }
  341. continue;
  342. }
  343. }
  344. if (Message)
  345. Message->swap(ResultMessage);
  346. return Result;
  347. }
  348. bool Decl::canBeWeakImported(bool &IsDefinition) const {
  349. IsDefinition = false;
  350. // Variables, if they aren't definitions.
  351. if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
  352. if (!Var->hasExternalStorage() || Var->getInit()) {
  353. IsDefinition = true;
  354. return false;
  355. }
  356. return true;
  357. // Functions, if they aren't definitions.
  358. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
  359. if (FD->hasBody()) {
  360. IsDefinition = true;
  361. return false;
  362. }
  363. return true;
  364. // Objective-C classes, if this is the non-fragile runtime.
  365. } else if (isa<ObjCInterfaceDecl>(this) &&
  366. getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
  367. return true;
  368. // Nothing else.
  369. } else {
  370. return false;
  371. }
  372. }
  373. bool Decl::isWeakImported() const {
  374. bool IsDefinition;
  375. if (!canBeWeakImported(IsDefinition))
  376. return false;
  377. for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
  378. if (isa<WeakImportAttr>(*A))
  379. return true;
  380. if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
  381. if (CheckAvailability(getASTContext(), Availability, 0)
  382. == AR_NotYetIntroduced)
  383. return true;
  384. }
  385. }
  386. return false;
  387. }
  388. unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
  389. switch (DeclKind) {
  390. case Function:
  391. case CXXMethod:
  392. case CXXConstructor:
  393. case CXXDestructor:
  394. case CXXConversion:
  395. case EnumConstant:
  396. case Var:
  397. case ImplicitParam:
  398. case ParmVar:
  399. case NonTypeTemplateParm:
  400. case ObjCMethod:
  401. case ObjCProperty:
  402. return IDNS_Ordinary;
  403. case Label:
  404. return IDNS_Label;
  405. case IndirectField:
  406. return IDNS_Ordinary | IDNS_Member;
  407. case ObjCCompatibleAlias:
  408. case ObjCInterface:
  409. return IDNS_Ordinary | IDNS_Type;
  410. case Typedef:
  411. case TypeAlias:
  412. case TypeAliasTemplate:
  413. case UnresolvedUsingTypename:
  414. case TemplateTypeParm:
  415. return IDNS_Ordinary | IDNS_Type;
  416. case UsingShadow:
  417. return 0; // we'll actually overwrite this later
  418. case UnresolvedUsingValue:
  419. return IDNS_Ordinary | IDNS_Using;
  420. case Using:
  421. return IDNS_Using;
  422. case ObjCProtocol:
  423. return IDNS_ObjCProtocol;
  424. case Field:
  425. case ObjCAtDefsField:
  426. case ObjCIvar:
  427. return IDNS_Member;
  428. case Record:
  429. case CXXRecord:
  430. case Enum:
  431. return IDNS_Tag | IDNS_Type;
  432. case Namespace:
  433. case NamespaceAlias:
  434. return IDNS_Namespace;
  435. case FunctionTemplate:
  436. return IDNS_Ordinary;
  437. case ClassTemplate:
  438. case TemplateTemplateParm:
  439. return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
  440. // Never have names.
  441. case Friend:
  442. case FriendTemplate:
  443. case AccessSpec:
  444. case LinkageSpec:
  445. case FileScopeAsm:
  446. case StaticAssert:
  447. case ObjCPropertyImpl:
  448. case Block:
  449. case TranslationUnit:
  450. case UsingDirective:
  451. case ClassTemplateSpecialization:
  452. case ClassTemplatePartialSpecialization:
  453. case ClassScopeFunctionSpecialization:
  454. case ObjCImplementation:
  455. case ObjCCategory:
  456. case ObjCCategoryImpl:
  457. case Import:
  458. // Never looked up by name.
  459. return 0;
  460. }
  461. llvm_unreachable("Invalid DeclKind!");
  462. }
  463. void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
  464. assert(!HasAttrs && "Decl already contains attrs.");
  465. AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
  466. assert(AttrBlank.empty() && "HasAttrs was wrong?");
  467. AttrBlank = attrs;
  468. HasAttrs = true;
  469. }
  470. void Decl::dropAttrs() {
  471. if (!HasAttrs) return;
  472. HasAttrs = false;
  473. getASTContext().eraseDeclAttrs(this);
  474. }
  475. const AttrVec &Decl::getAttrs() const {
  476. assert(HasAttrs && "No attrs to get!");
  477. return getASTContext().getDeclAttrs(this);
  478. }
  479. void Decl::swapAttrs(Decl *RHS) {
  480. bool HasLHSAttr = this->HasAttrs;
  481. bool HasRHSAttr = RHS->HasAttrs;
  482. // Usually, neither decl has attrs, nothing to do.
  483. if (!HasLHSAttr && !HasRHSAttr) return;
  484. // If 'this' has no attrs, swap the other way.
  485. if (!HasLHSAttr)
  486. return RHS->swapAttrs(this);
  487. ASTContext &Context = getASTContext();
  488. // Handle the case when both decls have attrs.
  489. if (HasRHSAttr) {
  490. std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
  491. return;
  492. }
  493. // Otherwise, LHS has an attr and RHS doesn't.
  494. Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
  495. Context.eraseDeclAttrs(this);
  496. this->HasAttrs = false;
  497. RHS->HasAttrs = true;
  498. }
  499. Decl *Decl::castFromDeclContext (const DeclContext *D) {
  500. Decl::Kind DK = D->getDeclKind();
  501. switch(DK) {
  502. #define DECL(NAME, BASE)
  503. #define DECL_CONTEXT(NAME) \
  504. case Decl::NAME: \
  505. return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
  506. #define DECL_CONTEXT_BASE(NAME)
  507. #include "clang/AST/DeclNodes.inc"
  508. default:
  509. #define DECL(NAME, BASE)
  510. #define DECL_CONTEXT_BASE(NAME) \
  511. if (DK >= first##NAME && DK <= last##NAME) \
  512. return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
  513. #include "clang/AST/DeclNodes.inc"
  514. llvm_unreachable("a decl that inherits DeclContext isn't handled");
  515. }
  516. }
  517. DeclContext *Decl::castToDeclContext(const Decl *D) {
  518. Decl::Kind DK = D->getKind();
  519. switch(DK) {
  520. #define DECL(NAME, BASE)
  521. #define DECL_CONTEXT(NAME) \
  522. case Decl::NAME: \
  523. return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
  524. #define DECL_CONTEXT_BASE(NAME)
  525. #include "clang/AST/DeclNodes.inc"
  526. default:
  527. #define DECL(NAME, BASE)
  528. #define DECL_CONTEXT_BASE(NAME) \
  529. if (DK >= first##NAME && DK <= last##NAME) \
  530. return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
  531. #include "clang/AST/DeclNodes.inc"
  532. llvm_unreachable("a decl that inherits DeclContext isn't handled");
  533. }
  534. }
  535. SourceLocation Decl::getBodyRBrace() const {
  536. // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
  537. // FunctionDecl stores EndRangeLoc for this purpose.
  538. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
  539. const FunctionDecl *Definition;
  540. if (FD->hasBody(Definition))
  541. return Definition->getSourceRange().getEnd();
  542. return SourceLocation();
  543. }
  544. if (Stmt *Body = getBody())
  545. return Body->getSourceRange().getEnd();
  546. return SourceLocation();
  547. }
  548. void Decl::CheckAccessDeclContext() const {
  549. #ifndef NDEBUG
  550. // Suppress this check if any of the following hold:
  551. // 1. this is the translation unit (and thus has no parent)
  552. // 2. this is a template parameter (and thus doesn't belong to its context)
  553. // 3. this is a non-type template parameter
  554. // 4. the context is not a record
  555. // 5. it's invalid
  556. // 6. it's a C++0x static_assert.
  557. if (isa<TranslationUnitDecl>(this) ||
  558. isa<TemplateTypeParmDecl>(this) ||
  559. isa<NonTypeTemplateParmDecl>(this) ||
  560. !isa<CXXRecordDecl>(getDeclContext()) ||
  561. isInvalidDecl() ||
  562. isa<StaticAssertDecl>(this) ||
  563. // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
  564. // as DeclContext (?).
  565. isa<ParmVarDecl>(this) ||
  566. // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
  567. // AS_none as access specifier.
  568. isa<CXXRecordDecl>(this) ||
  569. isa<ClassScopeFunctionSpecializationDecl>(this))
  570. return;
  571. assert(Access != AS_none &&
  572. "Access specifier is AS_none inside a record decl");
  573. #endif
  574. }
  575. DeclContext *Decl::getNonClosureContext() {
  576. return getDeclContext()->getNonClosureAncestor();
  577. }
  578. DeclContext *DeclContext::getNonClosureAncestor() {
  579. DeclContext *DC = this;
  580. // This is basically "while (DC->isClosure()) DC = DC->getParent();"
  581. // except that it's significantly more efficient to cast to a known
  582. // decl type and call getDeclContext() than to call getParent().
  583. while (isa<BlockDecl>(DC))
  584. DC = cast<BlockDecl>(DC)->getDeclContext();
  585. assert(!DC->isClosure());
  586. return DC;
  587. }
  588. //===----------------------------------------------------------------------===//
  589. // DeclContext Implementation
  590. //===----------------------------------------------------------------------===//
  591. bool DeclContext::classof(const Decl *D) {
  592. switch (D->getKind()) {
  593. #define DECL(NAME, BASE)
  594. #define DECL_CONTEXT(NAME) case Decl::NAME:
  595. #define DECL_CONTEXT_BASE(NAME)
  596. #include "clang/AST/DeclNodes.inc"
  597. return true;
  598. default:
  599. #define DECL(NAME, BASE)
  600. #define DECL_CONTEXT_BASE(NAME) \
  601. if (D->getKind() >= Decl::first##NAME && \
  602. D->getKind() <= Decl::last##NAME) \
  603. return true;
  604. #include "clang/AST/DeclNodes.inc"
  605. return false;
  606. }
  607. }
  608. DeclContext::~DeclContext() { }
  609. /// \brief Find the parent context of this context that will be
  610. /// used for unqualified name lookup.
  611. ///
  612. /// Generally, the parent lookup context is the semantic context. However, for
  613. /// a friend function the parent lookup context is the lexical context, which
  614. /// is the class in which the friend is declared.
  615. DeclContext *DeclContext::getLookupParent() {
  616. // FIXME: Find a better way to identify friends
  617. if (isa<FunctionDecl>(this))
  618. if (getParent()->getRedeclContext()->isFileContext() &&
  619. getLexicalParent()->getRedeclContext()->isRecord())
  620. return getLexicalParent();
  621. return getParent();
  622. }
  623. bool DeclContext::isInlineNamespace() const {
  624. return isNamespace() &&
  625. cast<NamespaceDecl>(this)->isInline();
  626. }
  627. bool DeclContext::isDependentContext() const {
  628. if (isFileContext())
  629. return false;
  630. if (isa<ClassTemplatePartialSpecializationDecl>(this))
  631. return true;
  632. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
  633. if (Record->getDescribedClassTemplate())
  634. return true;
  635. if (Record->isDependentLambda())
  636. return true;
  637. }
  638. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
  639. if (Function->getDescribedFunctionTemplate())
  640. return true;
  641. // Friend function declarations are dependent if their *lexical*
  642. // context is dependent.
  643. if (cast<Decl>(this)->getFriendObjectKind())
  644. return getLexicalParent()->isDependentContext();
  645. }
  646. return getParent() && getParent()->isDependentContext();
  647. }
  648. bool DeclContext::isTransparentContext() const {
  649. if (DeclKind == Decl::Enum)
  650. return !cast<EnumDecl>(this)->isScoped();
  651. else if (DeclKind == Decl::LinkageSpec)
  652. return true;
  653. return false;
  654. }
  655. bool DeclContext::isExternCContext() const {
  656. const DeclContext *DC = this;
  657. while (DC->DeclKind != Decl::TranslationUnit) {
  658. if (DC->DeclKind == Decl::LinkageSpec)
  659. return cast<LinkageSpecDecl>(DC)->getLanguage()
  660. == LinkageSpecDecl::lang_c;
  661. DC = DC->getParent();
  662. }
  663. return false;
  664. }
  665. bool DeclContext::Encloses(const DeclContext *DC) const {
  666. if (getPrimaryContext() != this)
  667. return getPrimaryContext()->Encloses(DC);
  668. for (; DC; DC = DC->getParent())
  669. if (DC->getPrimaryContext() == this)
  670. return true;
  671. return false;
  672. }
  673. DeclContext *DeclContext::getPrimaryContext() {
  674. switch (DeclKind) {
  675. case Decl::TranslationUnit:
  676. case Decl::LinkageSpec:
  677. case Decl::Block:
  678. // There is only one DeclContext for these entities.
  679. return this;
  680. case Decl::Namespace:
  681. // The original namespace is our primary context.
  682. return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
  683. case Decl::ObjCMethod:
  684. return this;
  685. case Decl::ObjCInterface:
  686. if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
  687. return Def;
  688. return this;
  689. case Decl::ObjCProtocol:
  690. if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
  691. return Def;
  692. return this;
  693. case Decl::ObjCCategory:
  694. return this;
  695. case Decl::ObjCImplementation:
  696. case Decl::ObjCCategoryImpl:
  697. return this;
  698. default:
  699. if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
  700. // If this is a tag type that has a definition or is currently
  701. // being defined, that definition is our primary context.
  702. TagDecl *Tag = cast<TagDecl>(this);
  703. assert(isa<TagType>(Tag->TypeForDecl) ||
  704. isa<InjectedClassNameType>(Tag->TypeForDecl));
  705. if (TagDecl *Def = Tag->getDefinition())
  706. return Def;
  707. if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
  708. const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
  709. if (TagTy->isBeingDefined())
  710. // FIXME: is it necessarily being defined in the decl
  711. // that owns the type?
  712. return TagTy->getDecl();
  713. }
  714. return Tag;
  715. }
  716. assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
  717. "Unknown DeclContext kind");
  718. return this;
  719. }
  720. }
  721. void
  722. DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
  723. Contexts.clear();
  724. if (DeclKind != Decl::Namespace) {
  725. Contexts.push_back(this);
  726. return;
  727. }
  728. NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
  729. for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
  730. N = N->getPreviousDecl())
  731. Contexts.push_back(N);
  732. std::reverse(Contexts.begin(), Contexts.end());
  733. }
  734. std::pair<Decl *, Decl *>
  735. DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
  736. bool FieldsAlreadyLoaded) {
  737. // Build up a chain of declarations via the Decl::NextInContextAndBits field.
  738. Decl *FirstNewDecl = 0;
  739. Decl *PrevDecl = 0;
  740. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  741. if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
  742. continue;
  743. Decl *D = Decls[I];
  744. if (PrevDecl)
  745. PrevDecl->NextInContextAndBits.setPointer(D);
  746. else
  747. FirstNewDecl = D;
  748. PrevDecl = D;
  749. }
  750. return std::make_pair(FirstNewDecl, PrevDecl);
  751. }
  752. /// \brief Load the declarations within this lexical storage from an
  753. /// external source.
  754. void
  755. DeclContext::LoadLexicalDeclsFromExternalStorage() const {
  756. ExternalASTSource *Source = getParentASTContext().getExternalSource();
  757. assert(hasExternalLexicalStorage() && Source && "No external storage?");
  758. // Notify that we have a DeclContext that is initializing.
  759. ExternalASTSource::Deserializing ADeclContext(Source);
  760. // Load the external declarations, if any.
  761. SmallVector<Decl*, 64> Decls;
  762. ExternalLexicalStorage = false;
  763. switch (Source->FindExternalLexicalDecls(this, Decls)) {
  764. case ELR_Success:
  765. break;
  766. case ELR_Failure:
  767. case ELR_AlreadyLoaded:
  768. return;
  769. }
  770. if (Decls.empty())
  771. return;
  772. // We may have already loaded just the fields of this record, in which case
  773. // we need to ignore them.
  774. bool FieldsAlreadyLoaded = false;
  775. if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
  776. FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
  777. // Splice the newly-read declarations into the beginning of the list
  778. // of declarations.
  779. Decl *ExternalFirst, *ExternalLast;
  780. llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
  781. FieldsAlreadyLoaded);
  782. ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
  783. FirstDecl = ExternalFirst;
  784. if (!LastDecl)
  785. LastDecl = ExternalLast;
  786. }
  787. DeclContext::lookup_result
  788. ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
  789. DeclarationName Name) {
  790. ASTContext &Context = DC->getParentASTContext();
  791. StoredDeclsMap *Map;
  792. if (!(Map = DC->LookupPtr.getPointer()))
  793. Map = DC->CreateStoredDeclsMap(Context);
  794. StoredDeclsList &List = (*Map)[Name];
  795. assert(List.isNull());
  796. (void) List;
  797. return DeclContext::lookup_result();
  798. }
  799. DeclContext::lookup_result
  800. ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
  801. DeclarationName Name,
  802. ArrayRef<NamedDecl*> Decls) {
  803. ASTContext &Context = DC->getParentASTContext();
  804. StoredDeclsMap *Map;
  805. if (!(Map = DC->LookupPtr.getPointer()))
  806. Map = DC->CreateStoredDeclsMap(Context);
  807. StoredDeclsList &List = (*Map)[Name];
  808. for (ArrayRef<NamedDecl*>::iterator
  809. I = Decls.begin(), E = Decls.end(); I != E; ++I) {
  810. if (List.isNull())
  811. List.setOnlyValue(*I);
  812. else
  813. List.AddSubsequentDecl(*I);
  814. }
  815. return List.getLookupResult();
  816. }
  817. DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
  818. return decl_iterator(FirstDecl);
  819. }
  820. DeclContext::decl_iterator DeclContext::decls_begin() const {
  821. if (hasExternalLexicalStorage())
  822. LoadLexicalDeclsFromExternalStorage();
  823. return decl_iterator(FirstDecl);
  824. }
  825. bool DeclContext::decls_empty() const {
  826. if (hasExternalLexicalStorage())
  827. LoadLexicalDeclsFromExternalStorage();
  828. return !FirstDecl;
  829. }
  830. void DeclContext::removeDecl(Decl *D) {
  831. assert(D->getLexicalDeclContext() == this &&
  832. "decl being removed from non-lexical context");
  833. assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
  834. "decl is not in decls list");
  835. // Remove D from the decl chain. This is O(n) but hopefully rare.
  836. if (D == FirstDecl) {
  837. if (D == LastDecl)
  838. FirstDecl = LastDecl = 0;
  839. else
  840. FirstDecl = D->NextInContextAndBits.getPointer();
  841. } else {
  842. for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
  843. assert(I && "decl not found in linked list");
  844. if (I->NextInContextAndBits.getPointer() == D) {
  845. I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
  846. if (D == LastDecl) LastDecl = I;
  847. break;
  848. }
  849. }
  850. }
  851. // Mark that D is no longer in the decl chain.
  852. D->NextInContextAndBits.setPointer(0);
  853. // Remove D from the lookup table if necessary.
  854. if (isa<NamedDecl>(D)) {
  855. NamedDecl *ND = cast<NamedDecl>(D);
  856. // Remove only decls that have a name
  857. if (!ND->getDeclName()) return;
  858. StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
  859. if (!Map) return;
  860. StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
  861. assert(Pos != Map->end() && "no lookup entry for decl");
  862. if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
  863. Pos->second.remove(ND);
  864. }
  865. }
  866. void DeclContext::addHiddenDecl(Decl *D) {
  867. assert(D->getLexicalDeclContext() == this &&
  868. "Decl inserted into wrong lexical context");
  869. assert(!D->getNextDeclInContext() && D != LastDecl &&
  870. "Decl already inserted into a DeclContext");
  871. if (FirstDecl) {
  872. LastDecl->NextInContextAndBits.setPointer(D);
  873. LastDecl = D;
  874. } else {
  875. FirstDecl = LastDecl = D;
  876. }
  877. // Notify a C++ record declaration that we've added a member, so it can
  878. // update it's class-specific state.
  879. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
  880. Record->addedMember(D);
  881. // If this is a newly-created (not de-serialized) import declaration, wire
  882. // it in to the list of local import declarations.
  883. if (!D->isFromASTFile()) {
  884. if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
  885. D->getASTContext().addedLocalImportDecl(Import);
  886. }
  887. }
  888. void DeclContext::addDecl(Decl *D) {
  889. addHiddenDecl(D);
  890. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  891. ND->getDeclContext()->getPrimaryContext()->
  892. makeDeclVisibleInContextWithFlags(ND, false, true);
  893. }
  894. void DeclContext::addDeclInternal(Decl *D) {
  895. addHiddenDecl(D);
  896. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  897. ND->getDeclContext()->getPrimaryContext()->
  898. makeDeclVisibleInContextWithFlags(ND, true, true);
  899. }
  900. /// shouldBeHidden - Determine whether a declaration which was declared
  901. /// within its semantic context should be invisible to qualified name lookup.
  902. static bool shouldBeHidden(NamedDecl *D) {
  903. // Skip unnamed declarations.
  904. if (!D->getDeclName())
  905. return true;
  906. // Skip entities that can't be found by name lookup into a particular
  907. // context.
  908. if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
  909. D->isTemplateParameter())
  910. return true;
  911. // Skip template specializations.
  912. // FIXME: This feels like a hack. Should DeclarationName support
  913. // template-ids, or is there a better way to keep specializations
  914. // from being visible?
  915. if (isa<ClassTemplateSpecializationDecl>(D))
  916. return true;
  917. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  918. if (FD->isFunctionTemplateSpecialization())
  919. return true;
  920. return false;
  921. }
  922. /// buildLookup - Build the lookup data structure with all of the
  923. /// declarations in this DeclContext (and any other contexts linked
  924. /// to it or transparent contexts nested within it) and return it.
  925. StoredDeclsMap *DeclContext::buildLookup() {
  926. assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
  927. if (!LookupPtr.getInt())
  928. return LookupPtr.getPointer();
  929. SmallVector<DeclContext *, 2> Contexts;
  930. collectAllContexts(Contexts);
  931. for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
  932. buildLookupImpl(Contexts[I]);
  933. // We no longer have any lazy decls.
  934. LookupPtr.setInt(false);
  935. return LookupPtr.getPointer();
  936. }
  937. /// buildLookupImpl - Build part of the lookup data structure for the
  938. /// declarations contained within DCtx, which will either be this
  939. /// DeclContext, a DeclContext linked to it, or a transparent context
  940. /// nested within it.
  941. void DeclContext::buildLookupImpl(DeclContext *DCtx) {
  942. for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
  943. I != E; ++I) {
  944. Decl *D = *I;
  945. // Insert this declaration into the lookup structure, but only if
  946. // it's semantically within its decl context. Any other decls which
  947. // should be found in this context are added eagerly.
  948. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  949. if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
  950. makeDeclVisibleInContextImpl(ND, false);
  951. // If this declaration is itself a transparent declaration context
  952. // or inline namespace, add the members of this declaration of that
  953. // context (recursively).
  954. if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
  955. if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
  956. buildLookupImpl(InnerCtx);
  957. }
  958. }
  959. DeclContext::lookup_result
  960. DeclContext::lookup(DeclarationName Name) {
  961. assert(DeclKind != Decl::LinkageSpec &&
  962. "Should not perform lookups into linkage specs!");
  963. DeclContext *PrimaryContext = getPrimaryContext();
  964. if (PrimaryContext != this)
  965. return PrimaryContext->lookup(Name);
  966. if (hasExternalVisibleStorage()) {
  967. // If a PCH has a result for this name, and we have a local declaration, we
  968. // will have imported the PCH result when adding the local declaration.
  969. // FIXME: For modules, we could have had more declarations added by module
  970. // imoprts since we saw the declaration of the local name.
  971. if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
  972. StoredDeclsMap::iterator I = Map->find(Name);
  973. if (I != Map->end())
  974. return I->second.getLookupResult();
  975. }
  976. ExternalASTSource *Source = getParentASTContext().getExternalSource();
  977. return Source->FindExternalVisibleDeclsByName(this, Name);
  978. }
  979. StoredDeclsMap *Map = LookupPtr.getPointer();
  980. if (LookupPtr.getInt())
  981. Map = buildLookup();
  982. if (!Map)
  983. return lookup_result(lookup_iterator(0), lookup_iterator(0));
  984. StoredDeclsMap::iterator I = Map->find(Name);
  985. if (I == Map->end())
  986. return lookup_result(lookup_iterator(0), lookup_iterator(0));
  987. return I->second.getLookupResult();
  988. }
  989. void DeclContext::localUncachedLookup(DeclarationName Name,
  990. SmallVectorImpl<NamedDecl *> &Results) {
  991. Results.clear();
  992. // If there's no external storage, just perform a normal lookup and copy
  993. // the results.
  994. if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
  995. lookup_result LookupResults = lookup(Name);
  996. Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
  997. return;
  998. }
  999. // If we have a lookup table, check there first. Maybe we'll get lucky.
  1000. if (Name) {
  1001. if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
  1002. StoredDeclsMap::iterator Pos = Map->find(Name);
  1003. if (Pos != Map->end()) {
  1004. Results.insert(Results.end(),
  1005. Pos->second.getLookupResult().begin(),
  1006. Pos->second.getLookupResult().end());
  1007. return;
  1008. }
  1009. }
  1010. }
  1011. // Slow case: grovel through the declarations in our chain looking for
  1012. // matches.
  1013. for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
  1014. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  1015. if (ND->getDeclName() == Name)
  1016. Results.push_back(ND);
  1017. }
  1018. }
  1019. DeclContext *DeclContext::getRedeclContext() {
  1020. DeclContext *Ctx = this;
  1021. // Skip through transparent contexts.
  1022. while (Ctx->isTransparentContext())
  1023. Ctx = Ctx->getParent();
  1024. return Ctx;
  1025. }
  1026. DeclContext *DeclContext::getEnclosingNamespaceContext() {
  1027. DeclContext *Ctx = this;
  1028. // Skip through non-namespace, non-translation-unit contexts.
  1029. while (!Ctx->isFileContext())
  1030. Ctx = Ctx->getParent();
  1031. return Ctx->getPrimaryContext();
  1032. }
  1033. bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
  1034. // For non-file contexts, this is equivalent to Equals.
  1035. if (!isFileContext())
  1036. return O->Equals(this);
  1037. do {
  1038. if (O->Equals(this))
  1039. return true;
  1040. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
  1041. if (!NS || !NS->isInline())
  1042. break;
  1043. O = NS->getParent();
  1044. } while (O);
  1045. return false;
  1046. }
  1047. void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
  1048. DeclContext *PrimaryDC = this->getPrimaryContext();
  1049. DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
  1050. // If the decl is being added outside of its semantic decl context, we
  1051. // need to ensure that we eagerly build the lookup information for it.
  1052. PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
  1053. }
  1054. void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
  1055. bool Recoverable) {
  1056. assert(this == getPrimaryContext() && "expected a primary DC");
  1057. // Skip declarations within functions.
  1058. // FIXME: We shouldn't need to build lookup tables for function declarations
  1059. // ever, and we can't do so correctly because we can't model the nesting of
  1060. // scopes which occurs within functions. We use "qualified" lookup into
  1061. // function declarations when handling friend declarations inside nested
  1062. // classes, and consequently accept the following invalid code:
  1063. //
  1064. // void f() { void g(); { int g; struct S { friend void g(); }; } }
  1065. if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
  1066. return;
  1067. // Skip declarations which should be invisible to name lookup.
  1068. if (shouldBeHidden(D))
  1069. return;
  1070. // If we already have a lookup data structure, perform the insertion into
  1071. // it. If we might have externally-stored decls with this name, look them
  1072. // up and perform the insertion. If this decl was declared outside its
  1073. // semantic context, buildLookup won't add it, so add it now.
  1074. //
  1075. // FIXME: As a performance hack, don't add such decls into the translation
  1076. // unit unless we're in C++, since qualified lookup into the TU is never
  1077. // performed.
  1078. if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
  1079. ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
  1080. (getParentASTContext().getLangOpts().CPlusPlus ||
  1081. !isTranslationUnit()))) {
  1082. // If we have lazily omitted any decls, they might have the same name as
  1083. // the decl which we are adding, so build a full lookup table before adding
  1084. // this decl.
  1085. buildLookup();
  1086. makeDeclVisibleInContextImpl(D, Internal);
  1087. } else {
  1088. LookupPtr.setInt(true);
  1089. }
  1090. // If we are a transparent context or inline namespace, insert into our
  1091. // parent context, too. This operation is recursive.
  1092. if (isTransparentContext() || isInlineNamespace())
  1093. getParent()->getPrimaryContext()->
  1094. makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
  1095. Decl *DCAsDecl = cast<Decl>(this);
  1096. // Notify that a decl was made visible unless we are a Tag being defined.
  1097. if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
  1098. if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
  1099. L->AddedVisibleDecl(this, D);
  1100. }
  1101. void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
  1102. // Find or create the stored declaration map.
  1103. StoredDeclsMap *Map = LookupPtr.getPointer();
  1104. if (!Map) {
  1105. ASTContext *C = &getParentASTContext();
  1106. Map = CreateStoredDeclsMap(*C);
  1107. }
  1108. // If there is an external AST source, load any declarations it knows about
  1109. // with this declaration's name.
  1110. // If the lookup table contains an entry about this name it means that we
  1111. // have already checked the external source.
  1112. if (!Internal)
  1113. if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
  1114. if (hasExternalVisibleStorage() &&
  1115. Map->find(D->getDeclName()) == Map->end())
  1116. Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
  1117. // Insert this declaration into the map.
  1118. StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
  1119. if (DeclNameEntries.isNull()) {
  1120. DeclNameEntries.setOnlyValue(D);
  1121. return;
  1122. }
  1123. if (DeclNameEntries.HandleRedeclaration(D)) {
  1124. // This declaration has replaced an existing one for which
  1125. // declarationReplaces returns true.
  1126. return;
  1127. }
  1128. // Put this declaration into the appropriate slot.
  1129. DeclNameEntries.AddSubsequentDecl(D);
  1130. }
  1131. /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
  1132. /// this context.
  1133. DeclContext::udir_iterator_range
  1134. DeclContext::getUsingDirectives() const {
  1135. // FIXME: Use something more efficient than normal lookup for using
  1136. // directives. In C++, using directives are looked up more than anything else.
  1137. lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
  1138. return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
  1139. reinterpret_cast<udir_iterator>(Result.end()));
  1140. }
  1141. //===----------------------------------------------------------------------===//
  1142. // Creation and Destruction of StoredDeclsMaps. //
  1143. //===----------------------------------------------------------------------===//
  1144. StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
  1145. assert(!LookupPtr.getPointer() && "context already has a decls map");
  1146. assert(getPrimaryContext() == this &&
  1147. "creating decls map on non-primary context");
  1148. StoredDeclsMap *M;
  1149. bool Dependent = isDependentContext();
  1150. if (Dependent)
  1151. M = new DependentStoredDeclsMap();
  1152. else
  1153. M = new StoredDeclsMap();
  1154. M->Previous = C.LastSDM;
  1155. C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
  1156. LookupPtr.setPointer(M);
  1157. return M;
  1158. }
  1159. void ASTContext::ReleaseDeclContextMaps() {
  1160. // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
  1161. // pointer because the subclass doesn't add anything that needs to
  1162. // be deleted.
  1163. StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
  1164. }
  1165. void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
  1166. while (Map) {
  1167. // Advance the iteration before we invalidate memory.
  1168. llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
  1169. if (Dependent)
  1170. delete static_cast<DependentStoredDeclsMap*>(Map);
  1171. else
  1172. delete Map;
  1173. Map = Next.getPointer();
  1174. Dependent = Next.getInt();
  1175. }
  1176. }
  1177. DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
  1178. DeclContext *Parent,
  1179. const PartialDiagnostic &PDiag) {
  1180. assert(Parent->isDependentContext()
  1181. && "cannot iterate dependent diagnostics of non-dependent context");
  1182. Parent = Parent->getPrimaryContext();
  1183. if (!Parent->LookupPtr.getPointer())
  1184. Parent->CreateStoredDeclsMap(C);
  1185. DependentStoredDeclsMap *Map
  1186. = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
  1187. // Allocate the copy of the PartialDiagnostic via the ASTContext's
  1188. // BumpPtrAllocator, rather than the ASTContext itself.
  1189. PartialDiagnostic::Storage *DiagStorage = 0;
  1190. if (PDiag.hasStorage())
  1191. DiagStorage = new (C) PartialDiagnostic::Storage;
  1192. DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
  1193. // TODO: Maybe we shouldn't reverse the order during insertion.
  1194. DD->NextDiagnostic = Map->FirstDiagnostic;
  1195. Map->FirstDiagnostic = DD;
  1196. return DD;
  1197. }