DeclBase.cpp 41 KB

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